From 755f3122579a1ff52c452560e0d7d7fbf9bb0b6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 27 Jan 2022 15:11:03 +0100 Subject: [PATCH 01/23] Major changes to project structure --- VirtualRealty-Free.iml | 31 --- pom.xml | 395 +++++++++++++++++----------------- src/main/resources/plugin.yml | 2 +- 3 files changed, 204 insertions(+), 224 deletions(-) delete mode 100644 VirtualRealty-Free.iml diff --git a/VirtualRealty-Free.iml b/VirtualRealty-Free.iml deleted file mode 100644 index 88b5798..0000000 --- a/VirtualRealty-Free.iml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - PAPER - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index c8a3389..5153902 100644 --- a/pom.xml +++ b/pom.xml @@ -1,192 +1,203 @@ - - - 4.0.0 - - me.plytki - VirtualRealty - 1.7.1 - jar - - VirtualRealty - - A plot creation and management plugin for Minecraft - - 1.8 - UTF-8 - - - - - - maven-compiler-plugin - 3.8.1 - - ${java.version} - ${java.version} - - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.4 - - - package - - shade - - - false - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.1 - - - - org.bstats - me.plytki.virtualrealty.utils - - org.apache.commons.io - me.plytki.virtualrealty.utils - - - org.h2 - me.plytki.virtualrealty.utils.h2 - - - - - - package - - shade - - - - - *:* - - META-INF/** - - - - - - - - - - - src/main/resources - true - - - - - - - papermc-repo - https://papermc.io/repo/repository/maven-public/ - - - sonatype - https://oss.sonatype.org/content/groups/public/ - - - panda-repository - https://repo.panda-lang.org/ - - - okaeri-repo - https://storehouse.okaeri.eu/repository/maven-public/ - - - dynmap-repo - http://repo.mikeprimm.com/ - - - placeholderapi - http://repo.extendedclip.com/content/repositories/placeholderapi/ - - - - - - org.jetbrains - annotations - 21.0.1 - provided - - - org.spigot - spigot - 1.13.2 - provided - - - org.bukkit - craftbukkit - 1.13.2-R0.1-SNAPSHOT - provided - - - com.h2database - h2 - 1.4.200 - compile - - - org.bstats - bstats-bukkit - 2.2.1 - compile - - - eu.okaeri - okaeri-configs-yaml-bukkit - 3.1.0 - - - eu.okaeri - okaeri-configs-serdes-commons - 3.1.0 - - - eu.okaeri - okaeri-configs-validator-okaeri - 3.1.0 - - - commons-io - commons-io - 2.11.0 - compile - - - org.apache.commons - commons-lang3 - 3.12.0 - compile - - - org.dynmap - dynmap-api - 2.0 - provided - - - me.clip - placeholderapi - 2.10.9 - provided - - - - + + + 4.0.0 + + com.modnmetl + virtualrealty + 1.8.0 + jar + + A plot creation and management plugin for Minecraft + + + 1.8 + UTF-8 + + + + + build + + ../target + + + + + + + + maven-compiler-plugin + 3.8.1 + + ${java.version} + ${java.version} + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + package + + shade + + + false + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.1 + + + + org.bstats + com.modnmetl.virtualrealty.utils + + + org.apache.commons.io + com.modnmetl.virtualrealty.utils + + + + + + package + + shade + + + + + *:* + + META-INF/** + + + + + + + + + + + src/main/resources + true + + + + + + + papermc-repo + https://papermc.io/repo/repository/maven-public/ + + + sonatype + https://oss.sonatype.org/content/groups/public/ + + + panda-repository + https://repo.panda-lang.org/ + + + okaeri-repo + https://storehouse.okaeri.eu/repository/maven-public/ + + + dynmap-repo + http://repo.mikeprimm.com/ + + + placeholderapi + http://repo.extendedclip.com/content/repositories/placeholderapi/ + + + + + + org.jetbrains + annotations + 21.0.1 + provided + + + org.spigot + spigot + 1.13.2 + provided + + + org.bukkit + craftbukkit + 1.13.2-R0.1-SNAPSHOT + provided + + + + + + + + + org.bstats + bstats-bukkit + 2.2.1 + compile + + + eu.okaeri + okaeri-configs-yaml-bukkit + 3.1.0 + + + eu.okaeri + okaeri-configs-serdes-commons + 3.1.0 + + + eu.okaeri + okaeri-configs-validator-okaeri + 3.1.0 + + + commons-io + commons-io + 2.11.0 + compile + + + org.apache.commons + commons-lang3 + 3.12.0 + compile + + + org.dynmap + dynmap-api + 2.0 + provided + + + me.clip + placeholderapi + 2.10.9 + provided + + + com.modnmetl + virtualrealty-premium + ${project.version} + provided + + + + diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 5cb9b40..f7c37b5 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ name: VirtualRealty version: ${project.version} -main: me.plytki.virtualrealty.VirtualRealty +main: com.modnmetl.virtualrealty.VirtualRealty prefix: Virtual Realty authors: [ plytki ] api-version: 1.13 From 87d0373793e195609f7f2fa1ba20fe3f3d44274f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 27 Jan 2022 15:18:00 +0100 Subject: [PATCH 02/23] Major changes to project structure --- .../modnmetl/virtualrealty/VirtualRealty.java | 567 +++++++++++++ .../virtualrealty/commands/PlotCommand.java | 369 ++++++++ .../commands/VirtualRealtyCommand.java | 734 ++++++++++++++++ .../configs/MessagesConfiguration.java | 69 ++ .../configs/PluginConfiguration.java | 174 ++++ .../configs/SizesConfiguration.java | 86 ++ .../virtualrealty/enums/Direction.java | 45 + .../modnmetl/virtualrealty/enums/Flag.java | 33 + .../virtualrealty/enums/HighlightType.java | 9 + .../virtualrealty/enums/Permission.java | 24 + .../virtualrealty/enums/PlotSize.java | 86 ++ .../exceptions/MaterialMatchException.java | 9 + .../listeners/ProtectionListener.java | 472 +++++++++++ .../listeners/VirtualListener.java | 22 + .../listeners/plot/BorderListener.java | 44 + .../listeners/plot/PlotListener.java | 100 +++ .../listeners/world/WorldListener.java | 49 ++ .../virtualrealty/managers/PlotManager.java | 186 ++++ .../virtualrealty/objects/Cuboid.java | 187 ++++ .../modnmetl/virtualrealty/objects/Plot.java | 796 ++++++++++++++++++ .../objects/math/BlockVector2.java | 44 + .../objects/math/BlockVector3.java | 59 ++ .../registry/VirtualPlaceholders.java | 123 +++ .../com/modnmetl/virtualrealty/sql/SQL.java | 120 +++ .../utils/ConfigurationFactory.java | 46 + .../virtualrealty/utils/Permissions.java | 27 + .../virtualrealty/utils/PlotUtil.java | 41 + .../virtualrealty/utils/ProtectionUtil.java | 40 + .../virtualrealty/utils/Reflections.java | 271 ++++++ .../virtualrealty/utils/SafeUtil.java | 27 + .../virtualrealty/utils/SchematicUtil.java | 150 ++++ .../virtualrealty/utils/UUIDUtils.java | 16 + .../virtualrealty/utils/UpdateChecker.java | 39 + .../virtualrealty/utils/data/Data.java | 31 + .../utils/multiversion/Chat.java | 44 + .../utils/multiversion/VMaterial.java | 60 ++ virtualrealty.iml | 43 + 37 files changed, 5242 insertions(+) create mode 100644 src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/Direction.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/Flag.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/HighlightType.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/Permission.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/exceptions/MaterialMatchException.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/Plot.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector2.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/sql/SQL.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/Permissions.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/UUIDUtils.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/UpdateChecker.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java create mode 100644 virtualrealty.iml diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java new file mode 100644 index 0000000..c6a6618 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -0,0 +1,567 @@ +package com.modnmetl.virtualrealty; + +import com.modnmetl.virtualrealty.commands.PlotCommand; +import com.modnmetl.virtualrealty.commands.VirtualRealtyCommand; +import com.modnmetl.virtualrealty.configs.MessagesConfiguration; +import com.modnmetl.virtualrealty.configs.PluginConfiguration; +import com.modnmetl.virtualrealty.configs.SizesConfiguration; +import com.modnmetl.virtualrealty.enums.Flag; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.exceptions.MaterialMatchException; +import com.modnmetl.virtualrealty.listeners.plot.BorderListener; +import com.modnmetl.virtualrealty.listeners.plot.PlotListener; +import com.modnmetl.virtualrealty.listeners.world.WorldListener; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.premiumloader.PremiumLoader; +import com.modnmetl.virtualrealty.registry.VirtualPlaceholders; +import com.modnmetl.virtualrealty.sql.SQL; +import com.modnmetl.virtualrealty.utils.ConfigurationFactory; +import com.modnmetl.virtualrealty.utils.SchematicUtil; +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import com.modnmetl.virtualrealty.listeners.ProtectionListener; +import com.modnmetl.virtualrealty.utils.UpdateChecker; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.LineIterator; +import org.bstats.bukkit.Metrics; +import org.bstats.charts.AdvancedPie; +import org.bstats.charts.SimplePie; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.permissions.Permission; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; +import org.dynmap.DynmapAPI; +import org.dynmap.markers.MarkerIcon; +import org.dynmap.markers.MarkerSet; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.Statement; +import java.util.*; +import java.util.concurrent.Callable; + +public final class VirtualRealty extends JavaPlugin { + + public final Locale locale = Locale.getDefault(); + public final List availableLocales = new ArrayList<>(Arrays.asList(new Locale("en", "GB"), new Locale("es", "ES"), new Locale("pl", "PL"))); + + //CORE + private static VirtualRealty instance; + public static final String PREFIX = "§a§lVR §8§l» §7"; + public static ArrayList tasks = new ArrayList<>(); + private static final ArrayList preVersions = new ArrayList<>(); + public static boolean isLegacy = false; + public static final Permission GLOBAL_PERMISSION = new Permission("virtualrealty"); + + //FILES + public static File plotsFolder; + public static File plotsSchemaFolder; + public PluginConfiguration pluginConfiguration; + public SizesConfiguration sizesConfiguration; + public MessagesConfiguration messagesConfiguration; + private final File pluginConfigurationFile = new File(this.getDataFolder(), "config.yml"); + private final File sizesConfigurationFile = new File(this.getDataFolder(), "sizes.yml"); + private final File languagesDirectory = new File(this.getDataFolder(), "messages"); + + //DYNMAP API + public static boolean isDynmapPresent = false; + public static DynmapAPI dapi = null; + public static MarkerSet markerset = null; + public static MarkerIcon markerIcon = null; + + @Override + public void onEnable() { + instance = this; + if (checkLegacyVersions()) { + isLegacy = true; + } + String[] updateCheck = UpdateChecker.getUpdate(); + if (updateCheck != null) { + if (!updateCheck[0].equals(this.getDescription().getVersion())) { + this.getLogger().info("A newer version is available!"); + this.getLogger().info("The current version you use: " + this.getDescription().getVersion()); + this.getLogger().info("Latest version available: " + updateCheck[0]); + this.getLogger().info("Download link: https://www.spigotmc.org/resources/virtual-realty.95599/"); + } else { + this.getLogger().info("Plugin is up to date!"); + } + } + try { + checkConfig(); + checkSizesConfig(); + } catch (IOException e) { + e.printStackTrace(); + } + plotsFolder = new File(getInstance().getDataFolder().getAbsolutePath(), "plots"); + plotsFolder.mkdirs(); + plotsSchemaFolder = new File(plotsFolder.getAbsolutePath(), "primary-terrain"); + plotsSchemaFolder.mkdirs(); + spawnLocales(); + reformatConfig(); + reloadConfigs(); + if (!pluginConfiguration.licenseKey.isEmpty()) { + //LOAD premium + } + registerMetrics(); + loadSizesConfiguration(); + connectToDatabase(); + PlotManager.loadPlots(); + if (pluginConfiguration.dynmapMarkers) { + registerDynmap(); + } + reloadFlags(); + registerCommands(); + registerListeners(); + registerTasks(); + checkForOldSchemas(); + //convertOldDatabase(); + if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")){ + new VirtualPlaceholders(this).register(); + debug("Registered new placeholders"); + } + debug("Server version: " + this.getServer().getBukkitVersion() + " | " + this.getServer().getVersion()); + try { + Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader"); + new PremiumLoader(); + } catch (ClassNotFoundException ignored) { + + } + } + + @Override + public void onDisable() { + PlotManager.plots.forEach(Plot::update); + tasks.forEach(BukkitTask::cancel); + SQL.closeConnection(); + pluginConfiguration.save(); + } + + public static void debug(String debugMessage) { + if (VirtualRealty.getPluginConfiguration().debugMode) + VirtualRealty.getInstance().getLogger().warning("DEBUG-MODE > " + debugMessage); + } + + public void spawnLocales() { + for (Locale availableLocale : availableLocales) { + if (availableLocale.toString().equalsIgnoreCase("en_GB")) { + File messagesConfigurationFile = new File(languagesDirectory, "messages_en_GB.yml"); + ConfigurationFactory configFactory = new ConfigurationFactory(); + configFactory.createMessagesConfiguration(messagesConfigurationFile); + } else { + File languageConfigurationFile = new File(languagesDirectory, "messages_" + availableLocale + ".yml"); + if (!languageConfigurationFile.exists()) { + saveResource("messages_" + availableLocale + ".yml", true); + File file = new File(this.getDataFolder(), "messages_" + availableLocale + ".yml"); + try { + FileUtils.moveFile(file, languageConfigurationFile); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + +// public void convertOldDatabase() { +// File oldDatabase = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.mv.db"); +// if (oldDatabase.exists()) { +// try { +// SQL.closeConnection(); +// Connection connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.db"); +// SQL.setConnection(connection); +// Statement statement = connection.createStatement(); +// SQL.setStatement(statement); +// statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); +// for (Plot plot : PlotManager.plots) { +// plot.insert(); +// } +// FileUtils.deleteQuietly(oldDatabase); +// debug("H2 database converted successfully to SQLITE"); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// } + + public void reloadConfigs() { + try { + ConfigurationFactory configFactory = new ConfigurationFactory(); + pluginConfiguration = configFactory.createPluginConfiguration(pluginConfigurationFile); + File messagesConfigurationFile = new File(languagesDirectory, "messages_" + pluginConfiguration.locale + ".yml"); + sizesConfiguration = configFactory.createSizesConfiguration(sizesConfigurationFile); + messagesConfiguration = configFactory.createMessagesConfiguration(messagesConfigurationFile); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void reloadFlags() { + if (pluginConfiguration.allowOutPlotBuild) { + for (Flag.World value : Flag.World.values()) { + value.setAllowed(true); + } + } else { + for (Flag.World value : Flag.World.values()) { + value.setAllowed(false); + } + } + } + + public static void checkForOldSchemas() { + for (Plot plot : PlotManager.plots) { + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plot.getID() + ".schem"); + if (f.exists()) { + List data = SchematicUtil.oldLoad(plot.getID()); + FileUtils.deleteQuietly(f); + SchematicUtil.save(plot.getID(), data.toArray(new String[0])); + debug("Converted Plot #" + plot.getID() + " | File: " + f.getName()); + } + } + } + + public void registerDynmap() { + new BukkitRunnable() { + @Override + public void run() { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); + if (plugin != null) { + isDynmapPresent = true; + } + if (plugin != null && plugin.isEnabled()) { + dapi = (DynmapAPI) plugin; + if (dapi.markerAPIInitialized()) { + markerset = dapi.getMarkerAPI().getMarkerSet("virtualrealty.plots"); + if (markerset == null) + markerset = dapi.getMarkerAPI().createMarkerSet("virutalrealty.plots", "Plots", dapi.getMarkerAPI().getMarkerIcons(), false); + for (MarkerSet markerSet : dapi.getMarkerAPI().getMarkerSets()) { + if (markerSet.getMarkerSetLabel().equalsIgnoreCase("Plots")) { + markerset = markerSet; + } + } + try { + if (dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon") == null) { + InputStream in = this.getClass().getResourceAsStream("/ploticon.png"); + if (in.available() > 0) { + markerIcon = dapi.getMarkerAPI().createMarkerIcon("virtualrealty_main_icon", "Plots", in); + } + } + else { + markerIcon = dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon"); + } + } + catch (IOException ex) {} + VirtualRealty.debug("Registering plots markers.."); + for (Plot plot : PlotManager.plots) { + PlotManager.resetPlotMarker(plot); + } + VirtualRealty.debug("Registered plots markers"); + this.cancel(); + } + } + } + }.runTaskTimer(this, 20, 20*5); + } + + + private void registerCommands() { + this.getCommand("plot").setExecutor(new PlotCommand()); + this.getCommand("virtualrealty").setExecutor(new VirtualRealtyCommand()); + } + + private void registerListeners() { + new BorderListener(this).registerEvents(); + new PlotListener(this).registerEvents(); + new ProtectionListener(this).registerEvents(); + new WorldListener(this).registerEvents(); + debug("Registered listeners"); + } + + private void registerTasks() { + //debug("Registered tasks"); + } + + private void registerMetrics() { + Metrics metrics = new Metrics(this, 14066); + metrics.addCustomChart(new SimplePie("used_database", () -> pluginConfiguration.dataModel.name())); + metrics.addCustomChart(new AdvancedPie("created_plots", new Callable>() { + @Override + public Map call() throws Exception { + Map valueMap = new HashMap(); + int smallPlots = 0; + int mediumPlots = 0; + int largePlots = 0; + int customPlots = 0; + for (Plot plot : PlotManager.plots) { + switch (plot.getPlotSize()) { + case SMALL: { + smallPlots++; + break; + } + case MEDIUM: { + mediumPlots++; + break; + } + case LARGE: { + largePlots++; + break; + } + case CUSTOM: { + customPlots++; + break; + } + default: + throw new IllegalStateException("Unexpected value: " + plot.getPlotSize()); + } + } + valueMap.put("SMALL", smallPlots); + valueMap.put("MEDIUM", mediumPlots); + valueMap.put("LARGE", largePlots); + valueMap.put("CUSTOM", customPlots); + return valueMap; + } + })); + debug("Registered metrics"); + } + + private void connectToDatabase() { + SQL.connect(); + SQL.createTables(); + debug("Connected to database"); + } + + public void loadSizesConfiguration() { + for (PlotSize plotSize : PlotSize.values()) { + if (plotSize == PlotSize.CUSTOM) return; + SizesConfiguration.PlotSizes.Size classSize = null; + switch (plotSize) { + case SMALL: { + classSize = sizesConfiguration.plotSizes.SMALL; + break; + } + case MEDIUM: { + classSize = sizesConfiguration.plotSizes.MEDIUM; + break; + } + case LARGE: { + classSize = sizesConfiguration.plotSizes.LARGE; + break; + } + } + Material floorMaterial; + try { + floorMaterial = VMaterial.catchMaterial(classSize.floorMaterial.toUpperCase()); + } catch (MaterialMatchException e) { + floorMaterial = VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK; + e.printStackTrace(); + //throw new MaterialMatchException("Couldn't parse floor-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK)); + } + Material borderMaterial; + try { + borderMaterial = VMaterial.catchMaterial(classSize.borderMaterial.toUpperCase()); + } catch (MaterialMatchException e) { + borderMaterial = VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB; + e.printStackTrace(); + //throw new MaterialMatchException("Couldn't parse border-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB)); + } + plotSize.setFloorMaterial(floorMaterial); + plotSize.setFloorData(classSize.floorData); + plotSize.setBorderMaterial(borderMaterial); + plotSize.setBorderData(classSize.borderData); + plotSize.setLength(classSize.length); + plotSize.setWidth(classSize.width); + plotSize.setHeight(classSize.height); + } + debug("Loaded sizes config"); + } + + public static VirtualRealty getInstance() { + return instance; + } + + public static PluginConfiguration getPluginConfiguration() { + return VirtualRealty.getInstance().pluginConfiguration; + } + + public static File getPluginConfigurationFile() { + return VirtualRealty.getInstance().pluginConfigurationFile; + } + + public static SizesConfiguration getSizesConfiguration() { + return VirtualRealty.getInstance().sizesConfiguration; + } + + public static File getSizesConfigurationFile() { + return VirtualRealty.getInstance().sizesConfigurationFile; + } + + public static MessagesConfiguration getMessages() { + return getInstance().messagesConfiguration; + } + + public boolean checkLegacyVersions() { + setPostVersions(); + for (String preVersion : preVersions) { + if (Bukkit.getBukkitVersion().toLowerCase().contains(preVersion.toLowerCase())) { + return true; + } + } + return false; + } + + public static Locale getLocale() { + return getInstance().locale; + } + + public void setPostVersions() { + preVersions.add("1.12"); + preVersions.add("1.11"); + preVersions.add("1.10"); + preVersions.add("1.9"); + preVersions.add("1.8"); + } + + public void reformatConfig() { + File configFile = new File(this.getDataFolder(), "config.yml"); + File newFile = new File(this.getDataFolder(), "config.yml.new"); + if (configFile.exists()) { + try { + List lines = FileUtils.readLines(configFile, StandardCharsets.UTF_8); + for (int i = 0; i < lines.size(); i++) { + if (lines.get(i).startsWith("force-plot-gamemode:")) { + lines.set(i, lines.get(i).replaceAll("force-plot-gamemode:", "lock-plot-gamemode:")); + } + } + FileUtils.writeLines(newFile, lines); + FileUtils.deleteQuietly(configFile); + newFile.createNewFile(); + File newConfigFile = new File(this.getDataFolder(), "config.yml"); + FileUtils.copyFile(newFile, newConfigFile); + FileUtils.deleteQuietly(newFile); + } catch (IOException e) { + + } + } + } + + public void checkConfig() throws IOException { + File oldConfigFile = new File(this.getDataFolder(), "config.yml"); + if (!oldConfigFile.exists()) return; + String version = null; + boolean isOldVersion = true; + boolean updateConfigVersion = false; + FileReader fileReader = new FileReader(this.pluginConfigurationFile); + BufferedReader reader = new BufferedReader(fileReader); + String latestLine; + while((latestLine = reader.readLine()) != null) { + if (latestLine.contains("config-version")) { + version = latestLine.replaceAll("config-version: ", ""); + isOldVersion = false; + } + } + fileReader.close(); + reader.close(); + if (version == null) { + System.err.println(" "); + this.getLogger().warning("Config has been reset due to major config changes!"); + this.getLogger().warning("Old config has been renamed to config.yml.old"); + this.getLogger().warning("Please update your config file!"); + System.err.println(" "); + } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { + updateConfigVersion = true; + this.getLogger().info("Config has been updated!"); + } + + // save old config file + if (isOldVersion) { + File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml.old"); + if (newConfigFile.exists()) { + newConfigFile.delete(); + } + FileUtils.copyFile(oldConfigFile, newConfigFile); + oldConfigFile.delete(); + } + +// update config version + if (updateConfigVersion) { + List lines = new ArrayList<>(); + LineIterator iterator = FileUtils.lineIterator(oldConfigFile); + while (iterator.hasNext()) { + String line = iterator.next(); + lines.add(line); + } + for (String line : new ArrayList<>(lines)) { + if (line.contains("config-version")) { + int index = lines.indexOf(line); + lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); + } + } + File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml"); + FileUtils.deleteQuietly(newConfigFile); + FileUtils.writeLines(newConfigFile, lines); + newConfigFile.createNewFile(); + } + } + + public void checkSizesConfig() throws IOException { + File oldConfigFile = new File(this.getDataFolder(), "sizes.yml"); + if (!oldConfigFile.exists()) return; + String version = null; + boolean isOldVersion = true; + boolean updateConfigVersion = false; + BufferedReader reader = new BufferedReader(new FileReader(this.sizesConfigurationFile)); + String latestLine; + while((latestLine = reader.readLine()) != null) { + if (latestLine.contains("config-version")) { + version = latestLine.replaceAll("config-version: ", ""); + isOldVersion = false; + } + } + reader.close(); + if (version == null) { + System.err.println(" "); + this.getLogger().warning("Config has been reset due to major config changes!"); + this.getLogger().warning("Old config has been renamed to sizes.yml.old"); + this.getLogger().warning("Please update your config file!"); + System.err.println(" "); + } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { + updateConfigVersion = true; + this.getLogger().info("Plot sizes config has been updated!"); + } + + // save old config file + if (isOldVersion) { + File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml.old"); + if (newConfigFile.exists()) { + newConfigFile.delete(); + } + FileUtils.copyFile(oldConfigFile, newConfigFile); + oldConfigFile.delete(); + } + + // update config version + if (updateConfigVersion) { + List lines = new ArrayList<>(); + LineIterator iterator = FileUtils.lineIterator(oldConfigFile); + while (iterator.hasNext()) { + String line = iterator.next(); + lines.add(line); + } + for (String line : new ArrayList<>(lines)) { + if (line.contains("config-version")) { + int index = lines.indexOf(line); + lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); + } + } + File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml"); + FileUtils.deleteQuietly(newConfigFile); + FileUtils.writeLines(newConfigFile, lines); + newConfigFile.createNewFile(); + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java new file mode 100644 index 0000000..ce69dfa --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java @@ -0,0 +1,369 @@ +package com.modnmetl.virtualrealty.commands; + +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Plot; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public class PlotCommand implements CommandExecutor { + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (!(sender instanceof Player)) { + return false; + } + Player p = ((Player) sender); + if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { + printHelp(sender); + return false; + } + if (args.length == 1) { + switch (args[0].toUpperCase()) { + case "ADD": { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot add §8<§7player§8> §8<§7plot§8>"); + break; + } + case "KICK": { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot kick §8<§7player§8> §8<§7plot§8>"); + break; + } + case "TP": { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot tp §8<§7plotID§8>"); + break; + } + case "GM": { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot gm §8<§7gamemode§8>"); + break; + } + case "INFO": { + Plot plot = PlotManager.getPlot(p.getLocation()); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); + return false; + } + printInfo(sender, plot); + break; + } + case "LIST": { + boolean hasPlot = false; + for (Plot plot : PlotManager.plots) { + if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()) && plot.getOwnedUntilDate().isAfter(LocalDateTime.now())) { + hasPlot = true; + break; + } + } + boolean isMember = false; + for (Plot plot : PlotManager.plots) { + if (plot.getMembers().contains(p.getUniqueId())) { + isMember = true; + break; + } + } + if (!hasPlot && !isMember) { + sender.sendMessage(VirtualRealty.PREFIX + "§cYou don't have any plots!"); + return false; + } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" "); + if (hasPlot) { + sender.sendMessage("§7§m "); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + for (Plot plot : PlotManager.plots) { + if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + StringBuilder ownedBy = new StringBuilder(); + ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); + boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); + for (int i = ownedBy.length(); i < 16; i++) { + ownedBy.append(" "); + } + StringBuilder size = new StringBuilder(plot.getPlotSize().name()); + for (int i = size.length(); i < 6; i++) { + size.append(" "); + } + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + sender.sendMessage(textComponent.toLegacyText()); + } + } + sender.sendMessage("§7§m "); + } + if (isMember) { + sender.sendMessage(" "); + sender.sendMessage("§7 §fMember of §8§l↴"); + sender.sendMessage(" "); + sender.sendMessage("§7§m "); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + for (Plot plot : PlotManager.plots) { + if (plot.getPlotOwner() != null && !plot.getPlotOwner().getUniqueId().equals(p.getUniqueId()) && plot.getMembers().contains(p.getUniqueId())) { + StringBuilder ownedBy = new StringBuilder(); + ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); + boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); + for (int i = ownedBy.length(); i < 16; i++) { + ownedBy.append(" "); + } + StringBuilder size = new StringBuilder(plot.getPlotSize().name()); + for (int i = size.length(); i < 6; i++) { + size.append(" "); + } + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + ownedBy + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + sender.sendMessage(textComponent.toLegacyText()); + } + } + sender.sendMessage("§7§m "); + } + break; + } + default: { + printHelp(sender); + } + } + } + if (args.length >= 2) { + switch (args[0].toUpperCase()) { + case "ADD": { + if (args.length == 3) { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[2]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); + return false; + } + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return false; + } + if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantAddYourself); + return false; + } + if (plot.getMembers().contains(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().alreadyInMembers); + return false; + } + plot.addMember(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerAdd.replaceAll("%player%", offlinePlayer.getName())); + return false; + } + break; + } + case "KICK": { + if (args.length == 3) { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[2]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); + return false; + } + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return false; + } + if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantKickYourself); + return false; + } + if (!plot.getMembers().contains(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notInMembers); + return false; + } + plot.removeMember(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerKick.replaceAll("%player%", offlinePlayer.getName())); + return false; + } + break; + } + case "TP": { + if (args.length == 2) { + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (!plot.hasPlotMembership(p)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); + return false; + } + if (plot.isOwnershipExpired()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return false; + } + Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); + loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); + p.teleport(loc); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); + } + break; + } + case "GM": { + if (VirtualRealty.getPluginConfiguration().lockPlotGameMode) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeFeatureDisabled); + return false; + } + GameMode gameMode; + int gameModeID; + try { + gameMode = GameMode.valueOf(args[1]); + gameModeID = gameMode.getValue(); + } catch (IllegalArgumentException e) { + try { + gameModeID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException ex) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().incorrectGamemode); + return false; + } + } + GameMode defaultGamemode = VirtualRealty.getInstance().getServer().getDefaultGameMode(); + GameMode configGamemode = VirtualRealty.getPluginConfiguration().getGameMode(); + if (!(gameModeID != configGamemode.getValue() && gameModeID != defaultGamemode.getValue())) { + gameMode = GameMode.getByValue(Integer.parseInt(args[1])); + } else { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeDisabled); + return false; + } + Plot plot = PlotManager.getBorderedPlot(p.getLocation()); + if (plot != null) { + if (!plot.hasPlotMembership(p)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); + } else { + if (plot.isOwnershipExpired()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } else { + if (p.getGameMode().equals(gameMode)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeAlreadySelected); + return false; + } + if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { + plot.setSelectedGameMode(gameMode); + } + p.setGameMode(gameMode); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeSwitched); + } + } + } else { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); + } + break; + } + default: { + printHelp(sender); + } + } + } + return false; + } + + private static void printHelp(CommandSender sender) { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot add §8- §7Adds a member"); + sender.sendMessage(" §a/plot kick §8- §7Kicks a member"); + sender.sendMessage(" §a/plot list §8- §7Shows your plots"); + sender.sendMessage(" §a/plot info §8- §7Shows plot info"); + sender.sendMessage(" §a/plot gm §8- §7Changes gamemode"); + sender.sendMessage(" §a/plot tp §8- §7Teleports to the plot"); + } + + private static void printInfo(CommandSender sender, Plot plot) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); +// String assignedBy = VirtualRealty.getMessages().notAssigned; +// if (plot.getAssignedBy() != null) { +// switch (plot.getAssignedBy().toUpperCase()) { +// case "CONSOLE": { +// assignedBy = VirtualRealty.getMessages().assignedByConsole; +// break; +// } +// case "SHOP_PURCHASE": { +// assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; +// break; +// } +// default: { +// OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); +// assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); +// } +// } +// } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); + sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); + if (plot.getMembers().size() != 0) { + sender.sendMessage(" §7Members §8§l↴"); + for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { + sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); + } + } + //sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); + sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); + sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); + sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); + sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); + sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); + //sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); + //sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); + //sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); + //sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); + //sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java new file mode 100644 index 0000000..ba2a7f6 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java @@ -0,0 +1,734 @@ +package com.modnmetl.virtualrealty.commands; + +import com.modnmetl.virtualrealty.enums.Direction; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.utils.Permissions; +import com.modnmetl.virtualrealty.utils.PlotUtil; +import com.modnmetl.virtualrealty.utils.UUIDUtils; +import com.modnmetl.virtualrealty.utils.multiversion.Chat; +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Plot; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.*; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permission; +import org.jetbrains.annotations.NotNull; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.UUID; + +public class VirtualRealtyCommand implements CommandExecutor { + + private static final Permission commandPermission = new Permission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".vrplot"); + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + Permission tempPermission = new Permission(commandPermission.getName()); + if (!Permissions.hasPermission(sender, tempPermission.getName())) return false; + Player p = null; + Location location = null; + if(sender instanceof Player) { + p = (Player)sender; + location = p.getLocation(); + location.add(0, -1, 0); + } + if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { + printHelp(sender); + return false; + } + if (args.length == 1) { + switch (args[0].toUpperCase()) { + case "CREATE": { + if (!Permissions.hasPermission(sender, tempPermission, "create")) return false; + if (sender instanceof Player) { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot create §8<§7small/medium/large§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); + sender.sendMessage(" §a/vrplot create §8<§7length§8> §8<§7width§8> §8<§7height§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); + } + break; + } + case "REMOVE": { + if (!Permissions.hasPermission(sender, tempPermission, "remove")) return false; + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot remove §8<§7plotID§8>"); + break; + } + case "SET": { + if (!Permissions.hasPermission(sender, tempPermission, "set")) return false; + printSetHelp(sender); + break; + } + case "ASSIGN": { + if (!Permissions.hasPermission(sender, tempPermission, "assign")) return false; + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot assign §8<§7plotID§8> §8<§7username§8>"); + break; + } + case "UNASSIGN": { + if (!Permissions.hasPermission(sender, tempPermission, "unassign")) return false; + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot unassign §8<§7plotID§8>"); + break; + } + case "INFO": { + if (!Permissions.hasPermission(sender, tempPermission, "info")) return false; + Plot plot = PlotManager.getPlot(p.getLocation()); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); + return false; + } + printInfo(sender, plot); + break; + } + case "LIST": { + if (!Permissions.hasPermission(sender, tempPermission, "list")) return false; + if (PlotManager.plots.isEmpty()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); + return false; + } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" "); + sender.sendMessage("§7§m "); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + for (Plot plot : PlotManager.plots) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + StringBuilder ownedBy = new StringBuilder(); + ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); + boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); + for (int i = ownedBy.length(); i < 16; i++) { + ownedBy.append(" "); + } + StringBuilder size = new StringBuilder(plot.getPlotSize().name()); + for (int i = size.length(); i < 6; i++) { + size.append(" "); + } + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + ownedBy.substring(0, 14) + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); + textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); + new Chat(textComponent).sendTo(sender); + } + sender.sendMessage("§7§m "); + break; + } + case "TP": { + if (!Permissions.hasPermission(sender, tempPermission, "tp")) return false; + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot tp §8<§7plotID§8>"); + break; + } + case "RELOAD": { + if (!Permissions.hasPermission(sender, tempPermission, "reload")) return false; + try { + VirtualRealty.getInstance().reloadConfigs(); + if (VirtualRealty.getPluginConfiguration().dynmapMarkers) { + if (VirtualRealty.markerset != null) { + VirtualRealty.markerset.deleteMarkerSet(); + } + VirtualRealty.getInstance().registerDynmap(); + for (Plot plot : PlotManager.plots) { + PlotManager.resetPlotMarker(plot); + } + } else { + if (VirtualRealty.markerset != null) { + VirtualRealty.markerset.deleteMarkerSet(); + } + } + PlotManager.loadPlots(); + VirtualRealty.getInstance().reloadFlags(); + VirtualRealty.getInstance().loadSizesConfiguration(); + } catch (Exception exception) { + exception.printStackTrace(); + } + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().reloadCompleted); + break; + } + default: { + printHelp(sender); + break; + } + } + } + if (args.length > 1) { + switch (args[0].toUpperCase()) { + case "CREATE": { + if (!Permissions.hasPermission(sender, commandPermission, "create")) return false; + if (sender instanceof Player) { + if (Arrays.stream(PlotSize.values()).anyMatch(plotSize -> plotSize.name().equalsIgnoreCase(args[1])) && !args[1].equalsIgnoreCase(PlotSize.CUSTOM.name())) { + PlotSize plotSize = null; + try { + plotSize = PlotSize.valueOf(args[1].toUpperCase()); + } catch (IllegalArgumentException ignored) { + } + if (plotSize != null) { + if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), plotSize.getLength(), plotSize.getWidth(), plotSize.getHeight()))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); + return false; + } else { + Material floorMaterial = null; + byte floorData = 0; + if (args.length >= 3) { + try { + floorMaterial = VMaterial.getMaterial(args[2].split(":")[0].toUpperCase()); + if (floorMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return false; + } + if (args[2].split(":").length == 2) { + floorData = Byte.parseByte(args[2].split(":")[1]); + } + } + Material borderMaterial = null; + byte borderData = 0; + if (args.length >= 4) { + try { + borderMaterial = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); + if (borderMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return false; + } + if (args[3].split(":").length == 2) { + borderData = Byte.parseByte(args[3].split(":")[1]); + } + } + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); + long timeStart = System.currentTimeMillis(); + Plot plot = PlotManager.createPlot(location, plotSize); + if (floorMaterial != null) { + plot.setFloorMaterial(floorMaterial, floorData); + } + if (borderMaterial != null) { + plot.setBorder(borderMaterial, borderData); + } + long timeEnd = System.currentTimeMillis(); + BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); + BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); + BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); + textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); + textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); + textComponent.addExtra(textComponent2); + textComponent.addExtra(textComponent3); + new Chat(textComponent).sendTo(p); + } + } else { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().sizeNotRecognised); + return false; + } + } else { + int length; + int width; + int height; + try { + length = Integer.parseInt(args[1]); + width = Integer.parseInt(args[2]); + height = Integer.parseInt(args[3]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + if (length > 500 || width > 500 || height > 500) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().LWHHardLimit); + return false; + } + if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), length, width, height))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); + return false; + } else { + Material floorMaterial = null; + byte floorData = 0; + if (args.length >= 5) { + try { + floorMaterial = VMaterial.getMaterial(args[4].split(":")[0].toUpperCase()); + if (floorMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return false; + } + if (args[4].split(":").length == 2) { + floorData = Byte.parseByte(args[4].split(":")[1]); + } + } + Material borderMaterial = null; + byte borderData = 0; + if (args.length >= 6) { + try { + borderMaterial = VMaterial.getMaterial(args[5].split(":")[0].toUpperCase()); + if (borderMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return false; + } + if (args[5].split(":").length == 2) { + borderData = Byte.parseByte(args[5].split(":")[1]); + } + } + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); + long timeStart = System.currentTimeMillis(); + Plot plot = PlotManager.createPlot(location, length, width, height); + if (floorMaterial != null) { + plot.setFloorMaterial(floorMaterial, floorData); + } + if (borderMaterial != null) { + plot.setBorder(borderMaterial, borderData); + } + long timeEnd = System.currentTimeMillis(); + BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); + BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); + BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); + textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); + textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); + textComponent.addExtra(textComponent2); + textComponent.addExtra(textComponent3); + new Chat(textComponent).sendTo(p); + } + } + } + break; + } + case "REMOVE": { + if (!Permissions.hasPermission(sender, commandPermission, "remove")) return false; + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + plot.remove(); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().removedPlot); + break; + } + case "SET": { + if (!Permissions.hasPermission(sender, commandPermission, "set")) return false; + if (args.length >= 3) { + switch (args[2].toUpperCase()) { + case "OWNEDBY": { + if (!Permissions.hasPermission(sender, commandPermission, "set.ownedby")) return false; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyUsername); + return false; + } + int plotID; + OfflinePlayer offlinePlayer; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + try { + if (UUIDUtils.isValidUUID(args[3])) { + offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[3])); + } else { + offlinePlayer = Bukkit.getOfflinePlayer(args[3]); + } + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + } catch (NullPointerException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (args.length >= 5) { + String dateFormat = args[4]; + String timeFormat; + int year; + int month; + int dayOfMonth; + int hour = 0; + int minute = 0; + LocalDateTime localDateTime; + try { + year = Integer.parseInt(dateFormat.split("/")[2]); + month = Integer.parseInt(dateFormat.split("/")[1]); + dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); + if (args.length >= 6) { + timeFormat = args[5]; + hour = Integer.parseInt(timeFormat.split(":")[0]); + minute = Integer.parseInt(timeFormat.split(":")[1]); + } + localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); + return false; + } + plot.setOwnedUntilDate(localDateTime); + } + if (sender instanceof RemoteConsoleCommandSender && args.length >= 7 && args[6].equalsIgnoreCase("assign")) { + plot.setAssignedBy("SHOP_PURCHASE"); + } + plot.setOwnedBy(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedTo.replaceAll("%assigned_to%", offlinePlayer.getName())); + plot.update(); + break; + } + case "FLOORMATERIAL": { + if (!Permissions.hasPermission(sender, commandPermission, "set.floormaterial")) return false; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Material material; + try { + material = Material.matchMaterial(args[3].split(":")[0].toUpperCase()); + if (material == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + byte data = 0; + if (args[3].split(":").length == 2) { + data = Byte.parseByte(args[3].split(":")[1]); + } + plot.setFloorMaterial(material, data); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newFloorMaterialSet); + plot.update(); + break; + } + case "BORDERMATERIAL": { + if (!Permissions.hasPermission(sender, commandPermission, "set.bordermaterial")) + return false; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Material material; + try { + material = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); + if (material == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + byte data = 0; + if (args[3].split(":").length == 2) { + data = Byte.parseByte(args[3].split(":")[1]); + } + plot.setBorder(material, data); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newBorderMaterialSet); + plot.update(); + return false; + } + case "OWNERSHIPEXPIRES": { + if (!Permissions.hasPermission(sender, commandPermission, "set.ownerexpires")) return false; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyExpiryDate); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + String dateFormat = args[3]; + String timeFormat; + int year; + int month; + int dayOfMonth; + int hour = 0; + int minute = 0; + LocalDateTime localDateTime; + try { + year = Integer.parseInt(dateFormat.split("/")[2]); + month = Integer.parseInt(dateFormat.split("/")[1]); + dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); + if (args.length == 5) { + timeFormat = args[4]; + hour = Integer.parseInt(timeFormat.split(":")[0]); + minute = Integer.parseInt(timeFormat.split(":")[1]); + } + localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + plot.setOwnedUntilDate(localDateTime); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownedUntilUpdated); + plot.update(); + break; + } + default: { + printSetHelp(sender); + break; + } + } + } else { + printSetHelp(sender); + } + break; + } + case "ASSIGN": { + if (!Permissions.hasPermission(sender, commandPermission, "assign")) return false; + if (args.length == 3) { + int plotID; + OfflinePlayer offlinePlayer; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + try { + if (UUIDUtils.isValidUUID(args[2])) { + offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[2])); + } else { + offlinePlayer = Bukkit.getOfflinePlayer(args[2]); + } + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + } catch (NullPointerException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (sender instanceof Player) { + plot.setAssignedBy(p.getUniqueId().toString()); + } else if (sender instanceof ConsoleCommandSender){ + plot.setAssignedBy("CONSOLE"); + } else { + plot.setAssignedBy("SHOP_PURCHASE"); + } + plot.setOwnedBy(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedToBy.replaceAll("%assigned_to%", offlinePlayer.getName()).replaceAll("%assigned_by%", sender.getName())); + plot.update(); + } + break; + } + case "UNASSIGN": { + if (!Permissions.hasPermission(sender, commandPermission, "unassign")) return false; + if (args.length == 2) { + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + plot.setAssignedBy(null); + plot.setOwnedBy(null); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().unassigned); + plot.update(); + } + break; + } + case "INFO": { + if (!Permissions.hasPermission(sender, commandPermission, "info")) return false; + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + if (PlotManager.plots.isEmpty()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); + return false; + } + if (plotID < PlotManager.getPlotMinID()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().minPlotID.replaceAll("%min_id%", String.valueOf(PlotManager.getPlotMinID()))); + return false; + } + if (plotID > PlotManager.getPlotMaxID()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().maxPlotID.replaceAll("%max_id%", String.valueOf(PlotManager.getPlotMaxID()))); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + printInfo(sender, plot); + break; + } + case "TP": { + if (!Permissions.hasPermission(sender, commandPermission, "tp")) return false; + if (!(sender instanceof Player)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cmdOnlyPlayers); + return false; + } + if (args.length == 2) { + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); + loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); + p.teleport(loc); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); + } + break; + } + default: { + printHelp(sender); + break; + } + } + } + return false; + } + + private static void printInfo(CommandSender sender, Plot plot) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); + String assignedBy = VirtualRealty.getMessages().notAssigned; + if (plot.getAssignedBy() != null) { + switch (plot.getAssignedBy().toUpperCase()) { + case "CONSOLE": { + assignedBy = VirtualRealty.getMessages().assignedByConsole; + break; + } + case "SHOP_PURCHASE": { + assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; + break; + } + default: { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); + assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); + } + } + } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); + sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); + if (plot.getMembers().size() != 0) { + sender.sendMessage(" §7Members §8§l↴"); + for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { + sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); + } + } + sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); + sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); + sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); + sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); + sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); + sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); + sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); + sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); + sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); + sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); + sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); + } + + private static void printHelp(CommandSender sender) { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot create §8- §7Creates a plot"); + sender.sendMessage(" §a/vrplot remove §8- §7Removes a plot"); + sender.sendMessage(" §a/vrplot set §8- §7Sets a variable for the plot"); + sender.sendMessage(" §a/vrplot assign §8- §7Assigns a plot to player"); + sender.sendMessage(" §a/vrplot unassign §8- §7Sets assigned to and assigned by to null"); + sender.sendMessage(" §a/vrplot info §8- §7Prints info about plot"); + sender.sendMessage(" §a/vrplot list §8- §7Prints all plots"); + sender.sendMessage(" §a/vrplot tp §8- §7Teleports to the plot"); + sender.sendMessage(" §a/vrplot reload §8- §7Reloads plugin"); + } + + private static void printSetHelp(CommandSender sender) { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownedBy §8<§7username§8>"); + sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7floorMaterial §8<§7material§8>"); + sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7borderMaterial §8<§7material§8>"); + sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownershipExpires §8<§7dd/mm/YYYY§8> §8<§7HH:mm (optional)§8>"); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java new file mode 100644 index 0000000..cd379df --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java @@ -0,0 +1,69 @@ +package com.modnmetl.virtualrealty.configs; + +import eu.okaeri.configs.OkaeriConfig; + +public class MessagesConfiguration extends OkaeriConfig { + + public String useNaturalNumbersOnly = "§cUse only natural numbers!"; + public String noPlotFound = "§cCouldn't get plot with specified ID!"; + public String notYourPlot = "§cIt's not your plot!"; + public String ownershipExpired = "§cYour ownership has expired!"; + public String teleportedToPlot = "§aYou have been teleported to the plot!"; + public String gamemodeFeatureDisabled = "§cGamemode feature is disabled!"; + public String incorrectGamemode = "§cIncorrect gamemode value!"; + public String gamemodeDisabled = "§cThis gamemode is disabled!"; + public String cantSwitchGamemode = "§cYou can't switch gamemode here!"; + public String notStandingOnPlot = "§cYou aren't standing on any plot!"; + public String assignedByConsole = "§eConsole"; + public String assignedByShopPurchase = "§eShop Purchase"; + public String noPlots = "§cThere are no plots!"; + public String available = "§cAvailable"; + public String reloadCompleted = "§aReload completed!"; + public String cantCreateOnExisting = "§cYou can't create new plot over an existing plot!"; + public String cantGetFloorMaterial = "§cCouldn't get floor material with specified name!"; + public String cantGetBorderMaterial = "§cCouldn't get border material with specified name!"; + public String cantGetMaterial = "§cCouldn't get material with specified name!"; + public String notCollidingCreating = "§aNot colliding. Creating plot.."; + public String clickToShowDetailedInfo = "§a§oClick to show detailed information about the plot! §8(§7ID: §f%plot_id%§8)"; + public String sizeNotRecognised = "§cSize not recognized!"; + public String LWHHardLimit = "§cL, W and H hard-limit is 500!"; + public String removedPlot = "§aSuccessfully removed plot!"; + public String specifyUsername = "§cSpecify username!"; + public String playerNotFoundWithUsername = "§cCouldn't find player with specified username!"; + public String invalidDateProvided = "§cInvalid date format provided!"; + public String assignedTo = "§aPlot has been assigned to §f%assigned_to%!"; + public String specifyMaterialName = "§cSpecify material name!"; + public String specifyExpiryDate = "§cSpecify expiry date!"; + public String newFloorMaterialSet = "§aNew floor material has been set!"; + public String newBorderMaterialSet = "§aNew border material has been set!"; + public String ownedUntilUpdated = "§aOwned until date has been updated!"; + public String assignedToBy = "§aPlot has been assigned to §f%assigned_to% §aby §f%assigned_by%!"; + public String notAssigned = "§cNot assigned"; + public String unassigned = "§aPlot has been unassigned!"; + public String minPlotID = "§cMinimum plot ID is %min_id%!"; + public String maxPlotID = "§cMaximum plot ID is %max_id%!"; + public String cmdOnlyPlayers = "§cCommand only for players!"; + + public String enteredAvailablePlot = "§2You have entered an available plot!"; + public String enteredOwnedPlot = "§7You have entered §2%owner%'s §7plot!"; + public String leftAvailablePlot = "§cYou have left an available plot!"; + public String leftOwnedPlot = "§7You have left §2%owner%'s §7plot!"; + public String cantInteract = "§cYou can't interact here!"; + public String cantBuildHere = "§cYou can't build here!"; + public String cantRideOnPlot = "§cYou can't ride on someones plot!"; + + public String creationPlotComponent1 = "§aPlot "; + public String creationPlotComponent2 = "§8#§7%plot_id%"; + public String creationPlotComponent3 = " §acreated! §8(§7%creation_time% ms§8)"; + + public String cantAddYourself = "§cYou can't add yourself to the plot!"; + public String cantKickYourself = "§cYou can't kick yourself from the plot!"; + public String alreadyInMembers = "§cThis player is already one of the plot members!"; + public String notInMembers = "§cThis player is not one of the plot members!"; + public String cantDoAnyDMG = "§cYou can't do any damage here!"; + public String playerKick = "§aPlayer §7%player% §ahas been kicked out of your plot!"; + public String playerAdd = "§aPlayer §7%player% §ahas been added to your plot!"; + public String gamemodeSwitched = "§aYour gamemode has changed!"; + public String gamemodeAlreadySelected = "§cThis gamemode is already selected!"; + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java new file mode 100644 index 0000000..639ff56 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java @@ -0,0 +1,174 @@ +package com.modnmetl.virtualrealty.configs; + +import com.modnmetl.virtualrealty.enums.HighlightType; +import eu.okaeri.configs.OkaeriConfig; +import eu.okaeri.configs.annotation.*; +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.GameMode; + +@Header("################################################################") +@Header("# #") +@Header("# Virtual Realty #") +@Header("# #") +@Header("################################################################") +@Names(strategy = NameStrategy.IDENTITY, modifier = NameModifier.TO_LOWER_CASE) +public class PluginConfiguration extends OkaeriConfig { + + @Comment(" ") + @Comment("-------------------------") + @Comment("Don't change this value!") + @CustomKey("config-version") + public String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); + + @Comment("-------------------------") + @Comment("Debug mode (Dev only)") + @CustomKey("debug-mode") + public boolean debugMode = false; + + @CustomKey("LICENSE-KEY") + public String licenseKey = ""; + + @Comment("Set player gamemode to change when they enter their plot") + @CustomKey("enable-plot-gamemode") + public boolean enablePlotGameMode = false; + + @Comment("Set your wanted language (locale)") + public String locale = VirtualRealty.getInstance().availableLocales.contains(VirtualRealty.getLocale()) ? VirtualRealty.getLocale().toString() : "en_GB"; + + @Comment("Set which gamemode players change to when they enter their plot") + @CustomKey("default-plot-gamemode") + public String plotGameMode = "SURVIVAL"; + + @Comment("Lock gamemode to plot default when player enters their plot (disables '/plot gm' command)") + @CustomKey("lock-plot-gamemode") + public boolean lockPlotGameMode = false; + + public GameMode getGameMode() { + try { + return GameMode.valueOf(plotGameMode); + } catch (Exception e) { + VirtualRealty.getInstance().getLogger().warning("Couldn't parse plot-gamemode from config.yml\nUsing default: SURVIVAL"); + return GameMode.SURVIVAL; + } + } + + @Comment("Allow players to build outside of their plots") + @CustomKey("allow-outplot-build") + public boolean allowOutPlotBuild = true; + + @Comment("Enables dynmap plots highlighting") + @CustomKey("enable-dynmap-markers") + public boolean dynmapMarkers = false; + + @Comment("Choose which type of plots should be highlighted on Dynmap page | Choose from: { ALL, AVAILABLE, OWNED }") + @CustomKey("dynmap-type") + public HighlightType dynmapType = HighlightType.ALL; + + @CustomKey("dynmap-markers") + public MarkerColor dynmapMarkersColor = new MarkerColor(new MarkerColor.Available("#80eb34", .3), new MarkerColor.Owned("#ffbf00", .45)); + + @Names(strategy = NameStrategy.IDENTITY) + public static class MarkerColor extends OkaeriConfig { + + public Available available; + + public Owned owned; + + public MarkerColor(Available available, Owned owned) { + this.available = available; + this.owned = owned; + } + + @Names(strategy = NameStrategy.IDENTITY) + public static class Available extends OkaeriConfig { + + public String color; + + public double opacity; + + public Available(String color, double opacity) { + this.color = color; + this.opacity = opacity; + } + + public int getHexColor() { + return Integer.decode("0x" + color.replaceAll("#", "")); + } + + } + + @Names(strategy = NameStrategy.IDENTITY) + public static class Owned extends OkaeriConfig { + + public String color; + + public double opacity; + + public Owned(String color, double opacity) { + this.color = color; + this.opacity = opacity; + } + + public int getHexColor() { + return Integer.decode("0x" + color.replaceAll("#", "")); + } + + } + + } + + @Comment("Enables plots enter/leave sounds") + @CustomKey("plot-sounds") + public boolean plotSound = true; + + @Comment("Type of data recording") + @Comment("SQLITE - Local database") + @Comment("MYSQL - External database") + @CustomKey("data-model") + public DataModel dataModel = DataModel.SQLITE; + + @Comment("Data required to connect to the database") + @Comment("The plotsTableName section is the name of the VR data table in the database") + @Comment("It is best to change these names only if you really need to (e.g. there is a conflict with another plugin)") + @Comment("To rename tables when you already have some VR data in the database:") + @Comment("1. Turn off the server") + @Comment("2. Change data in VR config") + @Comment("3. Rename database tables using phpMyAdmin for example") + @CustomKey("mysql") + public MySQL mysql = new MySQL("localhost", 3306, "db", "root", "passwd", true, "vr_plots"); + + public enum DataModel { + SQLITE, + MYSQL + } + + @Names(strategy = NameStrategy.IDENTITY) + public static class MySQL extends OkaeriConfig { + + @Variable("VR_MYSQL_HOSTNAME") + public String hostname; + @Variable("VR_MYSQL_PORT") + public int port; + @Variable("VR_MYSQL_DATABASE") + public String database; + @Variable("VR_MYSQL_USER") + public String user; + @Variable("VR_MYSQL_PASSWORD") + public String password; + @Variable("VR_MYSQL_USE_SSL") + public boolean useSSL; + @Variable("VR_MYSQL_USERS_TABLE_NAME") + public String plotsTableName; + + public MySQL(String hostname, int port, String database, String user, String password, boolean useSSL, String plotsTableName) { + this.hostname = hostname; + this.port = port; + this.database = database; + this.user = user; + this.password = password; + this.useSSL = useSSL; + this.plotsTableName = plotsTableName; + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java new file mode 100644 index 0000000..a09ca11 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java @@ -0,0 +1,86 @@ +package com.modnmetl.virtualrealty.configs; + +import eu.okaeri.configs.OkaeriConfig; +import eu.okaeri.configs.annotation.*; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.PlotSize; + +@Header("################################################################") +@Header("# #") +@Header("# Plot Sizes #") +@Header("# #") +@Header("################################################################") +public class SizesConfiguration extends OkaeriConfig { + + @Comment(" ") + @Comment("-------------------------") + @Comment("Don't change this value!") + @CustomKey("config-version") + public final String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); + @Comment("-------------------------") + + @Comment(" ") + @Comment("(<1.13) Legacy Materials: https://helpch.at/docs/1.8/org/bukkit/Material.html") + @Comment("(>1.12) Post-Legacy Materials: https://helpch.at/docs/1.13/org/bukkit/Material.html") + @Comment(" ") + @Comment("floor-data and border-data are only for legacy versions * <1.13 *") + @CustomKey("plot-sizes") + public PlotSizes plotSizes = new PlotSizes(); + + @Names(strategy = NameStrategy.IDENTITY) + public static class PlotSizes extends OkaeriConfig { + + @Variable("VR_SIZE_SMALL") + public Size SMALL = new Size(PlotSize.SMALL); + @Variable("VR_SIZE_MEDIUM") + public Size MEDIUM = new Size(PlotSize.MEDIUM); + @Variable("VR_SIZE_LARGE") + public Size LARGE = new Size(PlotSize.LARGE); + + public PlotSizes() { + } + + public PlotSizes(Size small, Size medium, Size large) { + this.SMALL = small; + this.MEDIUM = medium; + this.LARGE = large; + } + + public static class Size extends OkaeriConfig { + + @Variable("VR_SIZE_FLOORMATERIAL") + @CustomKey("floor-material") + public String floorMaterial; + @Variable("VR_SIZE_FLOORDATA") + @CustomKey("floor-data") + public byte floorData; + @Variable("VR_SIZE_BORDERMATERIAL") + @CustomKey("border-material") + public String borderMaterial; + @Variable("VR_SIZE_BORDERDATA") + @CustomKey("border-data") + public byte borderData; + @Variable("VR_SIZE_LENGTH") + public int length; + @Variable("VR_SIZE_WIDTH") + public int width; + @Variable("VR_SIZE_HEIGHT") + public int height; + + public Size() { + } + + public Size(PlotSize plotSize) { + this.floorMaterial = plotSize.getFloorMaterial().name(); + this.floorData = plotSize.getFloorData(); + this.borderMaterial = plotSize.getBorderMaterial().name(); + this.borderData = plotSize.getBorderData(); + this.length = plotSize.getLength(); + this.width = plotSize.getWidth(); + this.height = plotSize.getHeight(); + } + + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/Direction.java b/src/main/java/com/modnmetl/virtualrealty/enums/Direction.java new file mode 100644 index 0000000..772a253 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/Direction.java @@ -0,0 +1,45 @@ +package com.modnmetl.virtualrealty.enums; + +public enum Direction { + + SOUTH(315, 45), + WEST(45, 135), + NORTH(135, 225), + EAST(225, 315); + + private final float minYaw; + private final float maxYaw; + + Direction(float minYaw, float maxYaw) { + this.minYaw = minYaw; + this.maxYaw = maxYaw; + } + + public static Direction byYaw(float yaw) { + float absoluteYaw = Math.abs(yaw); + Direction direction = null; + if(absoluteYaw > 315 || absoluteYaw <= 45) { + //south + direction = SOUTH; + } else if(absoluteYaw > 45 && absoluteYaw <= 135) { + //west + direction = yaw > 0 ? WEST : EAST; + } else if(absoluteYaw > 135 && absoluteYaw <= 225) { + //north + direction = NORTH; + } else if(absoluteYaw > 225 && absoluteYaw <= 315) { + //east + direction = yaw > 0 ? EAST : WEST; + } + return direction; + } + + public float getMaxYaw() { + return maxYaw; + } + + public float getMinYaw() { + return minYaw; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/Flag.java b/src/main/java/com/modnmetl/virtualrealty/enums/Flag.java new file mode 100644 index 0000000..54e1a73 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/Flag.java @@ -0,0 +1,33 @@ +package com.modnmetl.virtualrealty.enums; + +public class Flag { + + public enum World { + + BLOCK_PLACE(false), + BLOCK_BREAK(false), + INTERACT(false), + IGNITE(false), + EXPLOSION_PRIME(false), + ENTITY_DAMAGE(false), + ARMOR_STAND_MANIPULATION(false), + ITEM_FRAME_DESTROY(false), + ITEM_FRAME_ROTATE(false); + + private boolean allowed; + + World(boolean allowed) { + this.allowed = allowed; + } + + public boolean isAllowed() { + return allowed; + } + + public void setAllowed(boolean allowed) { + this.allowed = allowed; + } + + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/HighlightType.java b/src/main/java/com/modnmetl/virtualrealty/enums/HighlightType.java new file mode 100644 index 0000000..d9e3bb9 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/HighlightType.java @@ -0,0 +1,9 @@ +package com.modnmetl.virtualrealty.enums; + +public enum HighlightType { + + ALL, + AVAILABLE, + OWNED + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/Permission.java b/src/main/java/com/modnmetl/virtualrealty/enums/Permission.java new file mode 100644 index 0000000..e84f66c --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/Permission.java @@ -0,0 +1,24 @@ +package com.modnmetl.virtualrealty.enums; + +public enum Permission { + + WORLD_BUILD("virtualrealty.build.world"), + PLOT_BUILD("virtualrealty.build.plot"), + BORDER_BUILD("virtualrealty.build.border"); + + private final String permission; + + Permission(String permission) { + this.permission = permission; + } + + public String getPermission() { + return permission; + } + + @Override + public String toString() { + return permission; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java b/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java new file mode 100644 index 0000000..4abf429 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java @@ -0,0 +1,86 @@ +package com.modnmetl.virtualrealty.enums; + +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.Material; + +public enum PlotSize { + + SMALL(10, 10, 10, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), + MEDIUM(25, 25, 25, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), + LARGE(50, 50, 50, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), + CUSTOM(0, 0, 0, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0); + + private int length; + private int width; + private int height; + private Material floorMaterial; + private byte floorData; + private Material borderMaterial; + private byte borderData; + + PlotSize(int length, int width, int height, Material floorMaterial, byte floorData, Material borderMaterial, byte borderData) { + this.length = length; + this.width = width; + this.height = height; + this.floorMaterial = floorMaterial; + this.floorData = floorData; + this.borderMaterial = borderMaterial; + this.borderData = borderData; + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + public Material getFloorMaterial() { + return floorMaterial; + } + + public void setFloorMaterial(Material floorMaterial) { + this.floorMaterial = floorMaterial; + } + + public byte getFloorData() { + return floorData; + } + + public void setFloorData(byte floorData) { + this.floorData = floorData; + } + + public Material getBorderMaterial() { + return borderMaterial; + } + + public void setBorderMaterial(Material borderMaterial) { + this.borderMaterial = borderMaterial; + } + + public byte getBorderData() { + return borderData; + } + + public void setBorderData(byte borderData) { + this.borderData = borderData; + } +} diff --git a/src/main/java/com/modnmetl/virtualrealty/exceptions/MaterialMatchException.java b/src/main/java/com/modnmetl/virtualrealty/exceptions/MaterialMatchException.java new file mode 100644 index 0000000..a95b1cb --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/exceptions/MaterialMatchException.java @@ -0,0 +1,9 @@ +package com.modnmetl.virtualrealty.exceptions; + +public class MaterialMatchException extends Exception { + + public MaterialMatchException(String exception) { + super(exception); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java new file mode 100644 index 0000000..79660f9 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java @@ -0,0 +1,472 @@ +package com.modnmetl.virtualrealty.listeners; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.Flag; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.ProtectionUtil; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.*; +import org.bukkit.event.hanging.HangingBreakByEntityEvent; +import org.bukkit.event.player.PlayerArmorStandManipulateEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.world.StructureGrowEvent; +import org.bukkit.util.Vector; + +import java.time.LocalDateTime; + +public class ProtectionListener extends VirtualListener { + + public ProtectionListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onBlockInteract(PlayerInteractEvent e) { + Player player = e.getPlayer(); + if (e.getClickedBlock() != null && (e.getAction() == Action.RIGHT_CLICK_BLOCK || (e.getAction() == Action.LEFT_CLICK_BLOCK && (!VirtualRealty.isLegacy && e.getClickedBlock().getType().isInteractable())))) { + Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { + if (!Flag.World.BLOCK_PLACE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent e) { + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlockPlaced().getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { + if (!Flag.World.BLOCK_PLACE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + + @EventHandler + public void onBlockBreak(BlockBreakEvent e) { + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_BREAK)) { + if (!Flag.World.BLOCK_BREAK.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + + @EventHandler + public void onBlockMove(BlockPistonExtendEvent e) { + if (VirtualRealty.isLegacy) { + if (e.getBlocks().isEmpty()) { + Location fromLocation = e.getBlock().getLocation(); + Location toLocation = e.getBlock().getLocation(); + toLocation.add(getDirection(e.getDirection())); + Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); + Plot toPlot = PlotManager.getBorderedPlot(toLocation); + Plot toUnborderedPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + if (fromPlot != null) { + if (toUnborderedPlot == null) { + e.setCancelled(true); + } + } + } else { + for (Block block : e.getBlocks()) { + Location fromLocation = block.getLocation(); + Location toLocation = block.getLocation(); + toLocation.add(getDirection(e.getDirection())); + Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); + Plot toPlot = PlotManager.getBorderedPlot(toLocation); + Plot toUnborderedPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } else { + e.setCancelled(true); + } + } + if (fromPlot != null) { + if (toUnborderedPlot == null) { + e.setCancelled(true); + } + } + } + } + } else { + if (e.getBlocks().isEmpty()) { + Location fromLocation = e.getBlock().getLocation(); + Location toLocation = e.getBlock().getLocation(); + toLocation.add(e.getDirection().getDirection()); + Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); + Plot toPlot = PlotManager.getBorderedPlot(toLocation); + Plot toUnborderedPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + if (fromPlot != null) { + if (toUnborderedPlot == null) { + e.setCancelled(true); + } + } + } else { + for (Block block : e.getBlocks()) { + Location fromLocation = block.getLocation(); + Location toLocation = block.getLocation(); + toLocation.add(e.getDirection().getDirection()); + Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); + Plot toPlot = PlotManager.getBorderedPlot(toLocation); + Plot toUnborderedPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } else { + e.setCancelled(true); + } + } + if (fromPlot != null) { + if (toUnborderedPlot == null) { + e.setCancelled(true); + } + } + } + } + } + } + + public Vector getDirection(BlockFace blockFace) { + Vector direction = new Vector(blockFace.getModX(), blockFace.getModY(), blockFace.getModZ()); + if (blockFace.getModX() != 0 || blockFace.getModY() != 0 || blockFace.getModZ() != 0) { + direction.normalize(); + } + + return direction; + } + + @EventHandler + public void onIgniteEvent(BlockIgniteEvent e) { + Player player = e.getPlayer(); + if (player != null) { + if (e.getIgnitingBlock() != null) { + Plot plot = PlotManager.getBorderedPlot(e.getIgnitingBlock().getLocation()); + if (plot != null) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + return; + } + e.setCancelled(!plot.hasPermissionToPlot(player)); + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.IGNITE)) { + if (!Flag.World.IGNITE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + } + + @EventHandler + public void onEntityExplode(ExplosionPrimeEvent e) { + Plot plot = PlotManager.getBorderedPlot(e.getEntity().getLocation()); + if (plot != null) { + e.setCancelled(true); + } else { + if (!Flag.World.EXPLOSION_PRIME.isAllowed()) { + e.setCancelled(true); + } + } + } + +// @EventHandler +// public void onPlotEnter(PlayerMoveEvent e) { +// Player player = e.getPlayer(); +// Plot plot = PlotManager.getPlot(e.getTo()); +// if (plot != null && e.getPlayer().isInsideVehicle()) { +// if (!plot.hasPermissionToPlot(player)) { +// e.getPlayer().getVehicle().eject(); +// player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantRideOnPlot); +// } +// } +// } + + @EventHandler + public void onTreeGrow(StructureGrowEvent e) { + for (BlockState block : e.getBlocks()) { + Location fromLocation = e.getLocation(); + Location toLocation = block.getLocation(); + Plot fromPlot = PlotManager.getPlot(fromLocation); + Plot toPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + } + } + + @EventHandler + public void onDragonEggMove(BlockFromToEvent e) { + Material block = e.getBlock().getType(); + if (block == Material.DRAGON_EGG || block == Material.LAVA || block == Material.WATER) { + Location fromLocation = e.getBlock().getLocation(); + Location toLocation = e.getToBlock().getLocation(); + Plot fromPlot = PlotManager.getPlot(fromLocation); + Plot toPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + } + } + + @EventHandler + public void onProjectileLaunch(ProjectileLaunchEvent e) { + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot != null) { + if (e.getEntity().getShooter() != null && e.getEntity().getShooter() instanceof Player) { + if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId()))) { + Player player = (Player) e.getEntity().getShooter(); + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.getEntity().remove(); + } + } else { + e.getEntity().remove(); + } + } + } + } + } + + @EventHandler + public void onProjectileHit(ProjectileHitEvent e) { + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot != null) { + if (e.getEntity().getShooter() != null && e.getEntity().getShooter() instanceof Player) { + if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId()))) { + Player player = (Player) e.getEntity().getShooter(); + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.getEntity().remove(); + } + } else { + e.getEntity().remove(); + } + } + } + } + } + + @EventHandler + public void onFireSpread(BlockSpreadEvent e) { + Location fromLocation = e.getSource().getLocation(); + Location toLocation = e.getBlock().getLocation(); + Plot fromPlot = PlotManager.getPlot(fromLocation); + Plot toPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + } + + @EventHandler + public void onArmorStandChange(PlayerArmorStandManipulateEvent e) { + Plot plot = PlotManager.getPlot(e.getPlayer().getLocation()); + Player player = e.getPlayer(); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ARMOR_STAND_MANIPULATION)) { + if (!Flag.World.ARMOR_STAND_MANIPULATION.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + + @EventHandler + public void onItemFrameDamage(HangingBreakByEntityEvent e) { + if (e.getRemover() instanceof Player) { + Player player = (Player) e.getRemover(); + Plot plot = PlotManager.getPlot(player.getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_DESTROY)) { + if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + + @EventHandler + public void onItemFrameRotate(PlayerInteractEntityEvent e) { + if (e.getRightClicked().getType().equals(EntityType.ITEM_FRAME)) { + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(player.getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_ROTATE)) { + if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + + + @EventHandler + public void onEntityDamage(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof Player) { + Player player = (Player) e.getDamager(); + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { + if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + + @EventHandler + public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof Projectile) { + if (((Projectile) e.getDamager()).getShooter() instanceof Player) { + Player player = ((Player) ((Projectile) e.getDamager()).getShooter()); + Plot plot = PlotManager.getBorderedPlot(e.getDamager().getLocation()); + if (plot != null) { + if (!plot.hasPermissionToPlot(player)) { + e.getDamager().remove(); + e.setCancelled(true); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { + if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java new file mode 100644 index 0000000..4e2ee5d --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java @@ -0,0 +1,22 @@ +package com.modnmetl.virtualrealty.listeners; + +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.event.Listener; + +public class VirtualListener implements Listener { + + private final VirtualRealty plugin; + + public VirtualListener(VirtualRealty plugin) { + this.plugin = plugin; + } + + public void registerEvents() { + this.plugin.getServer().getPluginManager().registerEvents(this, this.plugin); + } + + protected VirtualRealty getPlugin() { + return this.plugin; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java new file mode 100644 index 0000000..9c19010 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java @@ -0,0 +1,44 @@ +package com.modnmetl.virtualrealty.listeners.plot; + +import com.modnmetl.virtualrealty.enums.Permission; +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; + +public class BorderListener extends VirtualListener { + + public BorderListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onBorderBreak(BlockBreakEvent e) { + Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); + if (plot != null) { + if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { + if (plot.getBorderBlocks().contains(e.getBlock())) { + e.setCancelled(true); + e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + } + + @EventHandler + public void onBorderPlace(BlockPlaceEvent e) { + Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); + if (plot != null) { + if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { + if (plot.getBorderBlocks().contains(e.getBlock())) { + e.setCancelled(true); + e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java new file mode 100644 index 0000000..0c8f181 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java @@ -0,0 +1,100 @@ +package com.modnmetl.virtualrealty.listeners.plot; + +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Plot; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerMoveEvent; + +import java.util.AbstractMap; +import java.util.HashMap; + +public class PlotListener extends VirtualListener { + + public HashMap> enteredPlot = new HashMap<>(); + + public PlotListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onPlotMove(PlayerMoveEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Location to = e.getTo(); + Plot plot = PlotManager.getPlot(to); + if (plot != null) { + OfflinePlayer offlinePlayer; + String enterPlotString = VirtualRealty.getMessages().enteredAvailablePlot; + if (plot.getOwnedBy() != null) { + offlinePlayer = Bukkit.getOfflinePlayer(plot.getOwnedBy()); + enterPlotString = VirtualRealty.getMessages().enteredOwnedPlot.replaceAll("%owner%", offlinePlayer.getName()).replaceAll("%plot_id%", plot.getID() + ""); + } + if (!enteredPlot.containsKey(player)) { + enteredPlot.put(player, new AbstractMap.SimpleEntry<>(plot, true)); + Plot newPlot = enteredPlot.get(player).getKey(); + if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { + if (newPlot.getOwnedBy() != null && newPlot.getOwnedBy().equals(player.getUniqueId())) { + if (newPlot.getSelectedGameMode() != VirtualRealty.getInstance().getServer().getDefaultGameMode() || newPlot.getSelectedGameMode() != VirtualRealty.getPluginConfiguration().getGameMode()) { + newPlot.setSelectedGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); + } + player.setGameMode(newPlot.getSelectedGameMode()); + } else if (newPlot.getMembers().contains(player.getUniqueId())) { + player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); + } + } + if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { + if (VirtualRealty.getPluginConfiguration().plotSound) { + player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, 0.4f, 0.8f); + } + } + if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(enterPlotString)); + } + } else { + if (!enteredPlot.get(player).getValue()) { + enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(plot, true)); + if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { + player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); + } + } + } + } else { + if (enteredPlot.containsKey(player)) { + if (enteredPlot.get(player).getValue()) { + OfflinePlayer offlinePlayer; + String leavePlotString = VirtualRealty.getMessages().leftAvailablePlot; + if (enteredPlot.get(player).getKey().getOwnedBy() != null) { + offlinePlayer = Bukkit.getOfflinePlayer(enteredPlot.get(player).getKey().getOwnedBy()); + leavePlotString = VirtualRealty.getMessages().leftOwnedPlot.replaceAll("%owner%", offlinePlayer.getName()).replaceAll("%plot_id%", enteredPlot.get(player).getKey().getID() + ""); + if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { + if (enteredPlot.get(player).getKey().hasPlotMembership(player)) { + player.setGameMode(Bukkit.getServer().getDefaultGameMode()); + } + } + } + if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { + if (VirtualRealty.getPluginConfiguration().plotSound) { + player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_CLOSE, 0.3f, 1f); + } + if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(leavePlotString)); + } + } + enteredPlot.remove(player); + return; + } + enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(enteredPlot.get(player).getKey(), false)); + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java new file mode 100644 index 0000000..2f2501b --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java @@ -0,0 +1,49 @@ +package com.modnmetl.virtualrealty.listeners.world; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.Permission; +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; + +public class WorldListener extends VirtualListener { + + public WorldListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onBlockBreak(BlockBreakEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); + if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { + if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { + if (plot == null) { + e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); + if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { + if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { + if (plot == null) { + e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java b/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java new file mode 100644 index 0000000..3e88546 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java @@ -0,0 +1,186 @@ +package com.modnmetl.virtualrealty.managers; + +import com.modnmetl.virtualrealty.enums.HighlightType; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.objects.math.BlockVector2; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Cuboid; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.objects.math.BlockVector3; +import com.modnmetl.virtualrealty.sql.SQL; +import org.bukkit.Location; +import org.bukkit.Material; +import org.dynmap.markers.AreaMarker; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + +public class PlotManager { + + private static final String markerString = "

Plot #%s

Owned By: Available"; + private static final String markerOwnedString = "

Plot #%s

Owned By: %s
Owned Until: %s"; + + public static Set areaMarkers = new HashSet<>(); + public static Set plots = new LinkedHashSet<>(); + + public static void loadPlots() { + plots.clear(); + try { + ResultSet rs = SQL.getStatement().executeQuery("SELECT * FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "`"); + while (rs.next()) { + plots.add(new Plot(rs)); + } + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + public static Plot createPlot(Location creationLocation, PlotSize plotSize) { + Plot plot = new Plot(creationLocation, plotSize.getFloorMaterial(), plotSize.getBorderMaterial(), plotSize); + plots.add(plot); + plot.insert(); + return plot; + } + + public static Plot createPlot(Location creationLocation, int length, int width, int height) { + Plot plot = new Plot(creationLocation, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), length, width, height); + plots.add(plot); + plot.insert(); + return plot; + } + + public static Plot getPlot(int ID) { + for (Plot plot : plots) { + if(plot.getID() == ID) { + return plot; + } + } + return null; + } + + public static int getPlotMinID() { + return plots.isEmpty() ? null : plots.stream().findFirst().get().getID(); + } + + public static int getPlotMaxID() { + Plot[] plotArray = PlotManager.plots.toArray(new Plot[PlotManager.plots.size()]); + Plot lastPlot = plotArray[plotArray.length - 1]; + return lastPlot.getID(); + } + + public static List getPlayerPlots(UUID owner) { + List playerPlots = new ArrayList<>(); + for (Plot plot : plots) { + if (plot.getOwnedBy() != null) { + if (plot.getOwnedBy().equals(owner)) { + playerPlots.add(plot); + } + } + } + return playerPlots; + } + + public static Plot getPlot(Location location) { + BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + for (Plot plot : plots) { + Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); + if(region.contains(newVector)) { + return plot; + } + } + return null; + } + + public static boolean isLocationInPlot(Location location, Plot plot) { + BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); + return region.contains(newVector); + } + + public static Plot getBorderedPlot(Location location) { + BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + for (Plot plot : plots) { + Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), location.getWorld()); + if(region.contains(newVector)) { + return plot; + } + } + return null; + } + + public static boolean isLocationInBorderedPlot(Location location, Plot plot) { + BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), location.getWorld()); + return region.contains(newVector); + } + + public static boolean isColliding(Cuboid newPlot) { + for (Plot plot : plots) { + Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), plot.getCreatedLocation().getWorld()); + for (BlockVector2 vector2 : region.getWalls()) { + if (vector2.containedWithin(newPlot.getMinimumPoint(), newPlot.getMaximumPoint())) { + return true; + } + } + } + return false; + } + + private static AreaMarker getAreaMarker(String areaMarkerName) { + for (AreaMarker areaMarker : VirtualRealty.markerset.getAreaMarkers()) { + if (areaMarker.getMarkerID().equalsIgnoreCase(areaMarkerName)) { + return areaMarker; + } + } + return null; + } + + public static void resetPlotMarker(Plot plot) { + if (!VirtualRealty.isDynmapPresent) return; + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + String ownedBy; + double opacity; + int color; + if (plot.getOwnedBy() == null) { + ownedBy = "Available"; + color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.getHexColor(); + opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.opacity; + } else { + ownedBy = plot.getPlotOwner().getName(); + color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.getHexColor(); + opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.opacity; + } + if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.OWNED && plot.getOwnedBy() == null) return; + if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.AVAILABLE && plot.getOwnedBy() != null) return; + AreaMarker marker = getAreaMarker("virtualrealty.plots." + plot.getID()); + if (marker == null) { + marker = VirtualRealty.markerset.createAreaMarker("virtualrealty.plots." + plot.getID(), + + plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true, + + plot.getCreatedWorld(), new double[]{plot.getXMin(), plot.getXMax()}, new double[]{plot.getZMin(), plot.getZMax()}, true); + + areaMarkers.add(marker); + } else { + marker.setLabel( + + plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true); + + } + marker.setFillStyle(opacity, color); + marker.setLineStyle(2, 0.8, 0x474747); + marker.setMarkerSet(VirtualRealty.markerset); + } + + public static void removeDynMapMarker(Plot plot) { + if (!VirtualRealty.isDynmapPresent || VirtualRealty.dapi == null || VirtualRealty.markerset == null) return; + AreaMarker marker = VirtualRealty.markerset.findAreaMarker("virtualrealty.plots." + plot.getID()); + areaMarkers.remove(marker); + marker.deleteMarker(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java b/src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java new file mode 100644 index 0000000..7c0868b --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java @@ -0,0 +1,187 @@ +package com.modnmetl.virtualrealty.objects; + +import com.modnmetl.virtualrealty.objects.math.BlockVector2; +import com.modnmetl.virtualrealty.objects.math.BlockVector3; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class Cuboid { + + private final int xMin; + private final int xMax; + private final int yMin; + private final int yMax; + private final int zMin; + private final int zMax; + private final double xMinCentered; + private final double xMaxCentered; + private final double yMinCentered; + private final double yMaxCentered; + private final double zMinCentered; + private final double zMaxCentered; + private final World world; + + public Cuboid(Location point1, Location point2) { + this.xMin = Math.min(point1.getBlockX(), point2.getBlockX()); + this.xMax = Math.max(point1.getBlockX(), point2.getBlockX()); + this.yMin = Math.min(point1.getBlockY(), point2.getBlockY()); + this.yMax = Math.max(point1.getBlockY(), point2.getBlockY()); + this.zMin = Math.min(point1.getBlockZ(), point2.getBlockZ()); + this.zMax = Math.max(point1.getBlockZ(), point2.getBlockZ()); + this.world = point1.getWorld(); + this.xMinCentered = this.xMin + 0.5; + this.xMaxCentered = this.xMax + 0.5; + this.yMinCentered = this.yMin + 0.5; + this.yMaxCentered = this.yMax + 0.5; + this.zMinCentered = this.zMin + 0.5; + this.zMaxCentered = this.zMax + 0.5; + } + + public Cuboid(BlockVector3 point1, BlockVector3 point2, World world) { + this.xMin = Math.min(point1.getBlockX(), point2.getBlockX()); + this.xMax = Math.max(point1.getBlockX(), point2.getBlockX()); + this.yMin = Math.min(point1.getBlockY(), point2.getBlockY()); + this.yMax = Math.max(point1.getBlockY(), point2.getBlockY()); + this.zMin = Math.min(point1.getBlockZ(), point2.getBlockZ()); + this.zMax = Math.max(point1.getBlockZ(), point2.getBlockZ()); + this.world = world; + this.xMinCentered = this.xMin + 0.5; + this.xMaxCentered = this.xMax + 0.5; + this.yMinCentered = this.yMin + 0.5; + this.yMaxCentered = this.yMax + 0.5; + this.zMinCentered = this.zMin + 0.5; + this.zMaxCentered = this.zMax + 0.5; + } + + + public List blockList() { + ArrayList bL = new ArrayList<>((xMax - xMin) * (yMax - yMin) * (zMax - zMin)); + for(int x = this.xMin; x <= this.xMax; ++x) { + for(int y = this.yMin; y <= this.yMax; ++y) { + for(int z = this.zMin; z <= this.zMax; ++z) { + Block b = this.world.getBlockAt(x, y, z); + bL.add(b); + } + } + } + return bL; + } + + public Location getCenter() { + return new Location(this.world, (this.xMax - this.xMin) / 2 + this.xMin + 1, (this.yMax - this.yMin) / 2 + this.yMin, (this.zMax - this.zMin) / 2 + this.zMin + 1); + } + + public BlockVector3 getCenterVector() { + return BlockVector3.at((this.xMax - this.xMin) / 2 + this.xMin + 1, (this.yMax - this.yMin) / 2 + this.yMin, (this.zMax - this.zMin) / 2 + this.zMin + 1); + } + + public double getDistance() { + return this.getPoint1().distance(this.getPoint2()); + } + + public double getDistanceSquared() { + return this.getPoint1().distanceSquared(this.getPoint2()); + } + + public int getHeight() { + return this.yMax - this.yMin + 1; + } + + public BlockVector3 getMinimumPoint() { + return BlockVector3.at(this.xMin, this.yMin, this.zMin); + } + + public BlockVector3 getMaximumPoint() { + return BlockVector3.at(this.xMax, this.yMax, this.zMax); + } + + public Location getPoint1() { + return new Location(this.world, this.xMin, this.yMin, this.zMin); + } + + public Location getPoint2() { + return new Location(this.world, this.xMax, this.yMax, this.zMax); + } + + public Location getRandomLocation() { + Random rand = new Random(); + int x = rand.nextInt(Math.abs(this.xMax - this.xMin) + 1) + this.xMin; + int y = rand.nextInt(Math.abs(this.yMax - this.yMin) + 1) + this.yMin; + int z = rand.nextInt(Math.abs(this.zMax - this.zMin) + 1) + this.zMin; + return new Location(this.world, x, y, z); + } + + public boolean contains(BlockVector3 vector3) { + return vector3.getBlockX() >= this.xMin && vector3.getBlockX() <= this.xMax && vector3.getBlockY() >= this.yMin && vector3.getBlockY() <= this.yMax && vector3 + .getBlockZ() >= this.zMin && vector3.getBlockZ() <= this.zMax; + } + + public boolean contains(BlockVector3 vector3, World world) { + return world == this.world && vector3.getBlockX() >= this.xMin && vector3.getBlockX() <= this.xMax && vector3.getBlockY() >= this.yMin && vector3.getBlockY() <= this.yMax && vector3 + .getBlockZ() >= this.zMin && vector3.getBlockZ() <= this.zMax; + } + + public int getTotalBlockSize() { + return this.getHeight() * this.getXWidth() * this.getZWidth(); + } + + public int getXWidth() { + return this.xMax - this.xMin + 1; + } + + public int getZWidth() { + return this.zMax - this.zMin + 1; + } + + public boolean isIn(Location loc) { + return loc.getWorld() == this.world && loc.getBlockX() >= this.xMin && loc.getBlockX() <= this.xMax && loc.getBlockY() >= this.yMin && loc.getBlockY() <= this.yMax && loc + .getBlockZ() >= this.zMin && loc.getBlockZ() <= this.zMax; + } + + public boolean isIn(Player player) { + return this.isIn(player.getLocation()); + } + + public boolean isInWithMarge(Location loc, double marge) { + return loc.getWorld() == this.world && loc.getX() >= this.xMinCentered - marge && loc.getX() <= this.xMaxCentered + marge && loc.getY() >= this.yMinCentered - marge && loc + .getY() <= this.yMaxCentered + marge && loc.getZ() >= this.zMinCentered - marge && loc.getZ() <= this.zMaxCentered + marge; + } + + public boolean isColliding(Cuboid region) { + List flatRegion1 = new ArrayList<>(this.getFlatRegion()); + List flatRegion2 = new ArrayList<>(region.getFlatRegion()); + for (BlockVector2 vector1 : flatRegion1) { + for (BlockVector2 vector2 : flatRegion2) + if (vector1.getBlockX() == vector2.getBlockX() && vector1.getBlockZ() == vector2.getBlockZ()) return true; + } + return false; + } + + public List getFlatRegion() { + List blocksVector = new ArrayList<>(); + for (Block block : blockList()) { + blocksVector.add(BlockVector2.at(block.getLocation().getBlockX(), block.getLocation().getBlockZ())); + } + return blocksVector; + } + + public List getWalls() { + List walls = new ArrayList<>(); + for (int z = zMin; z <= zMax; z++) { + walls.add(BlockVector2.at(xMin, z)); + walls.add(BlockVector2.at(xMax, z)); + } + for (int x = xMin; x < xMax; x++) { + walls.add(BlockVector2.at(x, zMin)); + walls.add(BlockVector2.at(x, zMax)); + } + return walls; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java b/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java new file mode 100644 index 0000000..96f0949 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java @@ -0,0 +1,796 @@ +package com.modnmetl.virtualrealty.objects; + +import com.modnmetl.virtualrealty.enums.Direction; +import com.modnmetl.virtualrealty.enums.Permission; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.sql.SQL; +import com.modnmetl.virtualrealty.utils.SchematicUtil; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.math.BlockVector3; +import org.apache.commons.io.FileUtils; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.*; + +public class Plot { + + private int ID; + private UUID ownedBy; + private Set members; + private String assignedBy; + private LocalDateTime ownedUntilDate; + private PlotSize plotSize; + private int length; + private int width; + private int height; + private Material floorMaterial; + private byte floorData; + private Material borderMaterial; + private byte borderData; + private Location createdLocation; + private Direction createdDirection; + private BlockVector3 bottomLeftCorner; + private BlockVector3 topRightCorner; + private BlockVector3 borderBottomLeftCorner; + private BlockVector3 borderTopRightCorner; + private GameMode selectedGameMode; + private String createdWorld; + private Instant modified; + + @Override + public String toString() { + return "{ ID: " + ID + ", ownedBy: " + ownedBy + "}"; + } + + public Plot(Location location, Material floorMaterial, Material borderMaterial, PlotSize plotSize) { + this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; + this.ownedBy = null; + this.members = new HashSet<>(); + this.assignedBy = null; + this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); + this.floorMaterial = floorMaterial; + this.floorData = 0; + this.borderMaterial = borderMaterial; + this.borderData = 0; + this.plotSize = plotSize; + this.length = plotSize.getLength(); + this.width = plotSize.getWidth(); + this.height = plotSize.getHeight(); + this.createdLocation = location; + this.createdDirection = Direction.byYaw(location.getYaw()); + this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); + this.createdWorld = location.getWorld().getName(); + this.modified = Instant.now(); + initialize(); + initializeCorners(); + if (VirtualRealty.markerset != null) { + PlotManager.resetPlotMarker(this); + } + } + + public Plot(Location location, Material floorMaterial, Material borderMaterial, int length, int width, int height) { + this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; + this.ownedBy = null; + this.members = new HashSet<>(); + this.assignedBy = null; + this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); + this.floorMaterial = floorMaterial; + this.floorData = 0; + this.borderMaterial = borderMaterial; + this.borderData = 0; + this.plotSize = PlotSize.CUSTOM; + this.length = length; + this.width = width; + this.height = height; + this.createdLocation = location; + this.createdDirection = Direction.byYaw(location.getYaw()); + this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); + this.createdWorld = location.getWorld().getName(); + this.modified = Instant.now(); + initialize(); + initializeCorners(); + if (VirtualRealty.markerset != null) { + PlotManager.resetPlotMarker(this); + } + } + + + public Plot(ResultSet rs) { + try { + this.ID = rs.getInt("ID"); + this.ownedBy = rs.getString("ownedBy").isEmpty() ? null : UUID.fromString(rs.getString("ownedBy")); + this.members = new HashSet<>(); + String membersString = rs.getString("members"); + if (membersString != null && !membersString.isEmpty()) { + String[] membersArray = membersString.substring(0, membersString.length() - 1).split(";"); + for (String s : membersArray) { + members.add(UUID.fromString(s)); + } + } + this.assignedBy = rs.getString("assignedBy").equalsIgnoreCase("null") ? null : rs.getString("assignedBy"); + this.ownedUntilDate = rs.getTimestamp("ownedUntilDate").toLocalDateTime(); + this.floorMaterial = Material.getMaterial(rs.getString("floorMaterial").split(":")[0]); + this.floorData = rs.getString("floorMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("floorMaterial").split(":")[1]); + if (rs.getString("borderMaterial") != null) { + this.borderMaterial = Material.getMaterial(rs.getString("borderMaterial").split(":")[0]); + this.borderData = rs.getString("borderMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("borderMaterial").split(":")[1]); + } + this.plotSize = PlotSize.valueOf(rs.getString("plotSize")); + this.length = rs.getInt("length"); + this.width = rs.getInt("width"); + this.height = rs.getInt("height"); + ArrayList location = new ArrayList<>(Arrays.asList(rs.getString("createdLocation").subSequence(0, rs.getString("createdLocation").length() - 1).toString().split(";"))); + Location createLocation = new Location(Bukkit.getWorld(location.get(0)), Double.parseDouble(location.get(1)), Double.parseDouble(location.get(2)), Double.parseDouble(location.get(3)), Float.parseFloat(location.get(4)), Float.parseFloat(location.get(5))); + this.createdLocation = rs.getString("createdLocation").isEmpty() ? null : createLocation; + this.createdDirection = Direction.byYaw(createdLocation.getYaw()); + this.selectedGameMode = GameMode.CREATIVE; + this.createdWorld = location.get(0); + if (floorMaterial == null) { + floorMaterial = plotSize.getFloorMaterial(); + floorData = plotSize.getFloorData(); + } + if (borderMaterial == null) { + borderMaterial = plotSize.getBorderMaterial(); + borderData = plotSize.getBorderData(); + } + initializeCorners(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public boolean hasPermissionToPlot(Player player) { + if (player.hasPermission(Permission.PLOT_BUILD.getPermission())) return true; + if (members.contains(player.getUniqueId())) return true; + return ownedBy != null && ownedBy.equals(player.getUniqueId()); + } + + public boolean hasPlotMembership(Player player) { + if (members.contains(player.getUniqueId())) return true; + return ownedBy != null && ownedBy.equals(player.getUniqueId()); + } + + public boolean isOwnershipExpired() { + return ownedUntilDate.isBefore(LocalDateTime.now()); + } + + public int getXMin() { + return Math.min(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); + } + + public int getXMax() { + return Math.max(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); + } + + public int getZMin() { + return Math.min(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); + } + + public int getZMax() { + return Math.max(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); + } + + public int getID() { + return ID; + } + + public void setID(int ID) { + this.ID = ID; + } + + public UUID getOwnedBy() { + return ownedBy; + } + + public void setOwnedBy(UUID ownedBy) { + this.ownedBy = ownedBy; + members.remove(ownedBy); + updateMarker(); + modified(); + } + + public String getAssignedBy() { + return assignedBy; + } + + public void setAssignedBy(String assignedBy) { + this.assignedBy = assignedBy; + modified(); + } + + public LocalDateTime getOwnedUntilDate() { + return ownedUntilDate; + } + + public void setOwnedUntilDate(LocalDateTime ownedUntilDate) { + this.ownedUntilDate = ownedUntilDate; + updateMarker(); + modified(); + } + + public PlotSize getPlotSize() { + return plotSize; + } + + public void setPlotSize(PlotSize plotSize) { + this.plotSize = plotSize; + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + public Material getFloorMaterial() { + return floorMaterial; + } + + public void setFloorMaterial(Material floorMaterial, byte data) { + this.floorMaterial = floorMaterial; + this.floorData = data; + initializeFloor(); + modified(); + } + + public Location getCreatedLocation() { + return createdLocation; + } + + public void setBorderMaterial(Material borderMaterial, byte data) { + this.borderMaterial = borderMaterial; + this.borderData = data; + modified(); + } + + public Material getBorderMaterial() { + return borderMaterial; + } + + public void setCreatedLocation(Location createdLocation) { + this.createdLocation = createdLocation; + } + + public BlockVector3 getBottomLeftCorner() { + return bottomLeftCorner; + } + + public void setBottomLeftCorner(BlockVector3 bottomLeftCorner) { + this.bottomLeftCorner = bottomLeftCorner; + } + + public BlockVector3 getTopRightCorner() { + return topRightCorner; + } + + public void setTopRightCorner(BlockVector3 topRightCorner) { + this.topRightCorner = topRightCorner; + } + + public BlockVector3 getBorderBottomLeftCorner() { + return borderBottomLeftCorner; + } + + public void setBorderBottomLeftCorner(BlockVector3 borderBottomLeftCorner) { + this.borderBottomLeftCorner = borderBottomLeftCorner; + } + + public BlockVector3 getBorderTopRightCorner() { + return borderTopRightCorner; + } + + public void setBorderTopRightCorner(BlockVector3 borderTopRightCorner) { + this.borderTopRightCorner = borderTopRightCorner; + } + + public BlockVector3 getBorderedCenter() { + return new Cuboid(borderBottomLeftCorner, borderTopRightCorner, createdLocation.getWorld()).getCenterVector(); + } + + public BlockVector3 getCenter() { + return new Cuboid(bottomLeftCorner, topRightCorner, createdLocation.getWorld()).getCenterVector(); + } + + public GameMode getSelectedGameMode() { + return selectedGameMode; + } + + public String getCreatedWorld() { + return createdWorld; + } + + public OfflinePlayer getPlotOwner() { + return ownedBy == null ? null : Bukkit.getOfflinePlayer(ownedBy); + } + + public void setSelectedGameMode(GameMode selectedGameMode) { + this.selectedGameMode = selectedGameMode; + } + + public void addMember(UUID uuid) { + members.add(uuid); + modified(); + } + + public void removeMember(UUID uuid) { + members.remove(uuid); + } + + public Set getMembers() { + return members; + } + + public Set getMembersPlayer() { + Set offlinePlayers = new HashSet<>(); + for (UUID member : members) { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(member); + offlinePlayers.add(offlinePlayer); + } + return offlinePlayers; + } + + private void setFloorBlock(Block floorBlock) { + if (VirtualRealty.isLegacy) { + try { + Method m = Block.class.getDeclaredMethod("setType", Material.class); + m.setAccessible(true); + m.invoke(floorBlock, this.floorMaterial); + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(floorBlock, this.floorData); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + floorBlock.setType(floorMaterial); + } + modified(); + } + + private void initializeFloor() { + Location location = createdLocation; + Direction direction = Direction.byYaw(location.getYaw()); + switch(direction) { + case SOUTH: { + for (int x = location.getBlockX() - width + 1; x < location.getBlockX() + 1; x++) { + for (int z = location.getBlockZ(); z < location.getBlockZ() + length; z++) { + Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); + setFloorBlock(floorBlock); + } + } + break; + } + case WEST: { + for (int x = location.getBlockX() - length + 1; x < location.getBlockX() + 1; x++) { + for (int z = location.getBlockZ() - width + 1; z < location.getBlockZ() + 1; z++) { + Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); + setFloorBlock(floorBlock); + } + } + break; + } + case NORTH: { + for (int x = location.getBlockX(); x < location.getBlockX() + width; x++) { + for (int z = location.getBlockZ() - length + 1; z < location.getBlockZ() + 1; z++) { + Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); + setFloorBlock(floorBlock); + } + } + break; + } + case EAST: { + for (int x = location.getBlockX(); x < location.getBlockX() + length; x++) { + for (int z = location.getBlockZ(); z < location.getBlockZ() + width; z++) { + Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); + setFloorBlock(floorBlock); + } + } + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + } + + public void initializeCorners() { + Location location = createdLocation; + Direction direction = Direction.byYaw(location.getYaw()); + Location location1; + Location location2; + Location border1; + Location border2; + switch(direction) { + case SOUTH: { + location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); + location2 = new Location(location.getWorld(), location.getBlockX() - width + 1, location.getBlockY() + height, location.getBlockZ() + length - 1); + border1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); + border2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); + break; + } + case WEST: { + location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); + location2 = new Location(location.getWorld(), location.getBlockX() - length + 1, location.getBlockY() + height, location.getBlockZ() - width + 1); + border1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); + border2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); + break; + } + case NORTH: { + location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); + location2 = new Location(location.getWorld(), location.getBlockX() + width - 1, location.getBlockY() + height, location.getBlockZ() - length + 1); + border1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); + border2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); + break; + } + case EAST: { + location1 = new Location(location.getWorld(), location.getBlockX() + length - 1, location.getBlockY() - 10, location.getBlockZ()); + location2 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() + height, location.getBlockZ() + width - 1); + border1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); + border2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + this.bottomLeftCorner = BlockVector3.at(location1.getBlockX(), location1.getBlockY(), location1.getBlockZ()); + this.topRightCorner = BlockVector3.at(location2.getBlockX(), location2.getBlockY(), location2.getBlockZ()); + this.borderBottomLeftCorner = BlockVector3.at(border1.getBlockX(), border1.getBlockY(), border1.getBlockZ()); + this.borderTopRightCorner = BlockVector3.at(border2.getBlockX(), border2.getBlockY(), border2.getBlockZ()); + } + + public void initialize() { + prepareBlocks(createdLocation); + } + + public Set getBorderBlocks() { + Set blocks = new HashSet<>(); + Location location = this.getCreatedLocation(); + Direction direction = Direction.byYaw(location.getYaw()); + int maxX; + int maxZ; + int minX; + int minZ; + switch(direction) { + case SOUTH: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + length + 1; + minX = location.getBlockX() - width + 1; + minZ = location.getBlockZ() - 1; + break; + } + case WEST: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX() - length + 1; + minZ = location.getBlockZ() - width; + break; + } + case NORTH: { + maxX = location.getBlockX() + width + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - length; + break; + } + case EAST: { + maxX = location.getBlockX() + length + 1; + maxZ = location.getBlockZ() + width + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - 1; + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + for (int x = minX - 1; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { + blocks.add(location.getWorld().getBlockAt(x, location.getBlockY() + 1, z)); + } + } + } + return blocks; + } + + public Set getFloorBlocks() { + Set blocks = new HashSet<>(); + Location location = this.getCreatedLocation(); + Direction direction = Direction.byYaw(location.getYaw()); + int maxX; + int maxZ; + int minX; + int minZ; + switch(direction) { + case SOUTH: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + length + 1; + minX = location.getBlockX() - width + 1; + minZ = location.getBlockZ() - 1; + break; + } + case WEST: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX() - length + 1; + minZ = location.getBlockZ() - width; + break; + } + case NORTH: { + maxX = location.getBlockX() + width + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - length; + break; + } + case EAST: { + maxX = location.getBlockX() + length + 1; + maxZ = location.getBlockZ() + width + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - 1; + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + for (int x = minX - 1; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + blocks.add(location.getWorld().getBlockAt(x, location.getBlockY(), z)); + } + } + return blocks; + } + + public void setBorder(Material material, byte data) { + borderMaterial = material; + borderData = data; + for (Block borderBlock : getBorderBlocks()) { + if (VirtualRealty.isLegacy) { + borderBlock.setType(material); + try { + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(borderBlock, data); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } else { + borderBlock.setType(material); + } + } + modified(); + } + + public void prepareBlocks(Location location) { + Direction direction = Direction.byYaw(location.getYaw()); + Location location1; + Location location2; + switch (direction) { + case SOUTH: { + location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); + location2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); + break; + } + case WEST: { + location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); + location2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); + break; + } + case NORTH: { + location1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); + location2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); + break; + } + case EAST: { + location1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); + location2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); + break; + } + } + for (Block floorBlock : getFloorBlocks()) { + for (int y = location.getBlockY() + height; y > location.getBlockY() - 1; y--) { + Block airBlock = location.getWorld().getBlockAt(floorBlock.getX(), y, floorBlock.getZ()); + airBlock.setType(Material.AIR); + } + floorBlock.setType(floorMaterial); + if (VirtualRealty.isLegacy) { + try { + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(floorBlock, plotSize.getFloorData()); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } + } + int maxX = 0; + int maxZ = 0; + int minX = 0; + int minZ = 0; + switch(direction) { + case SOUTH: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + length + 1; + minX = location.getBlockX() - width + 1; + minZ = location.getBlockZ() - 1; + break; + } + case WEST: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX() - length + 1; + minZ = location.getBlockZ() - width; + break; + } + case NORTH: { + maxX = location.getBlockX() + width + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - length; + break; + } + case EAST: { + maxX = location.getBlockX() + length + 1; + maxZ = location.getBlockZ() + width + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - 1; + break; + } + } + for (int x = minX - 1; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { + Block borderBlock = location.getWorld().getBlockAt(x, location.getBlockY() + 1, z); + if (VirtualRealty.isLegacy) { + borderBlock.setType(plotSize.getBorderMaterial()); + try { + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(borderBlock, plotSize.getBorderData()); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } else { + borderBlock.setType(plotSize.getBorderMaterial()); + } + } + } + } + } + + public void unloadPlot() { + switch (createdDirection) { + case SOUTH: { + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - width, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); + break; + } + case WEST: { + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - length, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - width)); + break; + } + case NORTH: { + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - length)); + break; + } + case EAST: { + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); + break; + } + } + } + + public String getMembersString() { + StringBuilder stringBuilder = new StringBuilder(); + for (UUID member : members) { + stringBuilder.append(member.toString()).append(";"); + } + return stringBuilder.toString(); + } + + public void insert() { + StringBuilder builder = new StringBuilder(); + builder.append(this.createdLocation.getWorld().getName() + ";"); + builder.append(this.createdLocation.getX() + ";"); + builder.append(this.createdLocation.getY() + ";"); + builder.append(this.createdLocation.getZ() + ";"); + builder.append(this.createdLocation.getYaw() + ";"); + builder.append(this.createdLocation.getPitch() + ";"); + try { + SQL.getStatement().execute("INSERT INTO `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + + "` (`ID`, `ownedBy`, `members`, `assignedBy`, `ownedUntilDate`," + + " `floorMaterial`, `borderMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`, `created`, `modified`) " + + "VALUES ('" + this.ID + "', '" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "','" + getMembersString() + "', '" + this.assignedBy + "', " + + "'" + Timestamp.valueOf(this.ownedUntilDate) + "', '" + this.floorMaterial + ":" + this.floorData + "', '" + this.borderMaterial + ":" + this.borderData + "'," + + " '" + this.plotSize + "', '" + this.length + "', '" + this.width + "', '" + this.height + "', '" + builder + "', '" + Timestamp.from(Instant.now()) + "', '" + Timestamp.from(Instant.now()) + "')"); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void update() { + try { + SQL.getStatement().execute("UPDATE `" + + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + + "` SET `ownedBy`='" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "'," + + " `members`='" + getMembersString() + "', `assignedBy`='" + this.assignedBy + "'," + + " `ownedUntilDate`='" + Timestamp.valueOf(this.ownedUntilDate) + "'," + + " `floorMaterial`='" + this.floorMaterial + ":" + this.floorData + "'," + + " `borderMaterial`='" + this.borderMaterial + ":" + this.borderData + "'," + + " `plotSize`='" + this.plotSize + "'," + + " `length`='" + this.length + "'," + + " `width`='" + this.width + "'," + + " `height`='" + this.height + "'," + + " `modified`='" + (this.modified != null ? Timestamp.from(this.modified) : Timestamp.from(Instant.now())) + "'" + + " WHERE `ID`='" + this.ID + "'"); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void remove() { + this.unloadPlot(); + PlotManager.removeDynMapMarker(this); + try { + SQL.getStatement().execute("DELETE FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` WHERE `ID` = '" + ID + "';"); + } catch (SQLException e) { + e.printStackTrace(); + } + int id = ID; + File file = new File(VirtualRealty.plotsSchemaFolder, "plot" + id + ".region"); + if (file.exists()) + FileUtils.deleteQuietly(file); + PlotManager.plots.remove(this); + } + + public Direction getCreatedDirection() { + return createdDirection; + } + + public void setCreatedDirection(Direction createdDirection) { + this.createdDirection = createdDirection; + } + + public void updateMarker() { + PlotManager.resetPlotMarker(this); + } + + public void modified() { + this.modified = Instant.now(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector2.java b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector2.java new file mode 100644 index 0000000..6512d7e --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector2.java @@ -0,0 +1,44 @@ +package com.modnmetl.virtualrealty.objects.math; + +import java.util.Vector; + +public class BlockVector2 extends Vector { + + private int x; + private int z; + + public BlockVector2(int x, int z) { + this.x = x; + this.z = z; + } + + public static BlockVector2 at(int x, int z) { + return new BlockVector2(x, z); + } + + public int getBlockX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getBlockZ() { + return z; + } + + public void setZ(int z) { + this.z = z; + } + + public boolean containedWithin(BlockVector2 min, BlockVector2 max) { + return this.x >= min.x && this.x <= max.x && this.z >= min.z && this.z <= max.z; + } + + @Override + public String toString() { + return "(" + x + ", " + z + ")"; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java new file mode 100644 index 0000000..8c217a9 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java @@ -0,0 +1,59 @@ +package com.modnmetl.virtualrealty.objects.math; + +import org.bukkit.Location; + +public class BlockVector3 extends BlockVector2 { + + private int x; + private int y; + private int z; + + private BlockVector3(int x, int y, int z) { + super(x, z); + this.x = x; + this.y = y; + this.z = z; + } + + public static BlockVector3 at(int x, int y, int z) { + return new BlockVector3(x, y, z); + } + + public static BlockVector3 locationToVector(Location location) { + return new BlockVector3(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + } + + public int getBlockX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getBlockY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + public int getBlockZ() { + return z; + } + + public void setZ(int z) { + this.z = z; + } + + @Override + public String toString() { + return "(" + x + ", " + y + ", " + z + ")"; + } + + public String toSimpleString() { + return x + ", " + y + ", " + z; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java b/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java new file mode 100644 index 0000000..8c7d23b --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java @@ -0,0 +1,123 @@ +package com.modnmetl.virtualrealty.registry; + +import com.modnmetl.virtualrealty.managers.PlotManager; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.entity.Player; + +public class VirtualPlaceholders extends PlaceholderExpansion { + + private final VirtualRealty plugin; + + /** + * Since we register the expansion inside our own plugin, we + * can simply use this method here to get an instance of our + * plugin. + * + * @param plugin + * The instance of our plugin. + */ + public VirtualPlaceholders(VirtualRealty plugin){ + this.plugin = plugin; + } + + /** + * Because this is an internal class, + * you must override this method to let PlaceholderAPI know to not unregister your expansion class when + * PlaceholderAPI is reloaded + * + * @return true to persist through reloads + */ + @Override + public boolean persist(){ + return true; + } + + /** + * Because this is a internal class, this check is not needed + * and we can simply return {@code true} + * + * @return Always true since it's an internal class. + */ + @Override + public boolean canRegister(){ + return true; + } + + /** + * The name of the person who created this expansion should go here. + *
For convienience do we return the author from the plugin.yml + * + * @return The name of the author as a String. + */ + @Override + public String getAuthor(){ + return plugin.getDescription().getAuthors().toString(); + } + + /** + * The placeholder identifier should go here. + *
This is what tells PlaceholderAPI to call our onRequest + * method to obtain a value if a placeholder starts with our + * identifier. + *
The identifier has to be lowercase and can't contain _ or % + * + * @return The identifier in {@code %_%} as String. + */ + @Override + public String getIdentifier(){ + return "virtualrealty"; + } + + /** + * This is the version of the expansion. + *
You don't have to use numbers, since it is set as a String. + * + * For convienience do we return the version from the plugin.yml + * + * @return The version as a String. + */ + @Override + public String getVersion(){ + return plugin.getDescription().getVersion(); + } + + /** + * This is the method called when a placeholder with our identifier + * is found and needs a value. + *
We specify the value identifier in this method. + *
Since version 2.9.1 can you use OfflinePlayers in your requests. + * + * @param player + * A {@link org.bukkit.entity.Player Player}. + * @param identifier + * A String containing the identifier/value. + * + * @return possibly-null String of the requested identifier. + */ + @Override + public String onPlaceholderRequest(Player player, String identifier){ + if(player == null) + return ""; + + Plot plot = PlotManager.getBorderedPlot(player.getLocation()); + if (identifier.equals("plot_id")) { + if (plot == null) return ""; + return String.valueOf(plot.getID()); + } + if (identifier.equals("plot_owner")) { + if (plot == null) return ""; + if (plot.getOwnedBy() == null) return ""; + return String.valueOf(plot.getPlotOwner().getName()); + } + if (identifier.equals("is_plot_owner")) { + if (plot == null) return ""; + if (plot.getOwnedBy() == null) return "false"; + if (plot.getOwnedBy().equals(player.getUniqueId())) return "true"; + return "false"; + } + return null; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/sql/SQL.java b/src/main/java/com/modnmetl/virtualrealty/sql/SQL.java new file mode 100644 index 0000000..17d4854 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/sql/SQL.java @@ -0,0 +1,120 @@ +package com.modnmetl.virtualrealty.sql; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.configs.PluginConfiguration; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +public class SQL { + + private static Connection connection; + private static Statement statement; + public static final long MYSQL_TIMEOUT_MS = 28800000; + private static long lastQuery = System.currentTimeMillis(); + + public static void connect() { + try { + switch (VirtualRealty.getPluginConfiguration().dataModel) { + case SQLITE: { + Class.forName("org.sqlite.JDBC"); + File dataDir = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + File.separator + "data"); + if (!dataDir.exists()) { + dataDir.mkdirs(); + } + connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + File.separator + "data" + File.separator + "data.db"); + break; + } + case MYSQL: { + Class.forName("com.mysql.jdbc.Driver"); + connection = DriverManager.getConnection("jdbc:mysql://" + VirtualRealty.getPluginConfiguration().mysql.hostname + ":" + VirtualRealty.getPluginConfiguration().mysql.port + "/" + VirtualRealty.getPluginConfiguration().mysql.database + "?useSSL=" + VirtualRealty.getPluginConfiguration().mysql.useSSL + "&autoReconnect=true", VirtualRealty.getPluginConfiguration().mysql.user, VirtualRealty.getPluginConfiguration().mysql.password); + break; + } + } + createStatement(); + } catch (SQLException | ClassNotFoundException ex) { + ex.printStackTrace(); + } + } + + public static void createStatement() { + try { + statement = connection.createStatement(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + public static void closeConnection() { + try { + if (statement != null && (VirtualRealty.getPluginConfiguration().dataModel != PluginConfiguration.DataModel.SQLITE && !statement.isClosed())) { + statement.close(); + } + if (connection != null) + connection.close(); + VirtualRealty.debug("Database connection closed"); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + public static void createTables() { + try { + statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); + updateTables(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + public static void updateTables() { + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `borderMaterial` VARCHAR(32) AFTER `floorMaterial`;"); + } catch (SQLException ignored) { + + } + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `members` TEXT AFTER `ownedBy`;"); + } catch (SQLException ignored) { + + } + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `created` DATETIME AFTER `createdLocation`;"); + } catch (SQLException ignored) { + + } + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `modified` DATETIME AFTER `created`;"); + } catch (SQLException ignored) { + + } + } + + public static Statement getStatement() { + try { + if (System.currentTimeMillis() - lastQuery > MYSQL_TIMEOUT_MS) { + connection.close(); + statement.close(); + connect(); + } else if(connection.isClosed()) { + connect(); + } + lastQuery = System.currentTimeMillis(); + } catch (SQLException e) { + e.printStackTrace(); + } + return statement; + } + + + public static void setConnection(Connection connection) { + SQL.connection = connection; + } + + public static void setStatement(Statement statement) { + SQL.statement = statement; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java b/src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java new file mode 100644 index 0000000..1e1b393 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java @@ -0,0 +1,46 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.configs.SizesConfiguration; +import eu.okaeri.configs.ConfigManager; +import eu.okaeri.configs.serdes.commons.SerdesCommons; +import eu.okaeri.configs.validator.okaeri.OkaeriValidator; +import eu.okaeri.configs.yaml.bukkit.YamlBukkitConfigurer; +import com.modnmetl.virtualrealty.configs.MessagesConfiguration; +import com.modnmetl.virtualrealty.configs.PluginConfiguration; + +import java.io.File; + +public class ConfigurationFactory { + + public ConfigurationFactory() { + + } + + public PluginConfiguration createPluginConfiguration(File pluginConfigurationFile) { + return ConfigManager.create(PluginConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); + it.withBindFile(pluginConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + + public SizesConfiguration createSizesConfiguration(File sizesConfigurationFile) { + return ConfigManager.create(SizesConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); + it.withBindFile(sizesConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + + public MessagesConfiguration createMessagesConfiguration(File messagesConfigurationFile) { + return ConfigManager.create(MessagesConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); + it.withBindFile(messagesConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/Permissions.java b/src/main/java/com/modnmetl/virtualrealty/utils/Permissions.java new file mode 100644 index 0000000..d1cc936 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/Permissions.java @@ -0,0 +1,27 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; + +public class Permissions { + + public static boolean hasPermission(CommandSender sender, Permission basePermission, String permission) { + Permission finalPermission = new Permission(basePermission.getName() + "." + permission); + if (!sender.hasPermission(finalPermission)) { + sender.sendMessage(VirtualRealty.PREFIX + "§cInsufficient permissions! §8(§7" + finalPermission.getName() + "§8)"); + return false; + } + return true; + } + + public static boolean hasPermission(CommandSender sender, String permission) { + Permission finalPermission = new Permission(permission); + if (!sender.hasPermission(finalPermission)) { + sender.sendMessage(VirtualRealty.PREFIX + "§cInsufficient permissions! §8(§7" + finalPermission.getName() + "§8)"); + return false; + } + return true; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java new file mode 100644 index 0000000..a4cc196 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java @@ -0,0 +1,41 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.enums.Direction; +import com.modnmetl.virtualrealty.objects.Cuboid; +import com.modnmetl.virtualrealty.objects.math.BlockVector3; +import org.bukkit.Location; + +public class PlotUtil { + + public static Cuboid getPlotRegion(Location location, Direction direction, int length, int width, int height) { + Location location1; + Location location2; + switch(direction) { + case SOUTH: { + location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); + location2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); + break; + } + case WEST: { + location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); + location2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); + break; + } + case NORTH: { + location1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); + location2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); + break; + } + case EAST: { + location1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); + location2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + return new Cuboid(BlockVector3.at(location1.getBlockX(), location1.getBlockY(), location1.getBlockZ()), + BlockVector3.at(location2.getBlockX(), location2.getBlockY(), location2.getBlockZ()), location.getWorld()); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java new file mode 100644 index 0000000..84c2450 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java @@ -0,0 +1,40 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.enums.Permission; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.Flag; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.time.LocalDateTime; + +public class ProtectionUtil { + + public static boolean canBuild(Player player, Location location) { + Plot plot = PlotManager.getBorderedPlot(location); + if (plot != null) { + if (plot.getOwnedBy() != null) { + if (!plot.getOwnedBy().equals(player.getUniqueId())) { + return false; + } else { + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + return false; + } + } + } else { + return false; + } + } + return true; + } + + public static boolean hasPermissionToWorld(Player player, Flag.World flag) { + if (player.hasPermission(Permission.WORLD_BUILD.getPermission())) return true; + if (player.hasPermission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".world." + flag.name().toLowerCase())) return true; + if (player.isOp()) return true; + return false; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java b/src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java new file mode 100644 index 0000000..95bd794 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java @@ -0,0 +1,271 @@ +package com.modnmetl.virtualrealty.utils; + +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.entity.Entity; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public final class Reflections { + + public static final String SERVER_VERSION = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + public static final boolean USE_PRE_13_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 13; + public static final boolean USE_PRE_12_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 12; + public static final boolean USE_PRE_9_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 9; + + private static final Map> CLASS_CACHE = new HashMap<>(); + private static final Map FIELD_CACHE = new HashMap<>(); + private static final Map> FIELD_ACCESSOR_CACHE = new HashMap<>(); + private static final Map METHOD_CACHE = new HashMap<>(); + private static final Class INVALID_CLASS = InvalidMarker.class; + private static final Method INVALID_METHOD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredMethod("invalidMethodMaker")); + private static final Field INVALID_FIELD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredField("invalidFieldMarker")); + private static final FieldAccessor INVALID_FIELD_ACCESSOR = getField(INVALID_CLASS, Void.class, 0); + + public static Class getClassOmitCache(String className) { + CLASS_CACHE.remove(className); + return getClass(className); + } + + public static Class getClass(String className) { + Class c = CLASS_CACHE.get(className); + + if (c != null) { + return c != INVALID_CLASS ? c : null; + } + + try { + c = Class.forName(className); + CLASS_CACHE.put(className, c); + } + catch (Exception ex) { + System.err.println("Could not retrieve class"); + + CLASS_CACHE.put(className, INVALID_CLASS); + } + return c; + } + + public static Class getNMSClass(String name) { + return getClass("net.minecraft.server." + SERVER_VERSION + "." + name); + } + + public static Class getCraftBukkitClass(String name) { + return getClass("org.bukkit.craftbukkit." + SERVER_VERSION + "." + name); + } + + public static Class getBukkitClass(String name) { + return getClass("org.bukkit." + name); + } + + public static Object getHandle(Entity entity) { + try { + return getMethod(entity.getClass(), "getHandle").invoke(entity); + } + catch (Exception ex) { + System.err.println("Could not get entity handle"); + return null; + } + } + + public static Object getHandle(World world) { + try { + return getMethod(world.getClass(), "getHandle").invoke(world); + } + catch (Exception ex) { + System.err.println("Could not get world handle"); + + return null; + } + } + + private static String constructFieldCacheKey(Class cl, String fieldName) { + return cl.getName() + "." + fieldName; + } + + public static Field getField(Class cl, String fieldName) { + String cacheKey = constructFieldCacheKey(cl, fieldName); + + Field field = FIELD_CACHE.get(cacheKey); + + if (field != null) { + return field != INVALID_FIELD ? field : null; + } + + try { + field = cl.getDeclaredField(fieldName); + FIELD_CACHE.put(cacheKey, field); + } + catch (Exception ex) { + System.err.println("Could not retrieve field"); + + FIELD_CACHE.put(cacheKey, INVALID_FIELD); + } + + return field; + } + + public static FieldAccessor getField(Class target, Class fieldType, int index) { + return getField(target, null, fieldType, index); + } + + @SuppressWarnings("unchecked") + private static FieldAccessor getField(Class target, String name, Class fieldType, int index) { + final String cacheKey = target.getName() + "." + (name != null ? name : "NONE") + "." + fieldType.getName() + "." + index; + + FieldAccessor output = (FieldAccessor) FIELD_ACCESSOR_CACHE.get(cacheKey); + + if (output != null) { + if (output == INVALID_FIELD_ACCESSOR) { + throw new IllegalArgumentException("Cannot find field with type " + fieldType); + } + + return output; + } + + for (final Field field : target.getDeclaredFields()) { + if ((name == null || field.getName().equals(name)) && fieldType.isAssignableFrom(field.getType()) && index-- <= 0) { + field.setAccessible(true); + + output = new FieldAccessor() { + + @Override + public T get(Object target) { + try { + return (T) field.get(target); + } catch (IllegalAccessException e) { + throw new RuntimeException("Cannot access reflection.", e); + } + } + + @Override + public void set(Object target, Object value) { + try { + field.set(target, value); + } catch (IllegalAccessException e) { + throw new RuntimeException("Cannot access reflection.", e); + } + } + + @Override + public boolean hasField(Object target) { + return field.getDeclaringClass().isAssignableFrom(target.getClass()); + } + }; + + break; + } + } + + if (output == null && target.getSuperclass() != null) { + output = getField(target.getSuperclass(), name, fieldType, index); + } + + FIELD_ACCESSOR_CACHE.put(cacheKey, output != null ? output : INVALID_FIELD_ACCESSOR); + + if (output == null) { + throw new IllegalArgumentException("Cannot find field with type " + fieldType); + } + + return output; + } + + public static Field getPrivateField(Class cl, String fieldName) { + String cacheKey = constructFieldCacheKey(cl, fieldName); + + Field c = FIELD_CACHE.get(cacheKey); + if (c != null) { + return c != INVALID_FIELD ? c : null; + } + + try { + c = cl.getDeclaredField(fieldName); + c.setAccessible(true); + FIELD_CACHE.put(cacheKey, c); + } + catch (Exception ex) { + System.err.println("Could not retrieve field"); + + FIELD_CACHE.put(cacheKey, INVALID_FIELD); + } + + return c; + } + + public static Method getMethod(Class cl, String method, Class... args) { + String cacheKey = cl.getName() + "." + method + "." + (args == null ? "NONE" : Arrays.toString(args)); + + Method output = METHOD_CACHE.get(cacheKey); + if (output != null) { + return output != INVALID_METHOD ? output : null; + } + + for (Method m : cl.getMethods()) { + if (m.getName().equals(method) && (args == null || classListEqual(args, m.getParameterTypes()))) { + output = m; + break; + } + } + + METHOD_CACHE.put(cacheKey, output == null ? INVALID_METHOD : output); + return output; + } + + public static Method getMethod(Class cl, String method) { + return getMethod(cl, method, null); + } + + public static Constructor getConstructor(Class clazz, Class... arguments) { + for (Constructor constructor : clazz.getDeclaredConstructors()) { + if (Arrays.equals(constructor.getParameterTypes(), arguments)) { + return constructor; + } + } + + return null; + } + + public static boolean classListEqual(Class[] l1, Class[] l2) { + if (l1.length != l2.length) { + return false; + } + + for (int i = 0; i < l1.length; i++) { + if (l1[i] != l2[i]) { + return false; + } + } + + return true; + } + + public interface ConstructorInvoker { + Object invoke(Object... arguments); + } + + public interface MethodInvoker { + Object invoke(Object target, Object... arguments); + } + + public interface FieldAccessor { + T get(Object target); + + void set(Object target, Object value); + + boolean hasField(Object target); + } + + private static class InvalidMarker { + public Void invalidFieldMarker; + public void invalidMethodMaker() {} + } + + private Reflections() {} + +} + diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java new file mode 100644 index 0000000..bfe1722 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java @@ -0,0 +1,27 @@ +package com.modnmetl.virtualrealty.utils; + +public class SafeUtil { + + private static void reportUnsafe(Throwable th) { + try { + throw new Exception(th.getMessage()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static T safeInit(SafeInitializer initializer) { + try { + return initializer.initialize(); + } catch (Exception e) { + reportUnsafe(e); + return null; + } + } + + @FunctionalInterface + public interface SafeInitializer { + T initialize() throws Exception; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java new file mode 100644 index 0000000..28f0670 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java @@ -0,0 +1,150 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.data.Data; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; + +import java.io.*; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.util.*; + +public class SchematicUtil { + + public static String[] getStructure(Block block, Block block2) { + long time = System.currentTimeMillis(); + int minX = Math.min(block.getX(), block2.getX()); + int minZ = Math.min(block.getZ(), block2.getZ()); + int minY = Math.min(block.getY(), block2.getY()); + int maxX = Math.max(block.getX(), block2.getX()); + int maxZ = Math.max(block.getZ(), block2.getZ()); + int maxY = Math.max(block.getY(), block2.getY()); + List blocks = new ArrayList<>(); + for (int x = minX; x <= maxX; ++x) { + for (int y = minY; y <= maxY; ++y) { + for (int z = minZ; z <= maxZ; ++z) { + Block b = block.getWorld().getBlockAt(x, y, z); + if (b.getType() != Material.AIR) { + if (VirtualRealty.isLegacy) { + blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getType().getId() + ";" + b.getData()); + } else { + blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getBlockData().getAsString().substring(10)); + } + } + } + } + } + VirtualRealty.debug("Getted and serialized blocks in: " + (System.currentTimeMillis() - time) + " ms"); + return blocks.toArray(new String[0]); + } + + public static void paste(int plotID, Location l) { + long time = System.currentTimeMillis(); + String[] blocks = load(plotID); + if (blocks == null) return; + Plot plot = PlotManager.getPlot(plotID); + Location location = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderBottomLeftCorner().getBlockX(), plot.getBorderBottomLeftCorner().getBlockY(), plot.getBorderBottomLeftCorner().getBlockZ()); + Location location2 = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderTopRightCorner().getBlockX(), plot.getBorderTopRightCorner().getBlockY(), plot.getBorderTopRightCorner().getBlockZ()); + Block pos1Block = location.getBlock(); + Block pos2Block = location2.getBlock(); + int minX = Math.min(pos1Block.getX(), pos2Block.getX()); + int minZ = Math.min(pos1Block.getZ(), pos2Block.getZ()); + int minY = Math.min(pos1Block.getY(), pos2Block.getY()); + int maxX = Math.max(pos1Block.getX(), pos2Block.getX()); + int maxZ = Math.max(pos1Block.getZ(), pos2Block.getZ()); + int maxY = Math.max(pos1Block.getY(), pos2Block.getY()); + for (int x = minX; x <= maxX; ++x) { + for (int y = minY; y <= maxY; ++y) { + for (int z = minZ; z <= maxZ; ++z) { + Block b = location.getWorld().getBlockAt(x, y, z); + b.setType(Material.AIR); + } + } + } + if (blocks[0].isEmpty()) return; + for (String block : blocks) { + String[] cords = block.split(";"); + int x = Integer.parseInt(cords[0]); + int y = Integer.parseInt(cords[1]); + int z = Integer.parseInt(cords[2]); + Location displaced = l.clone(); + displaced.add(x, y, z); + Block b = displaced.getBlock(); + if (VirtualRealty.isLegacy) { + try { + Method m = Block.class.getDeclaredMethod("setType", Material.class); + m.setAccessible(true); + m.invoke(b, VMaterial.getMaterial(Integer.parseInt(cords[3]))); + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(b, (byte) Integer.parseInt(cords[4])); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + BlockData blockData = Bukkit.createBlockData("minecraft:" + cords[3]); + b.setBlockData(blockData); + } + b.getState().update(true); + } + VirtualRealty.debug("Pasted in: " + (System.currentTimeMillis() - time) + " ms"); + } + + public static void save(int plotID, String[] blocks) { + long time = System.currentTimeMillis(); + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); + + StringBuilder stringBuilder = new StringBuilder(); + for (String s : blocks) { + stringBuilder.append(s).append("|"); + } + String plotString = stringBuilder.toString(); + if (plotString.isEmpty()) + plotString = "clear|"; + try { + new Data().compressData(plotString.substring(0, plotString.length() - 1).getBytes(StandardCharsets.UTF_8), f); + } catch (IOException e) { + e.printStackTrace(); + } + VirtualRealty.debug("Saved in: " + (System.currentTimeMillis() - time) + " ms"); + } + + public static String[] load(int plotID) { + long time = System.currentTimeMillis(); + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); + if (f.exists()) { + String loaded = null; + try { + loaded = new String(new Data().decompressData(f)); + } catch (IOException e) { + e.printStackTrace(); + } + if (loaded.equalsIgnoreCase("clear")) return new String[]{""}; + VirtualRealty.debug("Loaded in: " + (System.currentTimeMillis() - time) + " ms"); + return loaded.split("\\|"); + } + return null; + } + + public static List oldLoad(int plotID) { + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".schem"); + List loaded = new ArrayList<>(); + try { + FileInputStream streamIn = new FileInputStream(f); + ObjectInputStream objectinputstream = new ObjectInputStream(streamIn); + loaded = (List)objectinputstream.readObject(); + objectinputstream.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return loaded; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/UUIDUtils.java b/src/main/java/com/modnmetl/virtualrealty/utils/UUIDUtils.java new file mode 100644 index 0000000..f39d2a8 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/UUIDUtils.java @@ -0,0 +1,16 @@ +package com.modnmetl.virtualrealty.utils; + +import java.util.UUID; + +public class UUIDUtils { + + public static boolean isValidUUID(String uuidString) { + try { + UUID.fromString(uuidString); + return true; + } catch (Exception e) { + return false; + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/UpdateChecker.java b/src/main/java/com/modnmetl/virtualrealty/utils/UpdateChecker.java new file mode 100644 index 0000000..052b0f4 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/UpdateChecker.java @@ -0,0 +1,39 @@ +package com.modnmetl.virtualrealty.utils; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.modnmetl.virtualrealty.VirtualRealty; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +public class UpdateChecker { + + private static final String VERSION_URL = "https://api.spiget.org/v2/resources/95599/versions/latest"; + private static final String DESCRIPTION_URL = "https://api.spiget.org/v2/resources/95599/updates/latest"; + + public static String[] getUpdate() { + try { + JsonObject latestVersionObj = getURLResults(VERSION_URL); + String newVersion = latestVersionObj.get("name").getAsString(); + JsonObject updateDesc = getURLResults(DESCRIPTION_URL); + String updateName = updateDesc.get("title").getAsString(); + return new String[] { newVersion, updateName }; + } catch (IOException ex) { + VirtualRealty.getInstance().getLogger().severe("Failed to get plugin update information, is Spiget down?"); + return null; + } + } + + private static JsonObject getURLResults(String urlStr) throws IOException { + URL url = new URL(urlStr); + HttpURLConnection connection = (HttpURLConnection)url.openConnection(); + connection.addRequestProperty("User-Agent", "AdvancedTeleportPA"); + return new JsonParser().parse(new InputStreamReader(connection.getInputStream())).getAsJsonObject(); + } + +} + + diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java b/src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java new file mode 100644 index 0000000..f13a3ef --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java @@ -0,0 +1,31 @@ +package com.modnmetl.virtualrealty.utils.data; + +import java.io.*; +import java.util.zip.*; + +public class Data { + + public void compressData(byte[] data, File file) throws IOException { + try (OutputStream outputStream = new FileOutputStream(file)) { + Deflater d = new Deflater(); + DeflaterOutputStream dout = new DeflaterOutputStream(outputStream, d); + dout.write(data); + dout.close(); + } + } + + public byte[] decompressData(File file) throws IOException { + try (InputStream inputStream = new FileInputStream(file)) { + InflaterInputStream newInput = new InflaterInputStream(inputStream); + ByteArrayOutputStream bout = new ByteArrayOutputStream(512); + int b; + while ((b = newInput.read()) != -1) { + bout.write(b); + } + newInput.close(); + bout.close(); + return bout.toByteArray(); + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java new file mode 100644 index 0000000..159f406 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java @@ -0,0 +1,44 @@ +package com.modnmetl.virtualrealty.utils.multiversion; + +import com.modnmetl.virtualrealty.VirtualRealty; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class Chat { + + private final BaseComponent text; + + public Chat(BaseComponent text) { + this.text = text; + } + + public Chat(String text) { + this.text = new TextComponent(text); + } + + public void sendTo(CommandSender sender) { + if (sender instanceof Player) { + Player player = (Player) sender; + if (VirtualRealty.isLegacy) { + try { + Method m = Player.class.getDeclaredMethod("sendMessage", BaseComponent.class); + m.setAccessible(true); + m.invoke(player, text); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } else { + player.spigot().sendMessage(text); + } + } else { + sender.sendMessage(text.toLegacyText()); + } + } + + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java new file mode 100644 index 0000000..feac87d --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java @@ -0,0 +1,60 @@ +package com.modnmetl.virtualrealty.utils.multiversion; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.exceptions.MaterialMatchException; +import org.bukkit.Material; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class VMaterial { + + public static Material getMaterial(int materialID) throws MaterialMatchException { + if (VirtualRealty.isLegacy) { + try { + Method m = Material.class.getDeclaredMethod("getMaterial", int.class); + m.setAccessible(true); + return (Material) m.invoke(Material.class, materialID); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } else { + int counter = 1; + for (Material material : Material.values()) { + if (counter == materialID) { + return material; + } + counter++; + } + } + throw new MaterialMatchException("Couldn't parse material: " + materialID); + } + + public static Material catchMaterial(String material) throws MaterialMatchException { + try { + Method m = Material.class.getDeclaredMethod("getMaterial", String.class); + m.setAccessible(true); + Material mat = (Material) m.invoke(Material.class, material); + if (mat == null) { + throw new MaterialMatchException("Couldn't parse material: \"" + material + "\""); + } + return mat; + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + public static Material getMaterial(String material) { + try { + Method m = Material.class.getDeclaredMethod("getMaterial", String.class); + m.setAccessible(true); + return (Material) m.invoke(Material.class, material); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + +} diff --git a/virtualrealty.iml b/virtualrealty.iml new file mode 100644 index 0000000..84ca1fd --- /dev/null +++ b/virtualrealty.iml @@ -0,0 +1,43 @@ + + + + + + + SPIGOT + BUKKIT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From ade1be4e9331329aafb94c6d4c2101d6b8384c8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 27 Jan 2022 15:19:29 +0100 Subject: [PATCH 03/23] Renamed classpath --- .../plytki/virtualrealty/VirtualRealty.java | 560 ------------ .../virtualrealty/commands/PlotCommand.java | 370 -------- .../commands/VirtualRealtyCommand.java | 735 ---------------- .../configs/MessagesConfiguration.java | 69 -- .../configs/PluginConfiguration.java | 172 ---- .../configs/SizesConfiguration.java | 89 -- .../plytki/virtualrealty/enums/Direction.java | 45 - .../me/plytki/virtualrealty/enums/Flag.java | 33 - .../virtualrealty/enums/HighlightType.java | 9 - .../virtualrealty/enums/Permission.java | 24 - .../plytki/virtualrealty/enums/PlotSize.java | 86 -- .../exceptions/MaterialMatchException.java | 9 - .../listeners/ProtectionListener.java | 448 ---------- .../listeners/VirtualListener.java | 22 - .../listeners/plot/BorderListener.java | 44 - .../listeners/plot/PlotListener.java | 100 --- .../listeners/world/WorldListener.java | 49 -- .../virtualrealty/managers/PlotManager.java | 186 ---- .../plytki/virtualrealty/objects/Cuboid.java | 187 ---- .../me/plytki/virtualrealty/objects/Plot.java | 796 ------------------ .../objects/math/BlockVector2.java | 44 - .../objects/math/BlockVector3.java | 59 -- .../registry/VirtualPlaceholders.java | 123 --- .../java/me/plytki/virtualrealty/sql/SQL.java | 125 --- .../utils/ConfigurationFactory.java | 46 - .../virtualrealty/utils/Permissions.java | 27 - .../plytki/virtualrealty/utils/PlotUtil.java | 41 - .../virtualrealty/utils/ProtectionUtil.java | 40 - .../virtualrealty/utils/Reflections.java | 271 ------ .../plytki/virtualrealty/utils/SafeUtil.java | 27 - .../virtualrealty/utils/SchematicUtil.java | 154 ---- .../plytki/virtualrealty/utils/UUIDUtils.java | 16 - .../virtualrealty/utils/UpdateChecker.java | 39 - .../plytki/virtualrealty/utils/data/Data.java | 31 - .../utils/multiversion/Chat.java | 44 - .../utils/multiversion/VMaterial.java | 60 -- 36 files changed, 5180 deletions(-) delete mode 100644 src/main/java/me/plytki/virtualrealty/VirtualRealty.java delete mode 100644 src/main/java/me/plytki/virtualrealty/commands/PlotCommand.java delete mode 100644 src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java delete mode 100644 src/main/java/me/plytki/virtualrealty/configs/MessagesConfiguration.java delete mode 100644 src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java delete mode 100644 src/main/java/me/plytki/virtualrealty/configs/SizesConfiguration.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/Direction.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/Flag.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/HighlightType.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/Permission.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/PlotSize.java delete mode 100644 src/main/java/me/plytki/virtualrealty/exceptions/MaterialMatchException.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/ProtectionListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/VirtualListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/plot/BorderListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/plot/PlotListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/world/WorldListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/managers/PlotManager.java delete mode 100644 src/main/java/me/plytki/virtualrealty/objects/Cuboid.java delete mode 100644 src/main/java/me/plytki/virtualrealty/objects/Plot.java delete mode 100644 src/main/java/me/plytki/virtualrealty/objects/math/BlockVector2.java delete mode 100644 src/main/java/me/plytki/virtualrealty/objects/math/BlockVector3.java delete mode 100644 src/main/java/me/plytki/virtualrealty/registry/VirtualPlaceholders.java delete mode 100644 src/main/java/me/plytki/virtualrealty/sql/SQL.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/ConfigurationFactory.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/Permissions.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/PlotUtil.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/ProtectionUtil.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/Reflections.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/SafeUtil.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/UUIDUtils.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/UpdateChecker.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/data/Data.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/multiversion/VMaterial.java diff --git a/src/main/java/me/plytki/virtualrealty/VirtualRealty.java b/src/main/java/me/plytki/virtualrealty/VirtualRealty.java deleted file mode 100644 index 3376005..0000000 --- a/src/main/java/me/plytki/virtualrealty/VirtualRealty.java +++ /dev/null @@ -1,560 +0,0 @@ -package me.plytki.virtualrealty; - -import me.plytki.virtualrealty.commands.PlotCommand; -import me.plytki.virtualrealty.commands.VirtualRealtyCommand; -import me.plytki.virtualrealty.configs.MessagesConfiguration; -import me.plytki.virtualrealty.configs.PluginConfiguration; -import me.plytki.virtualrealty.configs.SizesConfiguration; -import me.plytki.virtualrealty.enums.Flag; -import me.plytki.virtualrealty.enums.PlotSize; -import me.plytki.virtualrealty.exceptions.MaterialMatchException; -import me.plytki.virtualrealty.listeners.plot.BorderListener; -import me.plytki.virtualrealty.listeners.plot.PlotListener; -import me.plytki.virtualrealty.listeners.ProtectionListener; -import me.plytki.virtualrealty.listeners.world.WorldListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.registry.VirtualPlaceholders; -import me.plytki.virtualrealty.sql.SQL; -import me.plytki.virtualrealty.utils.ConfigurationFactory; -import me.plytki.virtualrealty.utils.SchematicUtil; -import me.plytki.virtualrealty.utils.UpdateChecker; -import me.plytki.virtualrealty.utils.multiversion.VMaterial; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.LineIterator; -import org.bstats.bukkit.Metrics; -import org.bstats.charts.AdvancedPie; -import org.bstats.charts.SimplePie; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.permissions.Permission; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; -import org.dynmap.DynmapAPI; -import org.dynmap.markers.MarkerIcon; -import org.dynmap.markers.MarkerSet; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.Statement; -import java.util.*; -import java.util.concurrent.Callable; - -public final class VirtualRealty extends JavaPlugin { - - public final Locale locale = Locale.getDefault(); - public final List availableLocales = new ArrayList<>(Arrays.asList(new Locale("en", "GB"), new Locale("es", "ES"), new Locale("pl", "PL"))); - - //CORE - private static VirtualRealty instance; - public static final String PREFIX = "§a§lVR §8§l» §7"; - public static ArrayList tasks = new ArrayList<>(); - private static final ArrayList preVersions = new ArrayList<>(); - public static boolean isLegacy = false; - public static final Permission GLOBAL_PERMISSION = new Permission("virtualrealty"); - - //FILES - public static File plotsFolder; - public static File plotsSchemaFolder; - public PluginConfiguration pluginConfiguration; - public SizesConfiguration sizesConfiguration; - public MessagesConfiguration messagesConfiguration; - private final File pluginConfigurationFile = new File(this.getDataFolder(), "config.yml"); - private final File sizesConfigurationFile = new File(this.getDataFolder(), "sizes.yml"); - private final File languagesDirectory = new File(this.getDataFolder(), "messages"); - - //DYNMAP API - public static boolean isDynmapPresent = false; - public static DynmapAPI dapi = null; - public static MarkerSet markerset = null; - public static MarkerIcon markerIcon = null; - - @Override - public void onEnable() { - instance = this; - if (checkLegacyVersions()) { - isLegacy = true; - } - String[] updateCheck = UpdateChecker.getUpdate(); - if (updateCheck != null) { - if (!updateCheck[0].equals(this.getDescription().getVersion())) { - this.getLogger().info("A newer version is available!"); - this.getLogger().info("The current version you use: " + this.getDescription().getVersion()); - this.getLogger().info("Latest version available: " + updateCheck[0]); - this.getLogger().info("Download link: https://www.spigotmc.org/resources/virtual-realty.95599/"); - } else { - this.getLogger().info("Plugin is up to date!"); - } - } - try { - checkConfig(); - checkSizesConfig(); - } catch (IOException e) { - e.printStackTrace(); - } - plotsFolder = new File(getInstance().getDataFolder().getAbsolutePath(), "plots"); - plotsFolder.mkdirs(); - plotsSchemaFolder = new File(plotsFolder.getAbsolutePath(), "primary-terrain"); - plotsSchemaFolder.mkdirs(); - spawnLocales(); - reformatConfig(); - reloadConfigs(); - registerMetrics(); - loadSizesConfiguration(); - connectToDatabase(); - PlotManager.loadPlots(); - if (pluginConfiguration.dynmapMarkers) { - registerDynmap(); - } - reloadFlags(); - registerCommands(); - registerListeners(); - registerTasks(); - checkForOldSchemas(); - convertOldDatabase(); - if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")){ - new VirtualPlaceholders(this).register(); - debug("Registered new placeholders"); - } - debug("Server version: " + this.getServer().getBukkitVersion() + " | " + this.getServer().getVersion()); - } - - @Override - public void onDisable() { - PlotManager.plots.forEach(Plot::update); - tasks.forEach(BukkitTask::cancel); - SQL.closeConnection(); - if (pluginConfiguration.dataModel == PluginConfiguration.DataModel.H2) { - pluginConfiguration.dataModel = PluginConfiguration.DataModel.SQLITE; - } - pluginConfiguration.save(); - } - - public static void debug(String debugMessage) { - if (VirtualRealty.getPluginConfiguration().debugMode) - VirtualRealty.getInstance().getLogger().warning("DEBUG-MODE > " + debugMessage); - } - - public void spawnLocales() { - for (Locale availableLocale : availableLocales) { - if (availableLocale.toString().equalsIgnoreCase("en_GB")) { - File messagesConfigurationFile = new File(languagesDirectory, "messages_en_GB.yml"); - ConfigurationFactory configFactory = new ConfigurationFactory(); - configFactory.createMessagesConfiguration(messagesConfigurationFile); - } else { - File languageConfigurationFile = new File(languagesDirectory, "messages_" + availableLocale + ".yml"); - if (!languageConfigurationFile.exists()) { - saveResource("messages_" + availableLocale + ".yml", true); - File file = new File(this.getDataFolder(), "messages_" + availableLocale + ".yml"); - try { - FileUtils.moveFile(file, languageConfigurationFile); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - } - - public void convertOldDatabase() { - File oldDatabase = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.mv.db"); - if (oldDatabase.exists()) { - try { - SQL.closeConnection(); - Connection connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.db"); - SQL.setConnection(connection); - Statement statement = connection.createStatement(); - SQL.setStatement(statement); - statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); - for (Plot plot : PlotManager.plots) { - plot.insert(); - } - FileUtils.deleteQuietly(oldDatabase); - debug("H2 database converted successfully to SQLITE"); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void reloadConfigs() { - try { - ConfigurationFactory configFactory = new ConfigurationFactory(); - pluginConfiguration = configFactory.createPluginConfiguration(pluginConfigurationFile); - File messagesConfigurationFile = new File(languagesDirectory, "messages_" + pluginConfiguration.locale + ".yml"); - sizesConfiguration = configFactory.createSizesConfiguration(sizesConfigurationFile); - messagesConfiguration = configFactory.createMessagesConfiguration(messagesConfigurationFile); - } catch (Exception exception) { - exception.printStackTrace(); - } - } - - public void reloadFlags() { - if (pluginConfiguration.allowOutPlotBuild) { - for (Flag.World value : Flag.World.values()) { - value.setAllowed(true); - } - } else { - for (Flag.World value : Flag.World.values()) { - value.setAllowed(false); - } - } - } - - public static void checkForOldSchemas() { - for (Plot plot : PlotManager.plots) { - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plot.getID() + ".schem"); - if (f.exists()) { - List data = SchematicUtil.oldLoad(plot.getID()); - FileUtils.deleteQuietly(f); - SchematicUtil.save(plot.getID(), data.toArray(new String[0])); - debug("Converted Plot #" + plot.getID() + " | File: " + f.getName()); - } - } - } - - public void registerDynmap() { - new BukkitRunnable() { - @Override - public void run() { - Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); - if (plugin != null) { - isDynmapPresent = true; - } - if (plugin != null && plugin.isEnabled()) { - dapi = (DynmapAPI) plugin; - if (dapi.markerAPIInitialized()) { - markerset = dapi.getMarkerAPI().getMarkerSet("virtualrealty.plots"); - if (markerset == null) - markerset = dapi.getMarkerAPI().createMarkerSet("virutalrealty.plots", "Plots", dapi.getMarkerAPI().getMarkerIcons(), false); - for (MarkerSet markerSet : dapi.getMarkerAPI().getMarkerSets()) { - if (markerSet.getMarkerSetLabel().equalsIgnoreCase("Plots")) { - markerset = markerSet; - } - } - try { - if (dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon") == null) { - InputStream in = this.getClass().getResourceAsStream("/ploticon.png"); - if (in.available() > 0) { - markerIcon = dapi.getMarkerAPI().createMarkerIcon("virtualrealty_main_icon", "Plots", in); - } - } - else { - markerIcon = dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon"); - } - } - catch (IOException ex) {} - VirtualRealty.debug("Registering plots markers.."); - for (Plot plot : PlotManager.plots) { - PlotManager.resetPlotMarker(plot); - } - VirtualRealty.debug("Registered plots markers"); - this.cancel(); - } - } - } - }.runTaskTimer(this, 20, 20*5); - } - - - private void registerCommands() { - this.getCommand("plot").setExecutor(new PlotCommand()); - this.getCommand("virtualrealty").setExecutor(new VirtualRealtyCommand()); - } - - private void registerListeners() { - new BorderListener(this).registerEvents(); - new PlotListener(this).registerEvents(); - new ProtectionListener(this).registerEvents(); - new WorldListener(this).registerEvents(); - debug("Registered listeners"); - } - - private void registerTasks() { - //debug("Registered tasks"); - } - - private void registerMetrics() { - Metrics metrics = new Metrics(this, 12578); - metrics.addCustomChart(new SimplePie("used_database", () -> pluginConfiguration.dataModel.name())); - metrics.addCustomChart(new AdvancedPie("created_plots", new Callable>() { - @Override - public Map call() throws Exception { - Map valueMap = new HashMap(); - int smallPlots = 0; - int mediumPlots = 0; - int largePlots = 0; - int customPlots = 0; - for (Plot plot : PlotManager.plots) { - switch (plot.getPlotSize()) { - case SMALL: { - smallPlots++; - break; - } - case MEDIUM: { - mediumPlots++; - break; - } - case LARGE: { - largePlots++; - break; - } - case CUSTOM: { - customPlots++; - break; - } - default: - throw new IllegalStateException("Unexpected value: " + plot.getPlotSize()); - } - } - valueMap.put("SMALL", smallPlots); - valueMap.put("MEDIUM", mediumPlots); - valueMap.put("LARGE", largePlots); - valueMap.put("CUSTOM", customPlots); - return valueMap; - } - })); - debug("Registered metrics"); - } - - private void connectToDatabase() { - SQL.connect(); - SQL.createTables(); - debug("Connected to database"); - } - - public void loadSizesConfiguration() { - for (PlotSize plotSize : PlotSize.values()) { - if (plotSize == PlotSize.CUSTOM) return; - SizesConfiguration.PlotSizes.Size classSize = null; - switch (plotSize) { - case SMALL: { - classSize = sizesConfiguration.plotSizes.SMALL; - break; - } - case MEDIUM: { - classSize = sizesConfiguration.plotSizes.MEDIUM; - break; - } - case LARGE: { - classSize = sizesConfiguration.plotSizes.LARGE; - break; - } - } - Material floorMaterial; - try { - floorMaterial = VMaterial.catchMaterial(classSize.floorMaterial.toUpperCase()); - } catch (MaterialMatchException e) { - floorMaterial = VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK; - e.printStackTrace(); - //throw new MaterialMatchException("Couldn't parse floor-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK)); - } - Material borderMaterial; - try { - borderMaterial = VMaterial.catchMaterial(classSize.borderMaterial.toUpperCase()); - } catch (MaterialMatchException e) { - borderMaterial = VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB; - e.printStackTrace(); - //throw new MaterialMatchException("Couldn't parse border-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB)); - } - plotSize.setFloorMaterial(floorMaterial); - plotSize.setFloorData(classSize.floorData); - plotSize.setBorderMaterial(borderMaterial); - plotSize.setBorderData(classSize.borderData); - plotSize.setLength(classSize.length); - plotSize.setWidth(classSize.width); - plotSize.setHeight(classSize.height); - } - debug("Loaded sizes config"); - } - - public static VirtualRealty getInstance() { - return instance; - } - - public static PluginConfiguration getPluginConfiguration() { - return VirtualRealty.getInstance().pluginConfiguration; - } - - public static File getPluginConfigurationFile() { - return VirtualRealty.getInstance().pluginConfigurationFile; - } - - public static SizesConfiguration getSizesConfiguration() { - return VirtualRealty.getInstance().sizesConfiguration; - } - - public static File getSizesConfigurationFile() { - return VirtualRealty.getInstance().sizesConfigurationFile; - } - - public static MessagesConfiguration getMessages() { - return getInstance().messagesConfiguration; - } - - public boolean checkLegacyVersions() { - setPostVersions(); - for (String preVersion : preVersions) { - if (Bukkit.getBukkitVersion().toLowerCase().contains(preVersion.toLowerCase())) { - return true; - } - } - return false; - } - - public static Locale getLocale() { - return getInstance().locale; - } - - public void setPostVersions() { - preVersions.add("1.12"); - preVersions.add("1.11"); - preVersions.add("1.10"); - preVersions.add("1.9"); - preVersions.add("1.8"); - } - - public void reformatConfig() { - File configFile = new File(this.getDataFolder(), "config.yml"); - File newFile = new File(this.getDataFolder(), "config.yml.new"); - if (configFile.exists()) { - try { - List lines = FileUtils.readLines(configFile, StandardCharsets.UTF_8); - for (int i = 0; i < lines.size(); i++) { - if (lines.get(i).startsWith("force-plot-gamemode:")) { - lines.set(i, lines.get(i).replaceAll("force-plot-gamemode:", "lock-plot-gamemode:")); - } - } - FileUtils.writeLines(newFile, lines); - FileUtils.deleteQuietly(configFile); - newFile.createNewFile(); - File newConfigFile = new File(this.getDataFolder(), "config.yml"); - FileUtils.copyFile(newFile, newConfigFile); - FileUtils.deleteQuietly(newFile); - } catch (IOException e) { - - } - } - } - - public void checkConfig() throws IOException { - File oldConfigFile = new File(this.getDataFolder(), "config.yml"); - if (!oldConfigFile.exists()) return; - String version = null; - boolean isOldVersion = true; - boolean updateConfigVersion = false; - FileReader fileReader = new FileReader(this.pluginConfigurationFile); - BufferedReader reader = new BufferedReader(fileReader); - String latestLine; - while((latestLine = reader.readLine()) != null) { - if (latestLine.contains("config-version")) { - version = latestLine.replaceAll("config-version: ", ""); - isOldVersion = false; - } - } - fileReader.close(); - reader.close(); - if (version == null) { - System.err.println(" "); - this.getLogger().warning("Config has been reset due to major config changes!"); - this.getLogger().warning("Old config has been renamed to config.yml.old"); - this.getLogger().warning("Please update your config file!"); - System.err.println(" "); - } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { - updateConfigVersion = true; - this.getLogger().info("Config has been updated!"); - } - - // save old config file - if (isOldVersion) { - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml.old"); - if (newConfigFile.exists()) { - newConfigFile.delete(); - } - FileUtils.copyFile(oldConfigFile, newConfigFile); - oldConfigFile.delete(); - } - -// update config version - if (updateConfigVersion) { - List lines = new ArrayList<>(); - LineIterator iterator = FileUtils.lineIterator(oldConfigFile); - while (iterator.hasNext()) { - String line = iterator.next(); - lines.add(line); - } - for (String line : new ArrayList<>(lines)) { - if (line.contains("config-version")) { - int index = lines.indexOf(line); - lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); - } - } - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml"); - FileUtils.deleteQuietly(newConfigFile); - FileUtils.writeLines(newConfigFile, lines); - newConfigFile.createNewFile(); - } - } - - public void checkSizesConfig() throws IOException { - File oldConfigFile = new File(this.getDataFolder(), "sizes.yml"); - if (!oldConfigFile.exists()) return; - String version = null; - boolean isOldVersion = true; - boolean updateConfigVersion = false; - BufferedReader reader = new BufferedReader(new FileReader(this.sizesConfigurationFile)); - String latestLine; - while((latestLine = reader.readLine()) != null) { - if (latestLine.contains("config-version")) { - version = latestLine.replaceAll("config-version: ", ""); - isOldVersion = false; - } - } - reader.close(); - if (version == null) { - System.err.println(" "); - this.getLogger().warning("Config has been reset due to major config changes!"); - this.getLogger().warning("Old config has been renamed to sizes.yml.old"); - this.getLogger().warning("Please update your config file!"); - System.err.println(" "); - } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { - updateConfigVersion = true; - this.getLogger().info("Plot sizes config has been updated!"); - } - - // save old config file - if (isOldVersion) { - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml.old"); - if (newConfigFile.exists()) { - newConfigFile.delete(); - } - FileUtils.copyFile(oldConfigFile, newConfigFile); - oldConfigFile.delete(); - } - - // update config version - if (updateConfigVersion) { - List lines = new ArrayList<>(); - LineIterator iterator = FileUtils.lineIterator(oldConfigFile); - while (iterator.hasNext()) { - String line = iterator.next(); - lines.add(line); - } - for (String line : new ArrayList<>(lines)) { - if (line.contains("config-version")) { - int index = lines.indexOf(line); - lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); - } - } - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml"); - FileUtils.deleteQuietly(newConfigFile); - FileUtils.writeLines(newConfigFile, lines); - newConfigFile.createNewFile(); - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/commands/PlotCommand.java b/src/main/java/me/plytki/virtualrealty/commands/PlotCommand.java deleted file mode 100644 index 71aca23..0000000 --- a/src/main/java/me/plytki/virtualrealty/commands/PlotCommand.java +++ /dev/null @@ -1,370 +0,0 @@ -package me.plytki.virtualrealty.commands; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.UUID; - -public class PlotCommand implements CommandExecutor { - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (!(sender instanceof Player)) { - return false; - } - Player p = ((Player) sender); - if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { - printHelp(sender); - return false; - } - if (args.length == 1) { - switch (args[0].toUpperCase()) { - case "ADD": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot add §8<§7player§8> §8<§7plot§8>"); - break; - } - case "KICK": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot kick §8<§7player§8> §8<§7plot§8>"); - break; - } - case "TP": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot tp §8<§7plotID§8>"); - break; - } - case "GM": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot gm §8<§7gamemode§8>"); - break; - } - case "INFO": { - Plot plot = PlotManager.getPlot(p.getLocation()); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); - return false; - } - printInfo(sender, plot); - break; - } - case "LIST": { - boolean hasPlot = false; - for (Plot plot : PlotManager.plots) { - if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()) && plot.getOwnedUntilDate().isAfter(LocalDateTime.now())) { - hasPlot = true; - break; - } - } - boolean isMember = false; - for (Plot plot : PlotManager.plots) { - if (plot.getMembers().contains(p.getUniqueId())) { - isMember = true; - break; - } - } - if (!hasPlot && !isMember) { - sender.sendMessage(VirtualRealty.PREFIX + "§cYou don't have any plots!"); - return false; - } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" "); - if (hasPlot) { - sender.sendMessage("§7§m "); - sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); - for (Plot plot : PlotManager.plots) { - if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - StringBuilder ownedBy = new StringBuilder(); - ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); - boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); - for (int i = ownedBy.length(); i < 16; i++) { - ownedBy.append(" "); - } - StringBuilder size = new StringBuilder(plot.getPlotSize().name()); - for (int i = size.length(); i < 6; i++) { - size.append(" "); - } - BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); - sender.sendMessage(textComponent.toLegacyText()); - } - } - sender.sendMessage("§7§m "); - } - if (isMember) { - sender.sendMessage(" "); - sender.sendMessage("§7 §fMember of §8§l↴"); - sender.sendMessage(" "); - sender.sendMessage("§7§m "); - sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); - for (Plot plot : PlotManager.plots) { - if (plot.getPlotOwner() != null && !plot.getPlotOwner().getUniqueId().equals(p.getUniqueId()) && plot.getMembers().contains(p.getUniqueId())) { - StringBuilder ownedBy = new StringBuilder(); - ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); - boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); - for (int i = ownedBy.length(); i < 16; i++) { - ownedBy.append(" "); - } - StringBuilder size = new StringBuilder(plot.getPlotSize().name()); - for (int i = size.length(); i < 6; i++) { - size.append(" "); - } - BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + ownedBy + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); - sender.sendMessage(textComponent.toLegacyText()); - } - } - sender.sendMessage("§7§m "); - } - break; - } - default: { - printHelp(sender); - } - } - } - if (args.length >= 2) { - switch (args[0].toUpperCase()) { - case "ADD": { - if (args.length == 3) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[2]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); - return false; - } - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - return false; - } - if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantAddYourself); - return false; - } - if (plot.getMembers().contains(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().alreadyInMembers); - return false; - } - plot.addMember(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerAdd.replaceAll("%player%", offlinePlayer.getName())); - return false; - } - break; - } - case "KICK": { - if (args.length == 3) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[2]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); - return false; - } - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - return false; - } - if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantKickYourself); - return false; - } - if (!plot.getMembers().contains(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notInMembers); - return false; - } - plot.removeMember(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerKick.replaceAll("%player%", offlinePlayer.getName())); - return false; - } - break; - } - case "TP": { - if (args.length == 2) { - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (!plot.hasPlotMembership(p)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); - return false; - } - if (plot.isOwnershipExpired()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - return false; - } - Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); - loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); - p.teleport(loc); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); - } - break; - } - case "GM": { - if (VirtualRealty.getPluginConfiguration().lockPlotGameMode) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeFeatureDisabled); - return false; - } - GameMode gameMode; - int gameModeID; - try { - gameMode = GameMode.valueOf(args[1]); - gameModeID = gameMode.getValue(); - } catch (IllegalArgumentException e) { - try { - gameModeID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException ex) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().incorrectGamemode); - return false; - } - } - GameMode defaultGamemode = VirtualRealty.getInstance().getServer().getDefaultGameMode(); - GameMode configGamemode = VirtualRealty.getPluginConfiguration().getGameMode(); - if (!(gameModeID != configGamemode.getValue() && gameModeID != defaultGamemode.getValue())) { - gameMode = GameMode.getByValue(Integer.parseInt(args[1])); - } else { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeDisabled); - return false; - } - Plot plot = PlotManager.getBorderedPlot(p.getLocation()); - if (plot != null) { - if (!plot.hasPlotMembership(p)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); - } else { - if (plot.isOwnershipExpired()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } else { - if (p.getGameMode().equals(gameMode)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeAlreadySelected); - return false; - } - if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { - plot.setSelectedGameMode(gameMode); - } - p.setGameMode(gameMode); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeSwitched); - } - } - } else { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); - } - break; - } - default: { - printHelp(sender); - } - } - } - return false; - } - - private static void printHelp(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot add §8- §7Adds a member"); - sender.sendMessage(" §a/plot kick §8- §7Kicks a member"); - sender.sendMessage(" §a/plot list §8- §7Shows your plots"); - sender.sendMessage(" §a/plot info §8- §7Shows plot info"); - sender.sendMessage(" §a/plot gm §8- §7Changes gamemode"); - sender.sendMessage(" §a/plot tp §8- §7Teleports to the plot"); - } - - private static void printInfo(CommandSender sender, Plot plot) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); -// String assignedBy = VirtualRealty.getMessages().notAssigned; -// if (plot.getAssignedBy() != null) { -// switch (plot.getAssignedBy().toUpperCase()) { -// case "CONSOLE": { -// assignedBy = VirtualRealty.getMessages().assignedByConsole; -// break; -// } -// case "SHOP_PURCHASE": { -// assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; -// break; -// } -// default: { -// OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); -// assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); -// } -// } -// } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); - sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); - if (plot.getMembers().size() != 0) { - sender.sendMessage(" §7Members §8§l↴"); - for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { - sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); - } - } - //sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); - sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); - sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); - sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); - sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); - sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); - //sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); - //sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); - //sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); - //sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); - //sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java b/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java deleted file mode 100644 index b790ba2..0000000 --- a/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java +++ /dev/null @@ -1,735 +0,0 @@ -package me.plytki.virtualrealty.commands; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Direction; -import me.plytki.virtualrealty.enums.PlotSize; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.utils.ConfigurationFactory; -import me.plytki.virtualrealty.utils.Permissions; -import me.plytki.virtualrealty.utils.PlotUtil; -import me.plytki.virtualrealty.utils.UUIDUtils; -import me.plytki.virtualrealty.utils.multiversion.Chat; -import me.plytki.virtualrealty.utils.multiversion.VMaterial; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.*; -import org.bukkit.entity.Player; -import org.bukkit.permissions.Permission; -import org.jetbrains.annotations.NotNull; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.UUID; - -public class VirtualRealtyCommand implements CommandExecutor { - - private static final Permission commandPermission = new Permission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".vrplot"); - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - Permission tempPermission = new Permission(commandPermission.getName()); - if (!Permissions.hasPermission(sender, tempPermission.getName())) return false; - Player p = null; - Location location = null; - if(sender instanceof Player) { - p = (Player)sender; - location = p.getLocation(); - location.add(0, -1, 0); - } - if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { - printHelp(sender); - return false; - } - if (args.length == 1) { - switch (args[0].toUpperCase()) { - case "CREATE": { - if (!Permissions.hasPermission(sender, tempPermission, "create")) return false; - if (sender instanceof Player) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot create §8<§7small/medium/large§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); - sender.sendMessage(" §a/vrplot create §8<§7length§8> §8<§7width§8> §8<§7height§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); - } - break; - } - case "REMOVE": { - if (!Permissions.hasPermission(sender, tempPermission, "remove")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot remove §8<§7plotID§8>"); - break; - } - case "SET": { - if (!Permissions.hasPermission(sender, tempPermission, "set")) return false; - printSetHelp(sender); - break; - } - case "ASSIGN": { - if (!Permissions.hasPermission(sender, tempPermission, "assign")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot assign §8<§7plotID§8> §8<§7username§8>"); - break; - } - case "UNASSIGN": { - if (!Permissions.hasPermission(sender, tempPermission, "unassign")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot unassign §8<§7plotID§8>"); - break; - } - case "INFO": { - if (!Permissions.hasPermission(sender, tempPermission, "info")) return false; - Plot plot = PlotManager.getPlot(p.getLocation()); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); - return false; - } - printInfo(sender, plot); - break; - } - case "LIST": { - if (!Permissions.hasPermission(sender, tempPermission, "list")) return false; - if (PlotManager.plots.isEmpty()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); - return false; - } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" "); - sender.sendMessage("§7§m "); - sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); - for (Plot plot : PlotManager.plots) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - StringBuilder ownedBy = new StringBuilder(); - ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); - boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); - for (int i = ownedBy.length(); i < 16; i++) { - ownedBy.append(" "); - } - StringBuilder size = new StringBuilder(plot.getPlotSize().name()); - for (int i = size.length(); i < 6; i++) { - size.append(" "); - } - BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + ownedBy.substring(0, 14) + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); - textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); - textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - new Chat(textComponent).sendTo(sender); - } - sender.sendMessage("§7§m "); - break; - } - case "TP": { - if (!Permissions.hasPermission(sender, tempPermission, "tp")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot tp §8<§7plotID§8>"); - break; - } - case "RELOAD": { - if (!Permissions.hasPermission(sender, tempPermission, "reload")) return false; - try { - VirtualRealty.getInstance().reloadConfigs(); - if (VirtualRealty.getPluginConfiguration().dynmapMarkers) { - if (VirtualRealty.markerset != null) { - VirtualRealty.markerset.deleteMarkerSet(); - } - VirtualRealty.getInstance().registerDynmap(); - for (Plot plot : PlotManager.plots) { - PlotManager.resetPlotMarker(plot); - } - } else { - if (VirtualRealty.markerset != null) { - VirtualRealty.markerset.deleteMarkerSet(); - } - } - PlotManager.loadPlots(); - VirtualRealty.getInstance().reloadFlags(); - VirtualRealty.getInstance().loadSizesConfiguration(); - } catch (Exception exception) { - exception.printStackTrace(); - } - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().reloadCompleted); - break; - } - default: { - printHelp(sender); - break; - } - } - } - if (args.length > 1) { - switch (args[0].toUpperCase()) { - case "CREATE": { - if (!Permissions.hasPermission(sender, commandPermission, "create")) return false; - if (sender instanceof Player) { - if (Arrays.stream(PlotSize.values()).anyMatch(plotSize -> plotSize.name().equalsIgnoreCase(args[1])) && !args[1].equalsIgnoreCase(PlotSize.CUSTOM.name())) { - PlotSize plotSize = null; - try { - plotSize = PlotSize.valueOf(args[1].toUpperCase()); - } catch (IllegalArgumentException ignored) { - } - if (plotSize != null) { - if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), plotSize.getLength(), plotSize.getWidth(), plotSize.getHeight()))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); - return false; - } else { - Material floorMaterial = null; - byte floorData = 0; - if (args.length >= 3) { - try { - floorMaterial = VMaterial.getMaterial(args[2].split(":")[0].toUpperCase()); - if (floorMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - if (args[2].split(":").length == 2) { - floorData = Byte.parseByte(args[2].split(":")[1]); - } - } - Material borderMaterial = null; - byte borderData = 0; - if (args.length >= 4) { - try { - borderMaterial = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); - if (borderMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - if (args[3].split(":").length == 2) { - borderData = Byte.parseByte(args[3].split(":")[1]); - } - } - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); - long timeStart = System.currentTimeMillis(); - Plot plot = PlotManager.createPlot(location, plotSize); - if (floorMaterial != null) { - plot.setFloorMaterial(floorMaterial, floorData); - } - if (borderMaterial != null) { - plot.setBorder(borderMaterial, borderData); - } - long timeEnd = System.currentTimeMillis(); - BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); - BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); - BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); - textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); - textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - textComponent.addExtra(textComponent2); - textComponent.addExtra(textComponent3); - new Chat(textComponent).sendTo(p); - } - } else { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().sizeNotRecognised); - return false; - } - } else { - int length; - int width; - int height; - try { - length = Integer.parseInt(args[1]); - width = Integer.parseInt(args[2]); - height = Integer.parseInt(args[3]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - if (length > 500 || width > 500 || height > 500) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().LWHHardLimit); - return false; - } - if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), length, width, height))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); - return false; - } else { - Material floorMaterial = null; - byte floorData = 0; - if (args.length >= 5) { - try { - floorMaterial = VMaterial.getMaterial(args[4].split(":")[0].toUpperCase()); - if (floorMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - if (args[4].split(":").length == 2) { - floorData = Byte.parseByte(args[4].split(":")[1]); - } - } - Material borderMaterial = null; - byte borderData = 0; - if (args.length >= 6) { - try { - borderMaterial = VMaterial.getMaterial(args[5].split(":")[0].toUpperCase()); - if (borderMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - if (args[5].split(":").length == 2) { - borderData = Byte.parseByte(args[5].split(":")[1]); - } - } - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); - long timeStart = System.currentTimeMillis(); - Plot plot = PlotManager.createPlot(location, length, width, height); - if (floorMaterial != null) { - plot.setFloorMaterial(floorMaterial, floorData); - } - if (borderMaterial != null) { - plot.setBorder(borderMaterial, borderData); - } - long timeEnd = System.currentTimeMillis(); - BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); - BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); - BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); - textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); - textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - textComponent.addExtra(textComponent2); - textComponent.addExtra(textComponent3); - new Chat(textComponent).sendTo(p); - } - } - } - break; - } - case "REMOVE": { - if (!Permissions.hasPermission(sender, commandPermission, "remove")) return false; - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - plot.remove(); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().removedPlot); - break; - } - case "SET": { - if (!Permissions.hasPermission(sender, commandPermission, "set")) return false; - if (args.length >= 3) { - switch (args[2].toUpperCase()) { - case "OWNEDBY": { - if (!Permissions.hasPermission(sender, commandPermission, "set.ownedby")) return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyUsername); - return false; - } - int plotID; - OfflinePlayer offlinePlayer; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - try { - if (UUIDUtils.isValidUUID(args[3])) { - offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[3])); - } else { - offlinePlayer = Bukkit.getOfflinePlayer(args[3]); - } - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - } catch (NullPointerException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (args.length >= 5) { - String dateFormat = args[4]; - String timeFormat; - int year; - int month; - int dayOfMonth; - int hour = 0; - int minute = 0; - LocalDateTime localDateTime; - try { - year = Integer.parseInt(dateFormat.split("/")[2]); - month = Integer.parseInt(dateFormat.split("/")[1]); - dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); - if (args.length >= 6) { - timeFormat = args[5]; - hour = Integer.parseInt(timeFormat.split(":")[0]); - minute = Integer.parseInt(timeFormat.split(":")[1]); - } - localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); - return false; - } - plot.setOwnedUntilDate(localDateTime); - } - if (sender instanceof RemoteConsoleCommandSender && args.length >= 7 && args[6].equalsIgnoreCase("assign")) { - plot.setAssignedBy("SHOP_PURCHASE"); - } - plot.setOwnedBy(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedTo.replaceAll("%assigned_to%", offlinePlayer.getName())); - plot.update(); - break; - } - case "FLOORMATERIAL": { - if (!Permissions.hasPermission(sender, commandPermission, "set.floormaterial")) return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Material material; - try { - material = Material.matchMaterial(args[3].split(":")[0].toUpperCase()); - if (material == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - byte data = 0; - if (args[3].split(":").length == 2) { - data = Byte.parseByte(args[3].split(":")[1]); - } - plot.setFloorMaterial(material, data); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newFloorMaterialSet); - plot.update(); - break; - } - case "BORDERMATERIAL": { - if (!Permissions.hasPermission(sender, commandPermission, "set.bordermaterial")) - return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Material material; - try { - material = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); - if (material == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - byte data = 0; - if (args[3].split(":").length == 2) { - data = Byte.parseByte(args[3].split(":")[1]); - } - plot.setBorder(material, data); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newBorderMaterialSet); - plot.update(); - return false; - } - case "OWNERSHIPEXPIRES": { - if (!Permissions.hasPermission(sender, commandPermission, "set.ownerexpires")) return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyExpiryDate); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - String dateFormat = args[3]; - String timeFormat; - int year; - int month; - int dayOfMonth; - int hour = 0; - int minute = 0; - LocalDateTime localDateTime; - try { - year = Integer.parseInt(dateFormat.split("/")[2]); - month = Integer.parseInt(dateFormat.split("/")[1]); - dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); - if (args.length == 5) { - timeFormat = args[4]; - hour = Integer.parseInt(timeFormat.split(":")[0]); - minute = Integer.parseInt(timeFormat.split(":")[1]); - } - localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - plot.setOwnedUntilDate(localDateTime); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownedUntilUpdated); - plot.update(); - break; - } - default: { - printSetHelp(sender); - break; - } - } - } else { - printSetHelp(sender); - } - break; - } - case "ASSIGN": { - if (!Permissions.hasPermission(sender, commandPermission, "assign")) return false; - if (args.length == 3) { - int plotID; - OfflinePlayer offlinePlayer; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - try { - if (UUIDUtils.isValidUUID(args[2])) { - offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[2])); - } else { - offlinePlayer = Bukkit.getOfflinePlayer(args[2]); - } - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - } catch (NullPointerException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (sender instanceof Player) { - plot.setAssignedBy(p.getUniqueId().toString()); - } else if (sender instanceof ConsoleCommandSender){ - plot.setAssignedBy("CONSOLE"); - } else { - plot.setAssignedBy("SHOP_PURCHASE"); - } - plot.setOwnedBy(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedToBy.replaceAll("%assigned_to%", offlinePlayer.getName()).replaceAll("%assigned_by%", sender.getName())); - plot.update(); - } - break; - } - case "UNASSIGN": { - if (!Permissions.hasPermission(sender, commandPermission, "unassign")) return false; - if (args.length == 2) { - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - plot.setAssignedBy(null); - plot.setOwnedBy(null); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().unassigned); - plot.update(); - } - break; - } - case "INFO": { - if (!Permissions.hasPermission(sender, commandPermission, "info")) return false; - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - if (PlotManager.plots.isEmpty()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); - return false; - } - if (plotID < PlotManager.getPlotMinID()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().minPlotID.replaceAll("%min_id%", String.valueOf(PlotManager.getPlotMinID()))); - return false; - } - if (plotID > PlotManager.getPlotMaxID()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().maxPlotID.replaceAll("%max_id%", String.valueOf(PlotManager.getPlotMaxID()))); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - printInfo(sender, plot); - break; - } - case "TP": { - if (!Permissions.hasPermission(sender, commandPermission, "tp")) return false; - if (!(sender instanceof Player)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cmdOnlyPlayers); - return false; - } - if (args.length == 2) { - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); - loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); - p.teleport(loc); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); - } - break; - } - default: { - printHelp(sender); - break; - } - } - } - return false; - } - - private static void printInfo(CommandSender sender, Plot plot) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); - String assignedBy = VirtualRealty.getMessages().notAssigned; - if (plot.getAssignedBy() != null) { - switch (plot.getAssignedBy().toUpperCase()) { - case "CONSOLE": { - assignedBy = VirtualRealty.getMessages().assignedByConsole; - break; - } - case "SHOP_PURCHASE": { - assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; - break; - } - default: { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); - assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); - } - } - } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); - sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); - if (plot.getMembers().size() != 0) { - sender.sendMessage(" §7Members §8§l↴"); - for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { - sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); - } - } - sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); - sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); - sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); - sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); - sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); - sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); - sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); - sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); - sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); - sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); - sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); - } - - private static void printHelp(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot create §8- §7Creates a plot"); - sender.sendMessage(" §a/vrplot remove §8- §7Removes a plot"); - sender.sendMessage(" §a/vrplot set §8- §7Sets a variable for the plot"); - sender.sendMessage(" §a/vrplot assign §8- §7Assigns a plot to player"); - sender.sendMessage(" §a/vrplot unassign §8- §7Sets assigned to and assigned by to null"); - sender.sendMessage(" §a/vrplot info §8- §7Prints info about plot"); - sender.sendMessage(" §a/vrplot list §8- §7Prints all plots"); - sender.sendMessage(" §a/vrplot tp §8- §7Teleports to the plot"); - sender.sendMessage(" §a/vrplot reload §8- §7Reloads plugin"); - } - - private static void printSetHelp(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownedBy §8<§7username§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7floorMaterial §8<§7material§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7borderMaterial §8<§7material§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownershipExpires §8<§7dd/mm/YYYY§8> §8<§7HH:mm (optional)§8>"); - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/configs/MessagesConfiguration.java b/src/main/java/me/plytki/virtualrealty/configs/MessagesConfiguration.java deleted file mode 100644 index cdfa228..0000000 --- a/src/main/java/me/plytki/virtualrealty/configs/MessagesConfiguration.java +++ /dev/null @@ -1,69 +0,0 @@ -package me.plytki.virtualrealty.configs; - -import eu.okaeri.configs.OkaeriConfig; - -public class MessagesConfiguration extends OkaeriConfig { - - public String useNaturalNumbersOnly = "§cUse only natural numbers!"; - public String noPlotFound = "§cCouldn't get plot with specified ID!"; - public String notYourPlot = "§cIt's not your plot!"; - public String ownershipExpired = "§cYour ownership has expired!"; - public String teleportedToPlot = "§aYou have been teleported to the plot!"; - public String gamemodeFeatureDisabled = "§cGamemode feature is disabled!"; - public String incorrectGamemode = "§cIncorrect gamemode value!"; - public String gamemodeDisabled = "§cThis gamemode is disabled!"; - public String cantSwitchGamemode = "§cYou can't switch gamemode here!"; - public String notStandingOnPlot = "§cYou aren't standing on any plot!"; - public String assignedByConsole = "§eConsole"; - public String assignedByShopPurchase = "§eShop Purchase"; - public String noPlots = "§cThere are no plots!"; - public String available = "§cAvailable"; - public String reloadCompleted = "§aReload completed!"; - public String cantCreateOnExisting = "§cYou can't create new plot over an existing plot!"; - public String cantGetFloorMaterial = "§cCouldn't get floor material with specified name!"; - public String cantGetBorderMaterial = "§cCouldn't get border material with specified name!"; - public String cantGetMaterial = "§cCouldn't get material with specified name!"; - public String notCollidingCreating = "§aNot colliding. Creating plot.."; - public String clickToShowDetailedInfo = "§a§oClick to show detailed information about the plot! §8(§7ID: §f%plot_id%§8)"; - public String sizeNotRecognised = "§cSize not recognized!"; - public String LWHHardLimit = "§cL, W and H hard-limit is 500!"; - public String removedPlot = "§aSuccessfully removed plot!"; - public String specifyUsername = "§cSpecify username!"; - public String playerNotFoundWithUsername = "§cCouldn't find player with specified username!"; - public String invalidDateProvided = "§cInvalid date format provided!"; - public String assignedTo = "§aPlot has been assigned to §f%assigned_to%!"; - public String specifyMaterialName = "§cSpecify material name!"; - public String specifyExpiryDate = "§cSpecify expiry date!"; - public String newFloorMaterialSet = "§aNew floor material has been set!"; - public String newBorderMaterialSet = "§aNew border material has been set!"; - public String ownedUntilUpdated = "§aOwned until date has been updated!"; - public String assignedToBy = "§aPlot has been assigned to §f%assigned_to% §aby §f%assigned_by%!"; - public String notAssigned = "§cNot assigned"; - public String unassigned = "§aPlot has been unassigned!"; - public String minPlotID = "§cMinimum plot ID is %min_id%!"; - public String maxPlotID = "§cMaximum plot ID is %max_id%!"; - public String cmdOnlyPlayers = "§cCommand only for players!"; - - public String enteredAvailablePlot = "§2You have entered an available plot!"; - public String enteredOwnedPlot = "§7You have entered §2%owner%'s §7plot!"; - public String leftAvailablePlot = "§cYou have left an available plot!"; - public String leftOwnedPlot = "§7You have left §2%owner%'s §7plot!"; - public String cantInteract = "§cYou can't interact here!"; - public String cantBuildHere = "§cYou can't build here!"; - public String cantRideOnPlot = "§cYou can't ride on someones plot!"; - - public String creationPlotComponent1 = "§aPlot "; - public String creationPlotComponent2 = "§8#§7%plot_id%"; - public String creationPlotComponent3 = " §acreated! §8(§7%creation_time% ms§8)"; - - public String cantAddYourself = "§cYou can't add yourself to the plot!"; - public String cantKickYourself = "§cYou can't kick yourself from the plot!"; - public String alreadyInMembers = "§cThis player is already one of the plot members!"; - public String notInMembers = "§cThis player is not one of the plot members!"; - public String cantDoAnyDMG = "§cYou can't do any damage here!"; - public String playerKick = "§aPlayer §7%player% §ahas been kicked out of your plot!"; - public String playerAdd = "§aPlayer §7%player% §ahas been added to your plot!"; - public String gamemodeSwitched = "§aYour gamemode has changed!"; - public String gamemodeAlreadySelected = "§cThis gamemode is already selected!"; - -} diff --git a/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java b/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java deleted file mode 100644 index fcf9693..0000000 --- a/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java +++ /dev/null @@ -1,172 +0,0 @@ -package me.plytki.virtualrealty.configs; - -import eu.okaeri.configs.OkaeriConfig; -import eu.okaeri.configs.annotation.*; -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.HighlightType; -import org.bukkit.GameMode; - -@Header("################################################################") -@Header("# #") -@Header("# Virtual Realty #") -@Header("# #") -@Header("################################################################") -@Names(strategy = NameStrategy.IDENTITY, modifier = NameModifier.TO_LOWER_CASE) -public class PluginConfiguration extends OkaeriConfig { - - @Comment(" ") - @Comment("-------------------------") - @Comment("Don't change this value!") - @CustomKey("config-version") - public String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); - - @Comment("-------------------------") - @Comment("Debug mode (Dev only)") - @CustomKey("debug-mode") - public boolean debugMode = false; - - @Comment("Set player gamemode to change when they enter their plot") - @CustomKey("enable-plot-gamemode") - public boolean enablePlotGameMode = false; - - @Comment("Set your wanted language (locale)") - public String locale = VirtualRealty.getInstance().availableLocales.contains(VirtualRealty.getLocale()) ? VirtualRealty.getLocale().toString() : "en_GB"; - - @Comment("Set which gamemode players change to when they enter their plot") - @CustomKey("default-plot-gamemode") - public String plotGameMode = "SURVIVAL"; - - @Comment("Lock gamemode to plot default when player enters their plot (disables '/plot gm' command)") - @CustomKey("lock-plot-gamemode") - public boolean lockPlotGameMode = false; - - public GameMode getGameMode() { - try { - return GameMode.valueOf(plotGameMode); - } catch (Exception e) { - VirtualRealty.getInstance().getLogger().warning("Couldn't parse plot-gamemode from config.yml\nUsing default: SURVIVAL"); - return GameMode.SURVIVAL; - } - } - - @Comment("Allow players to build outside of their plots") - @CustomKey("allow-outplot-build") - public boolean allowOutPlotBuild = true; - - @Comment("Enables dynmap plots highlighting") - @CustomKey("enable-dynmap-markers") - public boolean dynmapMarkers = false; - - @Comment("Choose which type of plots should be highlighted on Dynmap page | Choose from: { ALL, AVAILABLE, OWNED }") - @CustomKey("dynmap-type") - public HighlightType dynmapType = HighlightType.ALL; - - @CustomKey("dynmap-markers") - public MarkerColor dynmapMarkersColor = new MarkerColor(new MarkerColor.Available("#80eb34", .3), new MarkerColor.Owned("#ffbf00", .45)); - - @Names(strategy = NameStrategy.IDENTITY) - public static class MarkerColor extends OkaeriConfig { - - public Available available; - - public Owned owned; - - public MarkerColor(Available available, Owned owned) { - this.available = available; - this.owned = owned; - } - - @Names(strategy = NameStrategy.IDENTITY) - public static class Available extends OkaeriConfig { - - public String color; - - public double opacity; - - public Available(String color, double opacity) { - this.color = color; - this.opacity = opacity; - } - - public int getHexColor() { - return Integer.decode("0x" + color.replaceAll("#", "")); - } - - } - - @Names(strategy = NameStrategy.IDENTITY) - public static class Owned extends OkaeriConfig { - - public String color; - - public double opacity; - - public Owned(String color, double opacity) { - this.color = color; - this.opacity = opacity; - } - - public int getHexColor() { - return Integer.decode("0x" + color.replaceAll("#", "")); - } - - } - - } - - @Comment("Enables plots enter/leave sounds") - @CustomKey("plot-sounds") - public boolean plotSound = true; - - @Comment("Type of data recording") - @Comment("SQLITE - Local database") - @Comment("MYSQL - External database") - @CustomKey("data-model") - public DataModel dataModel = DataModel.SQLITE; - - @Comment("Data required to connect to the database") - @Comment("The plotsTableName section is the name of the VR data table in the database") - @Comment("It is best to change these names only if you really need to (e.g. there is a conflict with another plugin)") - @Comment("To rename tables when you already have some VR data in the database:") - @Comment("1. Turn off the server") - @Comment("2. Change data in VR config") - @Comment("3. Rename database tables using phpMyAdmin for example") - @CustomKey("mysql") - public MySQL mysql = new MySQL("localhost", 3306, "db", "root", "passwd", true, "vr_plots"); - - public enum DataModel { - SQLITE, - H2, - MYSQL - } - - @Names(strategy = NameStrategy.IDENTITY) - public static class MySQL extends OkaeriConfig { - - @Variable("VR_MYSQL_HOSTNAME") - public String hostname; - @Variable("VR_MYSQL_PORT") - public int port; - @Variable("VR_MYSQL_DATABASE") - public String database; - @Variable("VR_MYSQL_USER") - public String user; - @Variable("VR_MYSQL_PASSWORD") - public String password; - @Variable("VR_MYSQL_USE_SSL") - public boolean useSSL; - @Variable("VR_MYSQL_USERS_TABLE_NAME") - public String plotsTableName; - - public MySQL(String hostname, int port, String database, String user, String password, boolean useSSL, String plotsTableName) { - this.hostname = hostname; - this.port = port; - this.database = database; - this.user = user; - this.password = password; - this.useSSL = useSSL; - this.plotsTableName = plotsTableName; - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/configs/SizesConfiguration.java b/src/main/java/me/plytki/virtualrealty/configs/SizesConfiguration.java deleted file mode 100644 index 1751108..0000000 --- a/src/main/java/me/plytki/virtualrealty/configs/SizesConfiguration.java +++ /dev/null @@ -1,89 +0,0 @@ -package me.plytki.virtualrealty.configs; - -import eu.okaeri.configs.OkaeriConfig; -import eu.okaeri.configs.annotation.*; -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.PlotSize; -import org.bukkit.Material; - -import java.time.Instant; - -@Header("################################################################") -@Header("# #") -@Header("# Plot Sizes #") -@Header("# #") -@Header("################################################################") -public class SizesConfiguration extends OkaeriConfig { - - @Comment(" ") - @Comment("-------------------------") - @Comment("Don't change this value!") - @CustomKey("config-version") - public final String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); - @Comment("-------------------------") - - @Comment(" ") - @Comment("(<1.13) Legacy Materials: https://helpch.at/docs/1.8/org/bukkit/Material.html") - @Comment("(>1.12) Post-Legacy Materials: https://helpch.at/docs/1.13/org/bukkit/Material.html") - @Comment(" ") - @Comment("floor-data and border-data are only for legacy versions * <1.13 *") - @CustomKey("plot-sizes") - public PlotSizes plotSizes = new PlotSizes(); - - @Names(strategy = NameStrategy.IDENTITY) - public static class PlotSizes extends OkaeriConfig { - - @Variable("VR_SIZE_SMALL") - public Size SMALL = new Size(PlotSize.SMALL); - @Variable("VR_SIZE_MEDIUM") - public Size MEDIUM = new Size(PlotSize.MEDIUM); - @Variable("VR_SIZE_LARGE") - public Size LARGE = new Size(PlotSize.LARGE); - - public PlotSizes() { - } - - public PlotSizes(Size small, Size medium, Size large) { - this.SMALL = small; - this.MEDIUM = medium; - this.LARGE = large; - } - - public static class Size extends OkaeriConfig { - - @Variable("VR_SIZE_FLOORMATERIAL") - @CustomKey("floor-material") - public String floorMaterial; - @Variable("VR_SIZE_FLOORDATA") - @CustomKey("floor-data") - public byte floorData; - @Variable("VR_SIZE_BORDERMATERIAL") - @CustomKey("border-material") - public String borderMaterial; - @Variable("VR_SIZE_BORDERDATA") - @CustomKey("border-data") - public byte borderData; - @Variable("VR_SIZE_LENGTH") - public int length; - @Variable("VR_SIZE_WIDTH") - public int width; - @Variable("VR_SIZE_HEIGHT") - public int height; - - public Size() { - } - - public Size(PlotSize plotSize) { - this.floorMaterial = plotSize.getFloorMaterial().name(); - this.floorData = plotSize.getFloorData(); - this.borderMaterial = plotSize.getBorderMaterial().name(); - this.borderData = plotSize.getBorderData(); - this.length = plotSize.getLength(); - this.width = plotSize.getWidth(); - this.height = plotSize.getHeight(); - } - - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/Direction.java b/src/main/java/me/plytki/virtualrealty/enums/Direction.java deleted file mode 100644 index a3d0c11..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/Direction.java +++ /dev/null @@ -1,45 +0,0 @@ -package me.plytki.virtualrealty.enums; - -public enum Direction { - - SOUTH(315, 45), - WEST(45, 135), - NORTH(135, 225), - EAST(225, 315); - - private final float minYaw; - private final float maxYaw; - - Direction(float minYaw, float maxYaw) { - this.minYaw = minYaw; - this.maxYaw = maxYaw; - } - - public static Direction byYaw(float yaw) { - float absoluteYaw = Math.abs(yaw); - Direction direction = null; - if(absoluteYaw > 315 || absoluteYaw <= 45) { - //south - direction = SOUTH; - } else if(absoluteYaw > 45 && absoluteYaw <= 135) { - //west - direction = yaw > 0 ? WEST : EAST; - } else if(absoluteYaw > 135 && absoluteYaw <= 225) { - //north - direction = NORTH; - } else if(absoluteYaw > 225 && absoluteYaw <= 315) { - //east - direction = yaw > 0 ? EAST : WEST; - } - return direction; - } - - public float getMaxYaw() { - return maxYaw; - } - - public float getMinYaw() { - return minYaw; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/Flag.java b/src/main/java/me/plytki/virtualrealty/enums/Flag.java deleted file mode 100644 index 5409fc1..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/Flag.java +++ /dev/null @@ -1,33 +0,0 @@ -package me.plytki.virtualrealty.enums; - -public class Flag { - - public enum World { - - BLOCK_PLACE(false), - BLOCK_BREAK(false), - INTERACT(false), - IGNITE(false), - EXPLOSION_PRIME(false), - ENTITY_DAMAGE(false), - ARMOR_STAND_MANIPULATION(false), - ITEM_FRAME_DESTROY(false), - ITEM_FRAME_ROTATE(false); - - private boolean allowed; - - World(boolean allowed) { - this.allowed = allowed; - } - - public boolean isAllowed() { - return allowed; - } - - public void setAllowed(boolean allowed) { - this.allowed = allowed; - } - - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/HighlightType.java b/src/main/java/me/plytki/virtualrealty/enums/HighlightType.java deleted file mode 100644 index dc8f244..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/HighlightType.java +++ /dev/null @@ -1,9 +0,0 @@ -package me.plytki.virtualrealty.enums; - -public enum HighlightType { - - ALL, - AVAILABLE, - OWNED - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/Permission.java b/src/main/java/me/plytki/virtualrealty/enums/Permission.java deleted file mode 100644 index 3f0c433..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/Permission.java +++ /dev/null @@ -1,24 +0,0 @@ -package me.plytki.virtualrealty.enums; - -public enum Permission { - - WORLD_BUILD("virtualrealty.build.world"), - PLOT_BUILD("virtualrealty.build.plot"), - BORDER_BUILD("virtualrealty.build.border"); - - private final String permission; - - Permission(String permission) { - this.permission = permission; - } - - public String getPermission() { - return permission; - } - - @Override - public String toString() { - return permission; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/PlotSize.java b/src/main/java/me/plytki/virtualrealty/enums/PlotSize.java deleted file mode 100644 index ad59d12..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/PlotSize.java +++ /dev/null @@ -1,86 +0,0 @@ -package me.plytki.virtualrealty.enums; - -import me.plytki.virtualrealty.VirtualRealty; -import org.bukkit.Material; - -public enum PlotSize { - - SMALL(10, 10, 10, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), - MEDIUM(25, 25, 25, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), - LARGE(50, 50, 50, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), - CUSTOM(0, 0, 0, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0); - - private int length; - private int width; - private int height; - private Material floorMaterial; - private byte floorData; - private Material borderMaterial; - private byte borderData; - - PlotSize(int length, int width, int height, Material floorMaterial, byte floorData, Material borderMaterial, byte borderData) { - this.length = length; - this.width = width; - this.height = height; - this.floorMaterial = floorMaterial; - this.floorData = floorData; - this.borderMaterial = borderMaterial; - this.borderData = borderData; - } - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public Material getFloorMaterial() { - return floorMaterial; - } - - public void setFloorMaterial(Material floorMaterial) { - this.floorMaterial = floorMaterial; - } - - public byte getFloorData() { - return floorData; - } - - public void setFloorData(byte floorData) { - this.floorData = floorData; - } - - public Material getBorderMaterial() { - return borderMaterial; - } - - public void setBorderMaterial(Material borderMaterial) { - this.borderMaterial = borderMaterial; - } - - public byte getBorderData() { - return borderData; - } - - public void setBorderData(byte borderData) { - this.borderData = borderData; - } -} diff --git a/src/main/java/me/plytki/virtualrealty/exceptions/MaterialMatchException.java b/src/main/java/me/plytki/virtualrealty/exceptions/MaterialMatchException.java deleted file mode 100644 index bfe84ec..0000000 --- a/src/main/java/me/plytki/virtualrealty/exceptions/MaterialMatchException.java +++ /dev/null @@ -1,9 +0,0 @@ -package me.plytki.virtualrealty.exceptions; - -public class MaterialMatchException extends Exception { - - public MaterialMatchException(String exception) { - super(exception); - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/ProtectionListener.java b/src/main/java/me/plytki/virtualrealty/listeners/ProtectionListener.java deleted file mode 100644 index 5892906..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/ProtectionListener.java +++ /dev/null @@ -1,448 +0,0 @@ -package me.plytki.virtualrealty.listeners; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Flag; -import me.plytki.virtualrealty.listeners.VirtualListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.utils.ProtectionUtil; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.*; -import org.bukkit.event.entity.*; -import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.player.PlayerArmorStandManipulateEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.world.StructureGrowEvent; -import org.bukkit.util.Vector; - -import java.time.LocalDateTime; - -public class ProtectionListener extends VirtualListener { - - public ProtectionListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onBlockInteract(PlayerInteractEvent e) { - Player player = e.getPlayer(); - if (e.getClickedBlock() != null && (e.getAction() == Action.RIGHT_CLICK_BLOCK || (e.getAction() == Action.LEFT_CLICK_BLOCK && (!VirtualRealty.isLegacy && e.getClickedBlock().getType().isInteractable())))) { - Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { - if (!Flag.World.BLOCK_PLACE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - @EventHandler - public void onBlockPlace(BlockPlaceEvent e) { - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlockPlaced().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { - if (!Flag.World.BLOCK_PLACE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - - @EventHandler - public void onBlockBreak(BlockBreakEvent e) { - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_BREAK)) { - if (!Flag.World.BLOCK_BREAK.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - - @EventHandler - public void onBlockMove(BlockPistonExtendEvent e) { - if (VirtualRealty.isLegacy) { - if (e.getBlocks().isEmpty()) { - Location fromLocation = e.getBlock().getLocation(); - Location toLocation = e.getBlock().getLocation(); - toLocation.add(getDirection(e.getDirection())); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } else { - for (Block block : e.getBlocks()) { - Location fromLocation = block.getLocation(); - Location toLocation = block.getLocation(); - toLocation.add(getDirection(e.getDirection())); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } else { - e.setCancelled(true); - } - } - } - } - } else { - if (e.getBlocks().isEmpty()) { - Location fromLocation = e.getBlock().getLocation(); - Location toLocation = e.getBlock().getLocation(); - toLocation.add(e.getDirection().getDirection()); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } else { - for (Block block : e.getBlocks()) { - Location fromLocation = block.getLocation(); - Location toLocation = block.getLocation(); - toLocation.add(e.getDirection().getDirection()); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } else { - e.setCancelled(true); - } - } - } - } - } - } - - public Vector getDirection(BlockFace blockFace) { - Vector direction = new Vector(blockFace.getModX(), blockFace.getModY(), blockFace.getModZ()); - if (blockFace.getModX() != 0 || blockFace.getModY() != 0 || blockFace.getModZ() != 0) { - direction.normalize(); - } - - return direction; - } - - @EventHandler - public void onIgniteEvent(BlockIgniteEvent e) { - Player player = e.getPlayer(); - if (player != null) { - if (e.getIgnitingBlock() != null) { - Plot plot = PlotManager.getBorderedPlot(e.getIgnitingBlock().getLocation()); - if (plot != null) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - return; - } - e.setCancelled(!plot.hasPermissionToPlot(player)); - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.IGNITE)) { - if (!Flag.World.IGNITE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - } - - @EventHandler - public void onEntityExplode(ExplosionPrimeEvent e) { - Plot plot = PlotManager.getBorderedPlot(e.getEntity().getLocation()); - if (plot != null) { - e.setCancelled(true); - } else { - if (!Flag.World.EXPLOSION_PRIME.isAllowed()) { - e.setCancelled(true); - } - } - } - -// @EventHandler -// public void onPlotEnter(PlayerMoveEvent e) { -// Player player = e.getPlayer(); -// Plot plot = PlotManager.getPlot(e.getTo()); -// if (plot != null && e.getPlayer().isInsideVehicle()) { -// if (!plot.hasPermissionToPlot(player)) { -// e.getPlayer().getVehicle().eject(); -// player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantRideOnPlot); -// } -// } -// } - - @EventHandler - public void onTreeGrow(StructureGrowEvent e) { - for (BlockState block : e.getBlocks()) { - Location fromLocation = e.getLocation(); - Location toLocation = block.getLocation(); - Plot fromPlot = PlotManager.getPlot(fromLocation); - Plot toPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } - } - - @EventHandler - public void onDragonEggMove(BlockFromToEvent e) { - Material block = e.getBlock().getType(); - if (block == Material.DRAGON_EGG || block == Material.LAVA || block == Material.WATER) { - Location fromLocation = e.getBlock().getLocation(); - Location toLocation = e.getToBlock().getLocation(); - Plot fromPlot = PlotManager.getPlot(fromLocation); - Plot toPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } - } - - @EventHandler - public void onProjectileLaunch(ProjectileLaunchEvent e) { - Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); - if (plot != null) { - if (!(e.getEntity().getShooter() instanceof Player && plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player)e.getEntity().getShooter()).getUniqueId()))) { - Player player = (Player) e.getEntity().getShooter(); - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.getEntity().remove(); - } - } else { - e.getEntity().remove(); - } - } - } - } - - @EventHandler - public void onProjectileHit(ProjectileHitEvent e) { - Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); - if (plot != null) { - if (e.getEntity().getShooter() instanceof Player) { - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId()))) { - Player player = (Player) e.getEntity().getShooter(); - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.getEntity().remove(); - } - } else { - e.getEntity().remove(); - } - } - } - } - } - - @EventHandler - public void onFireSpread(BlockSpreadEvent e) { - Location fromLocation = e.getSource().getLocation(); - Location toLocation = e.getBlock().getLocation(); - Plot fromPlot = PlotManager.getPlot(fromLocation); - Plot toPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } - - @EventHandler - public void onArmorStandChange(PlayerArmorStandManipulateEvent e) { - Plot plot = PlotManager.getPlot(e.getPlayer().getLocation()); - Player player = e.getPlayer(); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ARMOR_STAND_MANIPULATION)) { - if (!Flag.World.ARMOR_STAND_MANIPULATION.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - - @EventHandler - public void onItemFrameDamage(HangingBreakByEntityEvent e) { - if (e.getRemover() instanceof Player) { - Player player = (Player) e.getRemover(); - Plot plot = PlotManager.getPlot(player.getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_DESTROY)) { - if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - @EventHandler - public void onItemFrameRotate(PlayerInteractEntityEvent e) { - if (e.getRightClicked().getType().equals(EntityType.ITEM_FRAME)) { - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(player.getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_ROTATE)) { - if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - - @EventHandler - public void onEntityDamage(EntityDamageByEntityEvent e) { - if (e.getDamager() instanceof Player) { - Player player = (Player) e.getDamager(); - Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { - if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - @EventHandler - public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { - if (e.getDamager() instanceof Projectile) { - if (((Projectile) e.getDamager()).getShooter() instanceof Player) { - Player player = ((Player) ((Projectile) e.getDamager()).getShooter()); - Plot plot = PlotManager.getBorderedPlot(e.getDamager().getLocation()); - if (plot != null) { - if (!plot.hasPermissionToPlot(player)) { - e.getDamager().remove(); - e.setCancelled(true); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { - if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/VirtualListener.java b/src/main/java/me/plytki/virtualrealty/listeners/VirtualListener.java deleted file mode 100644 index e612009..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/VirtualListener.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.plytki.virtualrealty.listeners; - -import me.plytki.virtualrealty.VirtualRealty; -import org.bukkit.event.Listener; - -public class VirtualListener implements Listener { - - private final VirtualRealty plugin; - - public VirtualListener(VirtualRealty plugin) { - this.plugin = plugin; - } - - public void registerEvents() { - this.plugin.getServer().getPluginManager().registerEvents(this, this.plugin); - } - - protected VirtualRealty getPlugin() { - return this.plugin; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/plot/BorderListener.java b/src/main/java/me/plytki/virtualrealty/listeners/plot/BorderListener.java deleted file mode 100644 index 4c034b9..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/plot/BorderListener.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.plytki.virtualrealty.listeners.plot; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Permission; -import me.plytki.virtualrealty.listeners.VirtualListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -public class BorderListener extends VirtualListener { - - public BorderListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onBorderBreak(BlockBreakEvent e) { - Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); - if (plot != null) { - if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { - if (plot.getBorderBlocks().contains(e.getBlock())) { - e.setCancelled(true); - e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - - @EventHandler - public void onBorderPlace(BlockPlaceEvent e) { - Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); - if (plot != null) { - if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { - if (plot.getBorderBlocks().contains(e.getBlock())) { - e.setCancelled(true); - e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/plot/PlotListener.java b/src/main/java/me/plytki/virtualrealty/listeners/plot/PlotListener.java deleted file mode 100644 index 4979ac1..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/plot/PlotListener.java +++ /dev/null @@ -1,100 +0,0 @@ -package me.plytki.virtualrealty.listeners.plot; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.listeners.VirtualListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import net.md_5.bungee.api.ChatMessageType; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.Sound; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerMoveEvent; - -import java.util.AbstractMap; -import java.util.HashMap; - -public class PlotListener extends VirtualListener { - - public HashMap> enteredPlot = new HashMap<>(); - - public PlotListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onPlotMove(PlayerMoveEvent e) { - if (e.isCancelled()) return; - Player player = e.getPlayer(); - Location to = e.getTo(); - Plot plot = PlotManager.getPlot(to); - if (plot != null) { - OfflinePlayer offlinePlayer; - String enterPlotString = VirtualRealty.getMessages().enteredAvailablePlot; - if (plot.getOwnedBy() != null) { - offlinePlayer = Bukkit.getOfflinePlayer(plot.getOwnedBy()); - enterPlotString = VirtualRealty.getMessages().enteredOwnedPlot.replaceAll("%owner%", offlinePlayer.getName()).replaceAll("%plot_id%", plot.getID() + ""); - } - if (!enteredPlot.containsKey(player)) { - enteredPlot.put(player, new AbstractMap.SimpleEntry<>(plot, true)); - Plot newPlot = enteredPlot.get(player).getKey(); - if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { - if (newPlot.getOwnedBy() != null && newPlot.getOwnedBy().equals(player.getUniqueId())) { - if (newPlot.getSelectedGameMode() != VirtualRealty.getInstance().getServer().getDefaultGameMode() || newPlot.getSelectedGameMode() != VirtualRealty.getPluginConfiguration().getGameMode()) { - newPlot.setSelectedGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); - } - player.setGameMode(newPlot.getSelectedGameMode()); - } else if (newPlot.getMembers().contains(player.getUniqueId())) { - player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); - } - } - if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { - if (VirtualRealty.getPluginConfiguration().plotSound) { - player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, 0.4f, 0.8f); - } - } - if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(enterPlotString)); - } - } else { - if (!enteredPlot.get(player).getValue()) { - enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(plot, true)); - if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { - player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); - } - } - } - } else { - if (enteredPlot.containsKey(player)) { - if (enteredPlot.get(player).getValue()) { - OfflinePlayer offlinePlayer; - String leavePlotString = VirtualRealty.getMessages().leftAvailablePlot; - if (enteredPlot.get(player).getKey().getOwnedBy() != null) { - offlinePlayer = Bukkit.getOfflinePlayer(enteredPlot.get(player).getKey().getOwnedBy()); - leavePlotString = VirtualRealty.getMessages().leftOwnedPlot.replaceAll("%owner%", offlinePlayer.getName()).replaceAll("%plot_id%", enteredPlot.get(player).getKey().getID() + ""); - if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { - if (enteredPlot.get(player).getKey().hasPlotMembership(player)) { - player.setGameMode(Bukkit.getServer().getDefaultGameMode()); - } - } - } - if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { - if (VirtualRealty.getPluginConfiguration().plotSound) { - player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_CLOSE, 0.3f, 1f); - } - if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(leavePlotString)); - } - } - enteredPlot.remove(player); - return; - } - enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(enteredPlot.get(player).getKey(), false)); - } - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/world/WorldListener.java b/src/main/java/me/plytki/virtualrealty/listeners/world/WorldListener.java deleted file mode 100644 index 4a45a15..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/world/WorldListener.java +++ /dev/null @@ -1,49 +0,0 @@ -package me.plytki.virtualrealty.listeners.world; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Permission; -import me.plytki.virtualrealty.listeners.VirtualListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -public class WorldListener extends VirtualListener { - - public WorldListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onBlockBreak(BlockBreakEvent e) { - if (e.isCancelled()) return; - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); - if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { - if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { - if (plot == null) { - e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - - @EventHandler - public void onBlockPlace(BlockPlaceEvent e) { - if (e.isCancelled()) return; - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); - if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { - if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { - if (plot == null) { - e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java b/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java deleted file mode 100644 index 2ba6ba5..0000000 --- a/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java +++ /dev/null @@ -1,186 +0,0 @@ -package me.plytki.virtualrealty.managers; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.HighlightType; -import me.plytki.virtualrealty.enums.PlotSize; -import me.plytki.virtualrealty.objects.Cuboid; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.objects.math.BlockVector2; -import me.plytki.virtualrealty.objects.math.BlockVector3; -import me.plytki.virtualrealty.sql.SQL; -import org.bukkit.Location; -import org.bukkit.Material; -import org.dynmap.markers.AreaMarker; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; - -public class PlotManager { - - private static final String markerString = "

Plot #%s

Owned By: Available"; - private static final String markerOwnedString = "

Plot #%s

Owned By: %s
Owned Until: %s"; - - public static Set areaMarkers = new HashSet<>(); - public static Set plots = new LinkedHashSet<>(); - - public static void loadPlots() { - plots.clear(); - try { - ResultSet rs = SQL.getStatement().executeQuery("SELECT * FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "`"); - while (rs.next()) { - plots.add(new Plot(rs)); - } - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public static Plot createPlot(Location creationLocation, PlotSize plotSize) { - Plot plot = new Plot(creationLocation, plotSize.getFloorMaterial(), plotSize.getBorderMaterial(), plotSize); - plots.add(plot); - plot.insert(); - return plot; - } - - public static Plot createPlot(Location creationLocation, int length, int width, int height) { - Plot plot = new Plot(creationLocation, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), length, width, height); - plots.add(plot); - plot.insert(); - return plot; - } - - public static Plot getPlot(int ID) { - for (Plot plot : plots) { - if(plot.getID() == ID) { - return plot; - } - } - return null; - } - - public static int getPlotMinID() { - return plots.isEmpty() ? null : plots.stream().findFirst().get().getID(); - } - - public static int getPlotMaxID() { - Plot[] plotArray = PlotManager.plots.toArray(new Plot[PlotManager.plots.size()]); - Plot lastPlot = plotArray[plotArray.length - 1]; - return lastPlot.getID(); - } - - public static List getPlayerPlots(UUID owner) { - List playerPlots = new ArrayList<>(); - for (Plot plot : plots) { - if (plot.getOwnedBy() != null) { - if (plot.getOwnedBy().equals(owner)) { - playerPlots.add(plot); - } - } - } - return playerPlots; - } - - public static Plot getPlot(Location location) { - BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - for (Plot plot : plots) { - Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); - if(region.contains(newVector)) { - return plot; - } - } - return null; - } - - public static boolean isLocationInPlot(Location location, Plot plot) { - BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); - return region.contains(newVector); - } - - public static Plot getBorderedPlot(Location location) { - BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - for (Plot plot : plots) { - Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), location.getWorld()); - if(region.contains(newVector)) { - return plot; - } - } - return null; - } - - public static boolean isLocationInBorderedPlot(Location location, Plot plot) { - BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), location.getWorld()); - return region.contains(newVector); - } - - public static boolean isColliding(Cuboid newPlot) { - for (Plot plot : plots) { - Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), plot.getCreatedLocation().getWorld()); - for (BlockVector2 vector2 : region.getWalls()) { - if (vector2.containedWithin(newPlot.getMinimumPoint(), newPlot.getMaximumPoint())) { - return true; - } - } - } - return false; - } - - private static AreaMarker getAreaMarker(String areaMarkerName) { - for (AreaMarker areaMarker : VirtualRealty.markerset.getAreaMarkers()) { - if (areaMarker.getMarkerID().equalsIgnoreCase(areaMarkerName)) { - return areaMarker; - } - } - return null; - } - - public static void resetPlotMarker(Plot plot) { - if (!VirtualRealty.isDynmapPresent) return; - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - String ownedBy; - double opacity; - int color; - if (plot.getOwnedBy() == null) { - ownedBy = "Available"; - color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.getHexColor(); - opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.opacity; - } else { - ownedBy = plot.getPlotOwner().getName(); - color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.getHexColor(); - opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.opacity; - } - if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.OWNED && plot.getOwnedBy() == null) return; - if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.AVAILABLE && plot.getOwnedBy() != null) return; - AreaMarker marker = getAreaMarker("virtualrealty.plots." + plot.getID()); - if (marker == null) { - marker = VirtualRealty.markerset.createAreaMarker("virtualrealty.plots." + plot.getID(), - - plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true, - - plot.getCreatedWorld(), new double[]{plot.getXMin(), plot.getXMax()}, new double[]{plot.getZMin(), plot.getZMax()}, true); - - areaMarkers.add(marker); - } else { - marker.setLabel( - - plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true); - - } - marker.setFillStyle(opacity, color); - marker.setLineStyle(2, 0.8, 0x474747); - marker.setMarkerSet(VirtualRealty.markerset); - } - - public static void removeDynMapMarker(Plot plot) { - if (!VirtualRealty.isDynmapPresent || VirtualRealty.dapi == null || VirtualRealty.markerset == null) return; - AreaMarker marker = VirtualRealty.markerset.findAreaMarker("virtualrealty.plots." + plot.getID()); - areaMarkers.remove(marker); - marker.deleteMarker(); - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/objects/Cuboid.java b/src/main/java/me/plytki/virtualrealty/objects/Cuboid.java deleted file mode 100644 index 1273672..0000000 --- a/src/main/java/me/plytki/virtualrealty/objects/Cuboid.java +++ /dev/null @@ -1,187 +0,0 @@ -package me.plytki.virtualrealty.objects; - -import me.plytki.virtualrealty.objects.math.BlockVector2; -import me.plytki.virtualrealty.objects.math.BlockVector3; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -public class Cuboid { - - private int xMin; - private int xMax; - private int yMin; - private int yMax; - private int zMin; - private int zMax; - private double xMinCentered; - private double xMaxCentered; - private double yMinCentered; - private double yMaxCentered; - private double zMinCentered; - private double zMaxCentered; - private World world; - - public Cuboid(Location point1, Location point2) { - this.xMin = Math.min(point1.getBlockX(), point2.getBlockX()); - this.xMax = Math.max(point1.getBlockX(), point2.getBlockX()); - this.yMin = Math.min(point1.getBlockY(), point2.getBlockY()); - this.yMax = Math.max(point1.getBlockY(), point2.getBlockY()); - this.zMin = Math.min(point1.getBlockZ(), point2.getBlockZ()); - this.zMax = Math.max(point1.getBlockZ(), point2.getBlockZ()); - this.world = point1.getWorld(); - this.xMinCentered = this.xMin + 0.5; - this.xMaxCentered = this.xMax + 0.5; - this.yMinCentered = this.yMin + 0.5; - this.yMaxCentered = this.yMax + 0.5; - this.zMinCentered = this.zMin + 0.5; - this.zMaxCentered = this.zMax + 0.5; - } - - public Cuboid(BlockVector3 point1, BlockVector3 point2, World world) { - this.xMin = Math.min(point1.getBlockX(), point2.getBlockX()); - this.xMax = Math.max(point1.getBlockX(), point2.getBlockX()); - this.yMin = Math.min(point1.getBlockY(), point2.getBlockY()); - this.yMax = Math.max(point1.getBlockY(), point2.getBlockY()); - this.zMin = Math.min(point1.getBlockZ(), point2.getBlockZ()); - this.zMax = Math.max(point1.getBlockZ(), point2.getBlockZ()); - this.world = world; - this.xMinCentered = this.xMin + 0.5; - this.xMaxCentered = this.xMax + 0.5; - this.yMinCentered = this.yMin + 0.5; - this.yMaxCentered = this.yMax + 0.5; - this.zMinCentered = this.zMin + 0.5; - this.zMaxCentered = this.zMax + 0.5; - } - - - public List blockList() { - ArrayList bL = new ArrayList<>((xMax - xMin) * (yMax - yMin) * (zMax - zMin)); - for(int x = this.xMin; x <= this.xMax; ++x) { - for(int y = this.yMin; y <= this.yMax; ++y) { - for(int z = this.zMin; z <= this.zMax; ++z) { - Block b = this.world.getBlockAt(x, y, z); - bL.add(b); - } - } - } - return bL; - } - - public Location getCenter() { - return new Location(this.world, (this.xMax - this.xMin) / 2 + this.xMin + 1, (this.yMax - this.yMin) / 2 + this.yMin, (this.zMax - this.zMin) / 2 + this.zMin + 1); - } - - public BlockVector3 getCenterVector() { - return BlockVector3.at((this.xMax - this.xMin) / 2 + this.xMin + 1, (this.yMax - this.yMin) / 2 + this.yMin, (this.zMax - this.zMin) / 2 + this.zMin + 1); - } - - public double getDistance() { - return this.getPoint1().distance(this.getPoint2()); - } - - public double getDistanceSquared() { - return this.getPoint1().distanceSquared(this.getPoint2()); - } - - public int getHeight() { - return this.yMax - this.yMin + 1; - } - - public BlockVector3 getMinimumPoint() { - return BlockVector3.at(this.xMin, this.yMin, this.zMin); - } - - public BlockVector3 getMaximumPoint() { - return BlockVector3.at(this.xMax, this.yMax, this.zMax); - } - - public Location getPoint1() { - return new Location(this.world, this.xMin, this.yMin, this.zMin); - } - - public Location getPoint2() { - return new Location(this.world, this.xMax, this.yMax, this.zMax); - } - - public Location getRandomLocation() { - Random rand = new Random(); - int x = rand.nextInt(Math.abs(this.xMax - this.xMin) + 1) + this.xMin; - int y = rand.nextInt(Math.abs(this.yMax - this.yMin) + 1) + this.yMin; - int z = rand.nextInt(Math.abs(this.zMax - this.zMin) + 1) + this.zMin; - return new Location(this.world, x, y, z); - } - - public boolean contains(BlockVector3 vector3) { - return vector3.getBlockX() >= this.xMin && vector3.getBlockX() <= this.xMax && vector3.getBlockY() >= this.yMin && vector3.getBlockY() <= this.yMax && vector3 - .getBlockZ() >= this.zMin && vector3.getBlockZ() <= this.zMax; - } - - public boolean contains(BlockVector3 vector3, World world) { - return world == this.world && vector3.getBlockX() >= this.xMin && vector3.getBlockX() <= this.xMax && vector3.getBlockY() >= this.yMin && vector3.getBlockY() <= this.yMax && vector3 - .getBlockZ() >= this.zMin && vector3.getBlockZ() <= this.zMax; - } - - public int getTotalBlockSize() { - return this.getHeight() * this.getXWidth() * this.getZWidth(); - } - - public int getXWidth() { - return this.xMax - this.xMin + 1; - } - - public int getZWidth() { - return this.zMax - this.zMin + 1; - } - - public boolean isIn(Location loc) { - return loc.getWorld() == this.world && loc.getBlockX() >= this.xMin && loc.getBlockX() <= this.xMax && loc.getBlockY() >= this.yMin && loc.getBlockY() <= this.yMax && loc - .getBlockZ() >= this.zMin && loc.getBlockZ() <= this.zMax; - } - - public boolean isIn(Player player) { - return this.isIn(player.getLocation()); - } - - public boolean isInWithMarge(Location loc, double marge) { - return loc.getWorld() == this.world && loc.getX() >= this.xMinCentered - marge && loc.getX() <= this.xMaxCentered + marge && loc.getY() >= this.yMinCentered - marge && loc - .getY() <= this.yMaxCentered + marge && loc.getZ() >= this.zMinCentered - marge && loc.getZ() <= this.zMaxCentered + marge; - } - - public boolean isColliding(Cuboid region) { - List flatRegion1 = new ArrayList<>(this.getFlatRegion()); - List flatRegion2 = new ArrayList<>(region.getFlatRegion()); - for (BlockVector2 vector1 : flatRegion1) { - for (BlockVector2 vector2 : flatRegion2) - if (vector1.getBlockX() == vector2.getBlockX() && vector1.getBlockZ() == vector2.getBlockZ()) return true; - } - return false; - } - - public List getFlatRegion() { - List blocksVector = new ArrayList<>(); - for (Block block : blockList()) { - blocksVector.add(BlockVector2.at(block.getLocation().getBlockX(), block.getLocation().getBlockZ())); - } - return blocksVector; - } - - public List getWalls() { - List walls = new ArrayList<>(); - for (int z = zMin; z <= zMax; z++) { - walls.add(BlockVector2.at(xMin, z)); - walls.add(BlockVector2.at(xMax, z)); - } - for (int x = xMin; x < xMax; x++) { - walls.add(BlockVector2.at(x, zMin)); - walls.add(BlockVector2.at(x, zMax)); - } - return walls; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/objects/Plot.java b/src/main/java/me/plytki/virtualrealty/objects/Plot.java deleted file mode 100644 index 2b1434e..0000000 --- a/src/main/java/me/plytki/virtualrealty/objects/Plot.java +++ /dev/null @@ -1,796 +0,0 @@ -package me.plytki.virtualrealty.objects; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Direction; -import me.plytki.virtualrealty.enums.Permission; -import me.plytki.virtualrealty.enums.PlotSize; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.math.BlockVector3; -import me.plytki.virtualrealty.sql.SQL; -import me.plytki.virtualrealty.utils.SchematicUtil; -import org.apache.commons.io.FileUtils; -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.time.Instant; -import java.time.LocalDateTime; -import java.util.*; - -public class Plot { - - private int ID; - private UUID ownedBy; - private Set members; - private String assignedBy; - private LocalDateTime ownedUntilDate; - private PlotSize plotSize; - private int length; - private int width; - private int height; - private Material floorMaterial; - private byte floorData; - private Material borderMaterial; - private byte borderData; - private Location createdLocation; - private Direction createdDirection; - private BlockVector3 bottomLeftCorner; - private BlockVector3 topRightCorner; - private BlockVector3 borderBottomLeftCorner; - private BlockVector3 borderTopRightCorner; - private GameMode selectedGameMode; - private String createdWorld; - private Instant modified; - - @Override - public String toString() { - return "{ ID: " + ID + ", ownedBy: " + ownedBy + "}"; - } - - public Plot(Location location, Material floorMaterial, Material borderMaterial, PlotSize plotSize) { - this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; - this.ownedBy = null; - this.members = new HashSet<>(); - this.assignedBy = null; - this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); - this.floorMaterial = floorMaterial; - this.floorData = 0; - this.borderMaterial = borderMaterial; - this.borderData = 0; - this.plotSize = plotSize; - this.length = plotSize.getLength(); - this.width = plotSize.getWidth(); - this.height = plotSize.getHeight(); - this.createdLocation = location; - this.createdDirection = Direction.byYaw(location.getYaw()); - this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); - this.createdWorld = location.getWorld().getName(); - this.modified = Instant.now(); - initialize(); - initializeCorners(); - if (VirtualRealty.markerset != null) { - PlotManager.resetPlotMarker(this); - } - } - - public Plot(Location location, Material floorMaterial, Material borderMaterial, int length, int width, int height) { - this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; - this.ownedBy = null; - this.members = new HashSet<>(); - this.assignedBy = null; - this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); - this.floorMaterial = floorMaterial; - this.floorData = 0; - this.borderMaterial = borderMaterial; - this.borderData = 0; - this.plotSize = PlotSize.CUSTOM; - this.length = length; - this.width = width; - this.height = height; - this.createdLocation = location; - this.createdDirection = Direction.byYaw(location.getYaw()); - this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); - this.createdWorld = location.getWorld().getName(); - this.modified = Instant.now(); - initialize(); - initializeCorners(); - if (VirtualRealty.markerset != null) { - PlotManager.resetPlotMarker(this); - } - } - - - public Plot(ResultSet rs) { - try { - this.ID = rs.getInt("ID"); - this.ownedBy = rs.getString("ownedBy").isEmpty() ? null : UUID.fromString(rs.getString("ownedBy")); - this.members = new HashSet<>(); - String membersString = rs.getString("members"); - if (membersString != null && !membersString.isEmpty()) { - String[] membersArray = membersString.substring(0, membersString.length() - 1).split(";"); - for (String s : membersArray) { - members.add(UUID.fromString(s)); - } - } - this.assignedBy = rs.getString("assignedBy").equalsIgnoreCase("null") ? null : rs.getString("assignedBy"); - this.ownedUntilDate = rs.getTimestamp("ownedUntilDate").toLocalDateTime(); - this.floorMaterial = Material.getMaterial(rs.getString("floorMaterial").split(":")[0]); - this.floorData = rs.getString("floorMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("floorMaterial").split(":")[1]); - if (rs.getString("borderMaterial") != null) { - this.borderMaterial = Material.getMaterial(rs.getString("borderMaterial").split(":")[0]); - this.borderData = rs.getString("borderMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("borderMaterial").split(":")[1]); - } - this.plotSize = PlotSize.valueOf(rs.getString("plotSize")); - this.length = rs.getInt("length"); - this.width = rs.getInt("width"); - this.height = rs.getInt("height"); - ArrayList location = new ArrayList<>(Arrays.asList(rs.getString("createdLocation").subSequence(0, rs.getString("createdLocation").length() - 1).toString().split(";"))); - Location createLocation = new Location(Bukkit.getWorld(location.get(0)), Double.parseDouble(location.get(1)), Double.parseDouble(location.get(2)), Double.parseDouble(location.get(3)), Float.parseFloat(location.get(4)), Float.parseFloat(location.get(5))); - this.createdLocation = rs.getString("createdLocation").isEmpty() ? null : createLocation; - this.createdDirection = Direction.byYaw(createdLocation.getYaw()); - this.selectedGameMode = GameMode.CREATIVE; - this.createdWorld = location.get(0); - if (floorMaterial == null) { - floorMaterial = plotSize.getFloorMaterial(); - floorData = plotSize.getFloorData(); - } - if (borderMaterial == null) { - borderMaterial = plotSize.getBorderMaterial(); - borderData = plotSize.getBorderData(); - } - initializeCorners(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public boolean hasPermissionToPlot(Player player) { - if (player.hasPermission(Permission.PLOT_BUILD.getPermission())) return true; - if (members.contains(player.getUniqueId())) return true; - return ownedBy != null && ownedBy.equals(player.getUniqueId()); - } - - public boolean hasPlotMembership(Player player) { - if (members.contains(player.getUniqueId())) return true; - return ownedBy != null && ownedBy.equals(player.getUniqueId()); - } - - public boolean isOwnershipExpired() { - return ownedUntilDate.isBefore(LocalDateTime.now()); - } - - public int getXMin() { - return Math.min(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); - } - - public int getXMax() { - return Math.max(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); - } - - public int getZMin() { - return Math.min(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); - } - - public int getZMax() { - return Math.max(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); - } - - public int getID() { - return ID; - } - - public void setID(int ID) { - this.ID = ID; - } - - public UUID getOwnedBy() { - return ownedBy; - } - - public void setOwnedBy(UUID ownedBy) { - this.ownedBy = ownedBy; - members.remove(ownedBy); - updateMarker(); - modified(); - } - - public String getAssignedBy() { - return assignedBy; - } - - public void setAssignedBy(String assignedBy) { - this.assignedBy = assignedBy; - modified(); - } - - public LocalDateTime getOwnedUntilDate() { - return ownedUntilDate; - } - - public void setOwnedUntilDate(LocalDateTime ownedUntilDate) { - this.ownedUntilDate = ownedUntilDate; - updateMarker(); - modified(); - } - - public PlotSize getPlotSize() { - return plotSize; - } - - public void setPlotSize(PlotSize plotSize) { - this.plotSize = plotSize; - } - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public Material getFloorMaterial() { - return floorMaterial; - } - - public void setFloorMaterial(Material floorMaterial, byte data) { - this.floorMaterial = floorMaterial; - this.floorData = data; - initializeFloor(); - modified(); - } - - public Location getCreatedLocation() { - return createdLocation; - } - - public void setBorderMaterial(Material borderMaterial, byte data) { - this.borderMaterial = borderMaterial; - this.borderData = data; - modified(); - } - - public Material getBorderMaterial() { - return borderMaterial; - } - - public void setCreatedLocation(Location createdLocation) { - this.createdLocation = createdLocation; - } - - public BlockVector3 getBottomLeftCorner() { - return bottomLeftCorner; - } - - public void setBottomLeftCorner(BlockVector3 bottomLeftCorner) { - this.bottomLeftCorner = bottomLeftCorner; - } - - public BlockVector3 getTopRightCorner() { - return topRightCorner; - } - - public void setTopRightCorner(BlockVector3 topRightCorner) { - this.topRightCorner = topRightCorner; - } - - public BlockVector3 getBorderBottomLeftCorner() { - return borderBottomLeftCorner; - } - - public void setBorderBottomLeftCorner(BlockVector3 borderBottomLeftCorner) { - this.borderBottomLeftCorner = borderBottomLeftCorner; - } - - public BlockVector3 getBorderTopRightCorner() { - return borderTopRightCorner; - } - - public void setBorderTopRightCorner(BlockVector3 borderTopRightCorner) { - this.borderTopRightCorner = borderTopRightCorner; - } - - public BlockVector3 getBorderedCenter() { - return new Cuboid(borderBottomLeftCorner, borderTopRightCorner, createdLocation.getWorld()).getCenterVector(); - } - - public BlockVector3 getCenter() { - return new Cuboid(bottomLeftCorner, topRightCorner, createdLocation.getWorld()).getCenterVector(); - } - - public GameMode getSelectedGameMode() { - return selectedGameMode; - } - - public String getCreatedWorld() { - return createdWorld; - } - - public OfflinePlayer getPlotOwner() { - return ownedBy == null ? null : Bukkit.getOfflinePlayer(ownedBy); - } - - public void setSelectedGameMode(GameMode selectedGameMode) { - this.selectedGameMode = selectedGameMode; - } - - public void addMember(UUID uuid) { - members.add(uuid); - modified(); - } - - public void removeMember(UUID uuid) { - members.remove(uuid); - } - - public Set getMembers() { - return members; - } - - public Set getMembersPlayer() { - Set offlinePlayers = new HashSet<>(); - for (UUID member : members) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(member); - offlinePlayers.add(offlinePlayer); - } - return offlinePlayers; - } - - private void setFloorBlock(Block floorBlock) { - if (VirtualRealty.isLegacy) { - try { - Method m = Block.class.getDeclaredMethod("setType", Material.class); - m.setAccessible(true); - m.invoke(floorBlock, this.floorMaterial); - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(floorBlock, this.floorData); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - floorBlock.setType(floorMaterial); - } - modified(); - } - - private void initializeFloor() { - Location location = createdLocation; - Direction direction = Direction.byYaw(location.getYaw()); - switch(direction) { - case SOUTH: { - for (int x = location.getBlockX() - width + 1; x < location.getBlockX() + 1; x++) { - for (int z = location.getBlockZ(); z < location.getBlockZ() + length; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - case WEST: { - for (int x = location.getBlockX() - length + 1; x < location.getBlockX() + 1; x++) { - for (int z = location.getBlockZ() - width + 1; z < location.getBlockZ() + 1; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - case NORTH: { - for (int x = location.getBlockX(); x < location.getBlockX() + width; x++) { - for (int z = location.getBlockZ() - length + 1; z < location.getBlockZ() + 1; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - case EAST: { - for (int x = location.getBlockX(); x < location.getBlockX() + length; x++) { - for (int z = location.getBlockZ(); z < location.getBlockZ() + width; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - } - - public void initializeCorners() { - Location location = createdLocation; - Direction direction = Direction.byYaw(location.getYaw()); - Location location1; - Location location2; - Location border1; - Location border2; - switch(direction) { - case SOUTH: { - location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); - location2 = new Location(location.getWorld(), location.getBlockX() - width + 1, location.getBlockY() + height, location.getBlockZ() + length - 1); - border1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); - border2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); - break; - } - case WEST: { - location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); - location2 = new Location(location.getWorld(), location.getBlockX() - length + 1, location.getBlockY() + height, location.getBlockZ() - width + 1); - border1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); - border2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); - break; - } - case NORTH: { - location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); - location2 = new Location(location.getWorld(), location.getBlockX() + width - 1, location.getBlockY() + height, location.getBlockZ() - length + 1); - border1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); - border2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); - break; - } - case EAST: { - location1 = new Location(location.getWorld(), location.getBlockX() + length - 1, location.getBlockY() - 10, location.getBlockZ()); - location2 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() + height, location.getBlockZ() + width - 1); - border1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); - border2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - this.bottomLeftCorner = BlockVector3.at(location1.getBlockX(), location1.getBlockY(), location1.getBlockZ()); - this.topRightCorner = BlockVector3.at(location2.getBlockX(), location2.getBlockY(), location2.getBlockZ()); - this.borderBottomLeftCorner = BlockVector3.at(border1.getBlockX(), border1.getBlockY(), border1.getBlockZ()); - this.borderTopRightCorner = BlockVector3.at(border2.getBlockX(), border2.getBlockY(), border2.getBlockZ()); - } - - public void initialize() { - prepareBlocks(createdLocation); - } - - public Set getBorderBlocks() { - Set blocks = new HashSet<>(); - Location location = this.getCreatedLocation(); - Direction direction = Direction.byYaw(location.getYaw()); - int maxX; - int maxZ; - int minX; - int minZ; - switch(direction) { - case SOUTH: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + length + 1; - minX = location.getBlockX() - width + 1; - minZ = location.getBlockZ() - 1; - break; - } - case WEST: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX() - length + 1; - minZ = location.getBlockZ() - width; - break; - } - case NORTH: { - maxX = location.getBlockX() + width + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - length; - break; - } - case EAST: { - maxX = location.getBlockX() + length + 1; - maxZ = location.getBlockZ() + width + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - 1; - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - for (int x = minX - 1; x < maxX; x++) { - for (int z = minZ; z < maxZ; z++) { - if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { - blocks.add(location.getWorld().getBlockAt(x, location.getBlockY() + 1, z)); - } - } - } - return blocks; - } - - public Set getFloorBlocks() { - Set blocks = new HashSet<>(); - Location location = this.getCreatedLocation(); - Direction direction = Direction.byYaw(location.getYaw()); - int maxX; - int maxZ; - int minX; - int minZ; - switch(direction) { - case SOUTH: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + length + 1; - minX = location.getBlockX() - width + 1; - minZ = location.getBlockZ() - 1; - break; - } - case WEST: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX() - length + 1; - minZ = location.getBlockZ() - width; - break; - } - case NORTH: { - maxX = location.getBlockX() + width + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - length; - break; - } - case EAST: { - maxX = location.getBlockX() + length + 1; - maxZ = location.getBlockZ() + width + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - 1; - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - for (int x = minX - 1; x < maxX; x++) { - for (int z = minZ; z < maxZ; z++) { - blocks.add(location.getWorld().getBlockAt(x, location.getBlockY(), z)); - } - } - return blocks; - } - - public void setBorder(Material material, byte data) { - borderMaterial = material; - borderData = data; - for (Block borderBlock : getBorderBlocks()) { - if (VirtualRealty.isLegacy) { - borderBlock.setType(material); - try { - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(borderBlock, data); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - } else { - borderBlock.setType(material); - } - } - modified(); - } - - public void prepareBlocks(Location location) { - Direction direction = Direction.byYaw(location.getYaw()); - Location location1; - Location location2; - switch (direction) { - case SOUTH: { - location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); - location2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); - SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - break; - } - case WEST: { - location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); - location2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); - SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - break; - } - case NORTH: { - location1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); - location2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); - SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - break; - } - case EAST: { - location1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); - location2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); - SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - break; - } - } - for (Block floorBlock : getFloorBlocks()) { - for (int y = location.getBlockY() + height; y > location.getBlockY() - 1; y--) { - Block airBlock = location.getWorld().getBlockAt(floorBlock.getX(), y, floorBlock.getZ()); - airBlock.setType(Material.AIR); - } - floorBlock.setType(floorMaterial); - if (VirtualRealty.isLegacy) { - try { - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(floorBlock, plotSize.getFloorData()); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - } - } - int maxX = 0; - int maxZ = 0; - int minX = 0; - int minZ = 0; - switch(direction) { - case SOUTH: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + length + 1; - minX = location.getBlockX() - width + 1; - minZ = location.getBlockZ() - 1; - break; - } - case WEST: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX() - length + 1; - minZ = location.getBlockZ() - width; - break; - } - case NORTH: { - maxX = location.getBlockX() + width + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - length; - break; - } - case EAST: { - maxX = location.getBlockX() + length + 1; - maxZ = location.getBlockZ() + width + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - 1; - break; - } - } - for (int x = minX - 1; x < maxX; x++) { - for (int z = minZ; z < maxZ; z++) { - if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { - Block borderBlock = location.getWorld().getBlockAt(x, location.getBlockY() + 1, z); - if (VirtualRealty.isLegacy) { - borderBlock.setType(plotSize.getBorderMaterial()); - try { - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(borderBlock, plotSize.getBorderData()); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - } else { - borderBlock.setType(plotSize.getBorderMaterial()); - } - } - } - } - } - - public void unloadPlot() { - switch (createdDirection) { - case SOUTH: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - width, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); - break; - } - case WEST: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - length, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - width)); - break; - } - case NORTH: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - length)); - break; - } - case EAST: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); - break; - } - } - } - - public String getMembersString() { - StringBuilder stringBuilder = new StringBuilder(); - for (UUID member : members) { - stringBuilder.append(member.toString()).append(";"); - } - return stringBuilder.toString(); - } - - public void insert() { - StringBuilder builder = new StringBuilder(); - builder.append(this.createdLocation.getWorld().getName() + ";"); - builder.append(this.createdLocation.getX() + ";"); - builder.append(this.createdLocation.getY() + ";"); - builder.append(this.createdLocation.getZ() + ";"); - builder.append(this.createdLocation.getYaw() + ";"); - builder.append(this.createdLocation.getPitch() + ";"); - try { - SQL.getStatement().execute("INSERT INTO `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + - "` (`ID`, `ownedBy`, `members`, `assignedBy`, `ownedUntilDate`," + - " `floorMaterial`, `borderMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`, `created`, `modified`) " + - "VALUES ('" + this.ID + "', '" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "','" + getMembersString() + "', '" + this.assignedBy + "', " + - "'" + Timestamp.valueOf(this.ownedUntilDate) + "', '" + this.floorMaterial + ":" + this.floorData + "', '" + this.borderMaterial + ":" + this.borderData + "'," + - " '" + this.plotSize + "', '" + this.length + "', '" + this.width + "', '" + this.height + "', '" + builder + "', '" + Timestamp.from(Instant.now()) + "', '" + Timestamp.from(Instant.now()) + "')"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void update() { - try { - SQL.getStatement().execute("UPDATE `" + - VirtualRealty.getPluginConfiguration().mysql.plotsTableName + - "` SET `ownedBy`='" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "'," + - " `members`='" + getMembersString() + "', `assignedBy`='" + this.assignedBy + "'," + - " `ownedUntilDate`='" + Timestamp.valueOf(this.ownedUntilDate) + "'," + - " `floorMaterial`='" + this.floorMaterial + ":" + this.floorData + "'," + - " `borderMaterial`='" + this.borderMaterial + ":" + this.borderData + "'," + - " `plotSize`='" + this.plotSize + "'," + - " `length`='" + this.length + "'," + - " `width`='" + this.width + "'," + - " `height`='" + this.height + "'," + - " `modified`='" + (this.modified != null ? Timestamp.from(this.modified) : Timestamp.from(Instant.now())) + "'" + - " WHERE `ID`='" + this.ID + "'"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void remove() { - this.unloadPlot(); - PlotManager.removeDynMapMarker(this); - try { - SQL.getStatement().execute("DELETE FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` WHERE `ID` = '" + ID + "';"); - } catch (SQLException e) { - e.printStackTrace(); - } - int id = ID; - File file = new File(VirtualRealty.plotsSchemaFolder, "plot" + id + ".region"); - if (file.exists()) - FileUtils.deleteQuietly(file); - PlotManager.plots.remove(this); - } - - public Direction getCreatedDirection() { - return createdDirection; - } - - public void setCreatedDirection(Direction createdDirection) { - this.createdDirection = createdDirection; - } - - public void updateMarker() { - PlotManager.resetPlotMarker(this); - } - - public void modified() { - this.modified = Instant.now(); - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector2.java b/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector2.java deleted file mode 100644 index 7101190..0000000 --- a/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector2.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.plytki.virtualrealty.objects.math; - -import java.util.Vector; - -public class BlockVector2 extends Vector { - - private int x; - private int z; - - public BlockVector2(int x, int z) { - this.x = x; - this.z = z; - } - - public static BlockVector2 at(int x, int z) { - return new BlockVector2(x, z); - } - - public int getBlockX() { - return x; - } - - public void setX(int x) { - this.x = x; - } - - public int getBlockZ() { - return z; - } - - public void setZ(int z) { - this.z = z; - } - - public boolean containedWithin(BlockVector2 min, BlockVector2 max) { - return this.x >= min.x && this.x <= max.x && this.z >= min.z && this.z <= max.z; - } - - @Override - public String toString() { - return "(" + x + ", " + z + ")"; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector3.java b/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector3.java deleted file mode 100644 index 1194dd5..0000000 --- a/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector3.java +++ /dev/null @@ -1,59 +0,0 @@ -package me.plytki.virtualrealty.objects.math; - -import org.bukkit.Location; - -public class BlockVector3 extends BlockVector2 { - - private int x; - private int y; - private int z; - - private BlockVector3(int x, int y, int z) { - super(x, z); - this.x = x; - this.y = y; - this.z = z; - } - - public static BlockVector3 at(int x, int y, int z) { - return new BlockVector3(x, y, z); - } - - public static BlockVector3 locationToVector(Location location) { - return new BlockVector3(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } - - public int getBlockX() { - return x; - } - - public void setX(int x) { - this.x = x; - } - - public int getBlockY() { - return y; - } - - public void setY(int y) { - this.y = y; - } - - public int getBlockZ() { - return z; - } - - public void setZ(int z) { - this.z = z; - } - - @Override - public String toString() { - return "(" + x + ", " + y + ", " + z + ")"; - } - - public String toSimpleString() { - return x + ", " + y + ", " + z; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/registry/VirtualPlaceholders.java b/src/main/java/me/plytki/virtualrealty/registry/VirtualPlaceholders.java deleted file mode 100644 index 3d86be8..0000000 --- a/src/main/java/me/plytki/virtualrealty/registry/VirtualPlaceholders.java +++ /dev/null @@ -1,123 +0,0 @@ -package me.plytki.virtualrealty.registry; - -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import org.bukkit.entity.Player; - -public class VirtualPlaceholders extends PlaceholderExpansion { - - private final VirtualRealty plugin; - - /** - * Since we register the expansion inside our own plugin, we - * can simply use this method here to get an instance of our - * plugin. - * - * @param plugin - * The instance of our plugin. - */ - public VirtualPlaceholders(VirtualRealty plugin){ - this.plugin = plugin; - } - - /** - * Because this is an internal class, - * you must override this method to let PlaceholderAPI know to not unregister your expansion class when - * PlaceholderAPI is reloaded - * - * @return true to persist through reloads - */ - @Override - public boolean persist(){ - return true; - } - - /** - * Because this is a internal class, this check is not needed - * and we can simply return {@code true} - * - * @return Always true since it's an internal class. - */ - @Override - public boolean canRegister(){ - return true; - } - - /** - * The name of the person who created this expansion should go here. - *
For convienience do we return the author from the plugin.yml - * - * @return The name of the author as a String. - */ - @Override - public String getAuthor(){ - return plugin.getDescription().getAuthors().toString(); - } - - /** - * The placeholder identifier should go here. - *
This is what tells PlaceholderAPI to call our onRequest - * method to obtain a value if a placeholder starts with our - * identifier. - *
The identifier has to be lowercase and can't contain _ or % - * - * @return The identifier in {@code %_%} as String. - */ - @Override - public String getIdentifier(){ - return "virtualrealty"; - } - - /** - * This is the version of the expansion. - *
You don't have to use numbers, since it is set as a String. - * - * For convienience do we return the version from the plugin.yml - * - * @return The version as a String. - */ - @Override - public String getVersion(){ - return plugin.getDescription().getVersion(); - } - - /** - * This is the method called when a placeholder with our identifier - * is found and needs a value. - *
We specify the value identifier in this method. - *
Since version 2.9.1 can you use OfflinePlayers in your requests. - * - * @param player - * A {@link org.bukkit.entity.Player Player}. - * @param identifier - * A String containing the identifier/value. - * - * @return possibly-null String of the requested identifier. - */ - @Override - public String onPlaceholderRequest(Player player, String identifier){ - if(player == null) - return ""; - - Plot plot = PlotManager.getBorderedPlot(player.getLocation()); - if (identifier.equals("plot_id")) { - if (plot == null) return ""; - return String.valueOf(plot.getID()); - } - if (identifier.equals("plot_owner")) { - if (plot == null) return ""; - if (plot.getOwnedBy() == null) return ""; - return String.valueOf(plot.getPlotOwner().getName()); - } - if (identifier.equals("is_plot_owner")) { - if (plot == null) return ""; - if (plot.getOwnedBy() == null) return "false"; - if (plot.getOwnedBy().equals(player.getUniqueId())) return "true"; - return "false"; - } - return null; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/sql/SQL.java b/src/main/java/me/plytki/virtualrealty/sql/SQL.java deleted file mode 100644 index 2a34081..0000000 --- a/src/main/java/me/plytki/virtualrealty/sql/SQL.java +++ /dev/null @@ -1,125 +0,0 @@ -package me.plytki.virtualrealty.sql; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.configs.PluginConfiguration; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; - -public class SQL { - - private static Connection connection; - private static Statement statement; - public static final long MYSQL_TIMEOUT_MS = 28800000; - private static long lastQuery = System.currentTimeMillis(); - - public static void connect() { - try { - switch (VirtualRealty.getPluginConfiguration().dataModel) { - case H2: { - Class.forName("me.plytki.virtualrealty.utils.h2.Driver"); - connection = DriverManager.getConnection("jdbc:h2:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data"); - break; - } - case SQLITE: { - Class.forName("org.sqlite.JDBC"); - File dataDir = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data"); - if (!dataDir.exists()) { - dataDir.mkdirs(); - } - connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.db"); - break; - } - case MYSQL: { - Class.forName("com.mysql.jdbc.Driver"); - connection = DriverManager.getConnection("jdbc:mysql://" + VirtualRealty.getPluginConfiguration().mysql.hostname + ":" + VirtualRealty.getPluginConfiguration().mysql.port + "/" + VirtualRealty.getPluginConfiguration().mysql.database + "?useSSL=" + VirtualRealty.getPluginConfiguration().mysql.useSSL + "&autoReconnect=true", VirtualRealty.getPluginConfiguration().mysql.user, VirtualRealty.getPluginConfiguration().mysql.password); - break; - } - } - createStatement(); - } catch (SQLException | ClassNotFoundException ex) { - ex.printStackTrace(); - } - } - - public static void createStatement() { - try { - statement = connection.createStatement(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public static void closeConnection() { - try { - if (statement != null && !statement.isClosed()) { - statement.close(); - } - if (connection != null) - connection.close(); - VirtualRealty.debug("Database connection closed"); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public static void createTables() { - try { - statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); - updateTables(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - public static void updateTables() { - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `borderMaterial` VARCHAR(32) AFTER `floorMaterial`;"); - } catch (SQLException ignored) { - - } - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `members` TEXT AFTER `ownedBy`;"); - } catch (SQLException ignored) { - - } - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `created` DATETIME AFTER `createdLocation`;"); - } catch (SQLException ignored) { - - } - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `modified` DATETIME AFTER `created`;"); - } catch (SQLException ignored) { - - } - } - - public static Statement getStatement() { - try { - if (System.currentTimeMillis() - lastQuery > MYSQL_TIMEOUT_MS) { - connection.close(); - statement.close(); - connect(); - } else if(connection.isClosed()) { - connect(); - } - lastQuery = System.currentTimeMillis(); - } catch (SQLException e) { - e.printStackTrace(); - } - return statement; - } - - - public static void setConnection(Connection connection) { - SQL.connection = connection; - } - - public static void setStatement(Statement statement) { - SQL.statement = statement; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/ConfigurationFactory.java b/src/main/java/me/plytki/virtualrealty/utils/ConfigurationFactory.java deleted file mode 100644 index 675de8a..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/ConfigurationFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import eu.okaeri.configs.ConfigManager; -import eu.okaeri.configs.serdes.commons.SerdesCommons; -import eu.okaeri.configs.validator.okaeri.OkaeriValidator; -import eu.okaeri.configs.yaml.bukkit.YamlBukkitConfigurer; -import me.plytki.virtualrealty.configs.MessagesConfiguration; -import me.plytki.virtualrealty.configs.PluginConfiguration; -import me.plytki.virtualrealty.configs.SizesConfiguration; - -import java.io.File; - -public class ConfigurationFactory { - - public ConfigurationFactory() { - - } - - public PluginConfiguration createPluginConfiguration(File pluginConfigurationFile) { - return ConfigManager.create(PluginConfiguration.class, (it) -> { - it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); - it.withBindFile(pluginConfigurationFile); - it.saveDefaults(); - it.load(true); - }); - } - - public SizesConfiguration createSizesConfiguration(File sizesConfigurationFile) { - return ConfigManager.create(SizesConfiguration.class, (it) -> { - it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); - it.withBindFile(sizesConfigurationFile); - it.saveDefaults(); - it.load(true); - }); - } - - public MessagesConfiguration createMessagesConfiguration(File messagesConfigurationFile) { - return ConfigManager.create(MessagesConfiguration.class, (it) -> { - it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); - it.withBindFile(messagesConfigurationFile); - it.saveDefaults(); - it.load(true); - }); - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/Permissions.java b/src/main/java/me/plytki/virtualrealty/utils/Permissions.java deleted file mode 100644 index 833e82e..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/Permissions.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import me.plytki.virtualrealty.VirtualRealty; -import org.bukkit.command.CommandSender; -import org.bukkit.permissions.Permission; - -public class Permissions { - - public static boolean hasPermission(CommandSender sender, Permission basePermission, String permission) { - Permission finalPermission = new Permission(basePermission.getName() + "." + permission); - if (!sender.hasPermission(finalPermission)) { - sender.sendMessage(VirtualRealty.PREFIX + "§cInsufficient permissions! §8(§7" + finalPermission.getName() + "§8)"); - return false; - } - return true; - } - - public static boolean hasPermission(CommandSender sender, String permission) { - Permission finalPermission = new Permission(permission); - if (!sender.hasPermission(finalPermission)) { - sender.sendMessage(VirtualRealty.PREFIX + "§cInsufficient permissions! §8(§7" + finalPermission.getName() + "§8)"); - return false; - } - return true; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/PlotUtil.java b/src/main/java/me/plytki/virtualrealty/utils/PlotUtil.java deleted file mode 100644 index 3fd3a69..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/PlotUtil.java +++ /dev/null @@ -1,41 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import me.plytki.virtualrealty.enums.Direction; -import me.plytki.virtualrealty.objects.Cuboid; -import me.plytki.virtualrealty.objects.math.BlockVector3; -import org.bukkit.Location; - -public class PlotUtil { - - public static Cuboid getPlotRegion(Location location, Direction direction, int length, int width, int height) { - Location location1; - Location location2; - switch(direction) { - case SOUTH: { - location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); - location2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); - break; - } - case WEST: { - location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); - location2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); - break; - } - case NORTH: { - location1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); - location2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); - break; - } - case EAST: { - location1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); - location2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - return new Cuboid(BlockVector3.at(location1.getBlockX(), location1.getBlockY(), location1.getBlockZ()), - BlockVector3.at(location2.getBlockX(), location2.getBlockY(), location2.getBlockZ()), location.getWorld()); - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/ProtectionUtil.java b/src/main/java/me/plytki/virtualrealty/utils/ProtectionUtil.java deleted file mode 100644 index ea2208c..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/ProtectionUtil.java +++ /dev/null @@ -1,40 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Flag; -import me.plytki.virtualrealty.enums.Permission; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.time.LocalDateTime; - -public class ProtectionUtil { - - public static boolean canBuild(Player player, Location location) { - Plot plot = PlotManager.getBorderedPlot(location); - if (plot != null) { - if (plot.getOwnedBy() != null) { - if (!plot.getOwnedBy().equals(player.getUniqueId())) { - return false; - } else { - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - return false; - } - } - } else { - return false; - } - } - return true; - } - - public static boolean hasPermissionToWorld(Player player, Flag.World flag) { - if (player.hasPermission(Permission.WORLD_BUILD.getPermission())) return true; - if (player.hasPermission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".world." + flag.name().toLowerCase())) return true; - if (player.isOp()) return true; - return false; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/Reflections.java b/src/main/java/me/plytki/virtualrealty/utils/Reflections.java deleted file mode 100644 index 87a8916..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/Reflections.java +++ /dev/null @@ -1,271 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Entity; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public final class Reflections { - - public static final String SERVER_VERSION = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; - public static final boolean USE_PRE_13_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 13; - public static final boolean USE_PRE_12_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 12; - public static final boolean USE_PRE_9_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 9; - - private static final Map> CLASS_CACHE = new HashMap<>(); - private static final Map FIELD_CACHE = new HashMap<>(); - private static final Map> FIELD_ACCESSOR_CACHE = new HashMap<>(); - private static final Map METHOD_CACHE = new HashMap<>(); - private static final Class INVALID_CLASS = InvalidMarker.class; - private static final Method INVALID_METHOD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredMethod("invalidMethodMaker")); - private static final Field INVALID_FIELD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredField("invalidFieldMarker")); - private static final FieldAccessor INVALID_FIELD_ACCESSOR = getField(INVALID_CLASS, Void.class, 0); - - public static Class getClassOmitCache(String className) { - CLASS_CACHE.remove(className); - return getClass(className); - } - - public static Class getClass(String className) { - Class c = CLASS_CACHE.get(className); - - if (c != null) { - return c != INVALID_CLASS ? c : null; - } - - try { - c = Class.forName(className); - CLASS_CACHE.put(className, c); - } - catch (Exception ex) { - System.err.println("Could not retrieve class"); - - CLASS_CACHE.put(className, INVALID_CLASS); - } - return c; - } - - public static Class getNMSClass(String name) { - return getClass("net.minecraft.server." + SERVER_VERSION + "." + name); - } - - public static Class getCraftBukkitClass(String name) { - return getClass("org.bukkit.craftbukkit." + SERVER_VERSION + "." + name); - } - - public static Class getBukkitClass(String name) { - return getClass("org.bukkit." + name); - } - - public static Object getHandle(Entity entity) { - try { - return getMethod(entity.getClass(), "getHandle").invoke(entity); - } - catch (Exception ex) { - System.err.println("Could not get entity handle"); - return null; - } - } - - public static Object getHandle(World world) { - try { - return getMethod(world.getClass(), "getHandle").invoke(world); - } - catch (Exception ex) { - System.err.println("Could not get world handle"); - - return null; - } - } - - private static String constructFieldCacheKey(Class cl, String fieldName) { - return cl.getName() + "." + fieldName; - } - - public static Field getField(Class cl, String fieldName) { - String cacheKey = constructFieldCacheKey(cl, fieldName); - - Field field = FIELD_CACHE.get(cacheKey); - - if (field != null) { - return field != INVALID_FIELD ? field : null; - } - - try { - field = cl.getDeclaredField(fieldName); - FIELD_CACHE.put(cacheKey, field); - } - catch (Exception ex) { - System.err.println("Could not retrieve field"); - - FIELD_CACHE.put(cacheKey, INVALID_FIELD); - } - - return field; - } - - public static FieldAccessor getField(Class target, Class fieldType, int index) { - return getField(target, null, fieldType, index); - } - - @SuppressWarnings("unchecked") - private static FieldAccessor getField(Class target, String name, Class fieldType, int index) { - final String cacheKey = target.getName() + "." + (name != null ? name : "NONE") + "." + fieldType.getName() + "." + index; - - FieldAccessor output = (FieldAccessor) FIELD_ACCESSOR_CACHE.get(cacheKey); - - if (output != null) { - if (output == INVALID_FIELD_ACCESSOR) { - throw new IllegalArgumentException("Cannot find field with type " + fieldType); - } - - return output; - } - - for (final Field field : target.getDeclaredFields()) { - if ((name == null || field.getName().equals(name)) && fieldType.isAssignableFrom(field.getType()) && index-- <= 0) { - field.setAccessible(true); - - output = new FieldAccessor() { - - @Override - public T get(Object target) { - try { - return (T) field.get(target); - } catch (IllegalAccessException e) { - throw new RuntimeException("Cannot access reflection.", e); - } - } - - @Override - public void set(Object target, Object value) { - try { - field.set(target, value); - } catch (IllegalAccessException e) { - throw new RuntimeException("Cannot access reflection.", e); - } - } - - @Override - public boolean hasField(Object target) { - return field.getDeclaringClass().isAssignableFrom(target.getClass()); - } - }; - - break; - } - } - - if (output == null && target.getSuperclass() != null) { - output = getField(target.getSuperclass(), name, fieldType, index); - } - - FIELD_ACCESSOR_CACHE.put(cacheKey, output != null ? output : INVALID_FIELD_ACCESSOR); - - if (output == null) { - throw new IllegalArgumentException("Cannot find field with type " + fieldType); - } - - return output; - } - - public static Field getPrivateField(Class cl, String fieldName) { - String cacheKey = constructFieldCacheKey(cl, fieldName); - - Field c = FIELD_CACHE.get(cacheKey); - if (c != null) { - return c != INVALID_FIELD ? c : null; - } - - try { - c = cl.getDeclaredField(fieldName); - c.setAccessible(true); - FIELD_CACHE.put(cacheKey, c); - } - catch (Exception ex) { - System.err.println("Could not retrieve field"); - - FIELD_CACHE.put(cacheKey, INVALID_FIELD); - } - - return c; - } - - public static Method getMethod(Class cl, String method, Class... args) { - String cacheKey = cl.getName() + "." + method + "." + (args == null ? "NONE" : Arrays.toString(args)); - - Method output = METHOD_CACHE.get(cacheKey); - if (output != null) { - return output != INVALID_METHOD ? output : null; - } - - for (Method m : cl.getMethods()) { - if (m.getName().equals(method) && (args == null || classListEqual(args, m.getParameterTypes()))) { - output = m; - break; - } - } - - METHOD_CACHE.put(cacheKey, output == null ? INVALID_METHOD : output); - return output; - } - - public static Method getMethod(Class cl, String method) { - return getMethod(cl, method, null); - } - - public static Constructor getConstructor(Class clazz, Class... arguments) { - for (Constructor constructor : clazz.getDeclaredConstructors()) { - if (Arrays.equals(constructor.getParameterTypes(), arguments)) { - return constructor; - } - } - - return null; - } - - public static boolean classListEqual(Class[] l1, Class[] l2) { - if (l1.length != l2.length) { - return false; - } - - for (int i = 0; i < l1.length; i++) { - if (l1[i] != l2[i]) { - return false; - } - } - - return true; - } - - public interface ConstructorInvoker { - Object invoke(Object... arguments); - } - - public interface MethodInvoker { - Object invoke(Object target, Object... arguments); - } - - public interface FieldAccessor { - T get(Object target); - - void set(Object target, Object value); - - boolean hasField(Object target); - } - - private static class InvalidMarker { - public Void invalidFieldMarker; - public void invalidMethodMaker() {} - } - - private Reflections() {} - -} - diff --git a/src/main/java/me/plytki/virtualrealty/utils/SafeUtil.java b/src/main/java/me/plytki/virtualrealty/utils/SafeUtil.java deleted file mode 100644 index 61d809c..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/SafeUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.plytki.virtualrealty.utils; - -public class SafeUtil { - - private static void reportUnsafe(Throwable th) { - try { - throw new Exception(th.getMessage()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static T safeInit(SafeInitializer initializer) { - try { - return initializer.initialize(); - } catch (Exception e) { - reportUnsafe(e); - return null; - } - } - - @FunctionalInterface - public interface SafeInitializer { - T initialize() throws Exception; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java b/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java deleted file mode 100644 index b99ba70..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java +++ /dev/null @@ -1,154 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.utils.data.Data; -import me.plytki.virtualrealty.utils.multiversion.VMaterial; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; - -import java.io.*; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.zip.Deflater; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.InflaterInputStream; - -public class SchematicUtil { - - public static String[] getStructure(Block block, Block block2) { - long time = System.currentTimeMillis(); - int minX = Math.min(block.getX(), block2.getX()); - int minZ = Math.min(block.getZ(), block2.getZ()); - int minY = Math.min(block.getY(), block2.getY()); - int maxX = Math.max(block.getX(), block2.getX()); - int maxZ = Math.max(block.getZ(), block2.getZ()); - int maxY = Math.max(block.getY(), block2.getY()); - List blocks = new ArrayList<>(); - for (int x = minX; x <= maxX; ++x) { - for (int y = minY; y <= maxY; ++y) { - for (int z = minZ; z <= maxZ; ++z) { - Block b = block.getWorld().getBlockAt(x, y, z); - if (b.getType() != Material.AIR) { - if (VirtualRealty.isLegacy) { - blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getType().getId() + ";" + b.getData()); - } else { - blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getBlockData().getAsString().substring(10)); - } - } - } - } - } - VirtualRealty.debug("Getted and serialized blocks in: " + (System.currentTimeMillis() - time) + " ms"); - return blocks.toArray(new String[0]); - } - - public static void paste(int plotID, Location l) { - long time = System.currentTimeMillis(); - String[] blocks = load(plotID); - if (blocks == null) return; - Plot plot = PlotManager.getPlot(plotID); - Location location = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderBottomLeftCorner().getBlockX(), plot.getBorderBottomLeftCorner().getBlockY(), plot.getBorderBottomLeftCorner().getBlockZ()); - Location location2 = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderTopRightCorner().getBlockX(), plot.getBorderTopRightCorner().getBlockY(), plot.getBorderTopRightCorner().getBlockZ()); - Block pos1Block = location.getBlock(); - Block pos2Block = location2.getBlock(); - int minX = Math.min(pos1Block.getX(), pos2Block.getX()); - int minZ = Math.min(pos1Block.getZ(), pos2Block.getZ()); - int minY = Math.min(pos1Block.getY(), pos2Block.getY()); - int maxX = Math.max(pos1Block.getX(), pos2Block.getX()); - int maxZ = Math.max(pos1Block.getZ(), pos2Block.getZ()); - int maxY = Math.max(pos1Block.getY(), pos2Block.getY()); - for (int x = minX; x <= maxX; ++x) { - for (int y = minY; y <= maxY; ++y) { - for (int z = minZ; z <= maxZ; ++z) { - Block b = location.getWorld().getBlockAt(x, y, z); - b.setType(Material.AIR); - } - } - } - if (blocks[0].isEmpty()) return; - for (String block : blocks) { - String[] cords = block.split(";"); - int x = Integer.parseInt(cords[0]); - int y = Integer.parseInt(cords[1]); - int z = Integer.parseInt(cords[2]); - Location displaced = l.clone(); - displaced.add(x, y, z); - Block b = displaced.getBlock(); - if (VirtualRealty.isLegacy) { - try { - Method m = Block.class.getDeclaredMethod("setType", Material.class); - m.setAccessible(true); - m.invoke(b, VMaterial.getMaterial(Integer.parseInt(cords[3]))); - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(b, (byte) Integer.parseInt(cords[4])); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - BlockData blockData = Bukkit.createBlockData("minecraft:" + cords[3]); - b.setBlockData(blockData); - } - b.getState().update(true); - } - VirtualRealty.debug("Pasted in: " + (System.currentTimeMillis() - time) + " ms"); - } - - public static void save(int plotID, String[] blocks) { - long time = System.currentTimeMillis(); - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); - - StringBuilder stringBuilder = new StringBuilder(); - for (String s : blocks) { - stringBuilder.append(s).append("|"); - } - String plotString = stringBuilder.toString(); - if (plotString.isEmpty()) - plotString = "clear|"; - try { - new Data().compressData(plotString.substring(0, plotString.length() - 1).getBytes(StandardCharsets.UTF_8), f); - } catch (IOException e) { - e.printStackTrace(); - } - VirtualRealty.debug("Saved in: " + (System.currentTimeMillis() - time) + " ms"); - } - - public static String[] load(int plotID) { - long time = System.currentTimeMillis(); - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); - if (f.exists()) { - String loaded = null; - try { - loaded = new String(new Data().decompressData(f)); - } catch (IOException e) { - e.printStackTrace(); - } - if (loaded.equalsIgnoreCase("clear")) return new String[]{""}; - VirtualRealty.debug("Loaded in: " + (System.currentTimeMillis() - time) + " ms"); - return loaded.split("\\|"); - } - return null; - } - - public static List oldLoad(int plotID) { - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".schem"); - List loaded = new ArrayList<>(); - try { - FileInputStream streamIn = new FileInputStream(f); - ObjectInputStream objectinputstream = new ObjectInputStream(streamIn); - loaded = (List)objectinputstream.readObject(); - objectinputstream.close(); - } catch (Exception e) { - e.printStackTrace(); - } - return loaded; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/UUIDUtils.java b/src/main/java/me/plytki/virtualrealty/utils/UUIDUtils.java deleted file mode 100644 index ce40e3c..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/UUIDUtils.java +++ /dev/null @@ -1,16 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import java.util.UUID; - -public class UUIDUtils { - - public static boolean isValidUUID(String uuidString) { - try { - UUID.fromString(uuidString); - return true; - } catch (Exception e) { - return false; - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/UpdateChecker.java b/src/main/java/me/plytki/virtualrealty/utils/UpdateChecker.java deleted file mode 100644 index 34bd2e0..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/UpdateChecker.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import me.plytki.virtualrealty.VirtualRealty; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; - -public class UpdateChecker { - - private static final String VERSION_URL = "https://api.spiget.org/v2/resources/95599/versions/latest"; - private static final String DESCRIPTION_URL = "https://api.spiget.org/v2/resources/95599/updates/latest"; - - public static String[] getUpdate() { - try { - JsonObject latestVersionObj = getURLResults(VERSION_URL); - String newVersion = latestVersionObj.get("name").getAsString(); - JsonObject updateDesc = getURLResults(DESCRIPTION_URL); - String updateName = updateDesc.get("title").getAsString(); - return new String[] { newVersion, updateName }; - } catch (IOException ex) { - VirtualRealty.getInstance().getLogger().severe("Failed to get plugin update information, is Spiget down?"); - return null; - } - } - - private static JsonObject getURLResults(String urlStr) throws IOException { - URL url = new URL(urlStr); - HttpURLConnection connection = (HttpURLConnection)url.openConnection(); - connection.addRequestProperty("User-Agent", "AdvancedTeleportPA"); - return new JsonParser().parse(new InputStreamReader(connection.getInputStream())).getAsJsonObject(); - } - -} - - diff --git a/src/main/java/me/plytki/virtualrealty/utils/data/Data.java b/src/main/java/me/plytki/virtualrealty/utils/data/Data.java deleted file mode 100644 index 0ff5e38..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/data/Data.java +++ /dev/null @@ -1,31 +0,0 @@ -package me.plytki.virtualrealty.utils.data; - -import java.io.*; -import java.util.zip.*; - -public class Data { - - public void compressData(byte[] data, File file) throws IOException { - try (OutputStream outputStream = new FileOutputStream(file)) { - Deflater d = new Deflater(); - DeflaterOutputStream dout = new DeflaterOutputStream(outputStream, d); - dout.write(data); - dout.close(); - } - } - - public byte[] decompressData(File file) throws IOException { - try (InputStream inputStream = new FileInputStream(file)) { - InflaterInputStream newInput = new InflaterInputStream(inputStream); - ByteArrayOutputStream bout = new ByteArrayOutputStream(512); - int b; - while ((b = newInput.read()) != -1) { - bout.write(b); - } - newInput.close(); - bout.close(); - return bout.toByteArray(); - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java b/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java deleted file mode 100644 index c3c88bb..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.plytki.virtualrealty.utils.multiversion; - -import me.plytki.virtualrealty.VirtualRealty; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class Chat { - - private final BaseComponent text; - - public Chat(BaseComponent text) { - this.text = text; - } - - public Chat(String text) { - this.text = new TextComponent(text); - } - - public void sendTo(CommandSender sender) { - if (sender instanceof Player) { - Player player = (Player) sender; - if (VirtualRealty.isLegacy) { - try { - Method m = Player.class.getDeclaredMethod("sendMessage", BaseComponent.class); - m.setAccessible(true); - m.invoke(player, text); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } else { - player.spigot().sendMessage(text); - } - } else { - sender.sendMessage(text.toLegacyText()); - } - } - - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/multiversion/VMaterial.java b/src/main/java/me/plytki/virtualrealty/utils/multiversion/VMaterial.java deleted file mode 100644 index 3e651a4..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/multiversion/VMaterial.java +++ /dev/null @@ -1,60 +0,0 @@ -package me.plytki.virtualrealty.utils.multiversion; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.exceptions.MaterialMatchException; -import org.bukkit.Material; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class VMaterial { - - public static Material getMaterial(int materialID) throws MaterialMatchException { - if (VirtualRealty.isLegacy) { - try { - Method m = Material.class.getDeclaredMethod("getMaterial", int.class); - m.setAccessible(true); - return (Material) m.invoke(Material.class, materialID); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } else { - int counter = 1; - for (Material material : Material.values()) { - if (counter == materialID) { - return material; - } - counter++; - } - } - throw new MaterialMatchException("Couldn't parse material: " + materialID); - } - - public static Material catchMaterial(String material) throws MaterialMatchException { - try { - Method m = Material.class.getDeclaredMethod("getMaterial", String.class); - m.setAccessible(true); - Material mat = (Material) m.invoke(Material.class, material); - if (mat == null) { - throw new MaterialMatchException("Couldn't parse material: \"" + material + "\""); - } - return mat; - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } - - public static Material getMaterial(String material) { - try { - Method m = Material.class.getDeclaredMethod("getMaterial", String.class); - m.setAccessible(true); - return (Material) m.invoke(Material.class, material); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } - - -} From d3be26cc0ac3fae59df4d8e671ddbfe5c2a90dc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 27 Jan 2022 15:28:19 +0100 Subject: [PATCH 04/23] v1.8.0 --- virtualrealty.iml | 1 + 1 file changed, 1 insertion(+) diff --git a/virtualrealty.iml b/virtualrealty.iml index 84ca1fd..fa730ca 100644 --- a/virtualrealty.iml +++ b/virtualrealty.iml @@ -18,6 +18,7 @@ + From 1605c4494c025c689ef5bf6b4faf648e244d50ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 27 Jan 2022 15:11:03 +0100 Subject: [PATCH 05/23] Major changes to project structure --- VirtualRealty-Free.iml | 31 --- pom.xml | 395 +++++++++++++++++----------------- src/main/resources/plugin.yml | 2 +- 3 files changed, 204 insertions(+), 224 deletions(-) delete mode 100644 VirtualRealty-Free.iml diff --git a/VirtualRealty-Free.iml b/VirtualRealty-Free.iml deleted file mode 100644 index 88b5798..0000000 --- a/VirtualRealty-Free.iml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - PAPER - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index c8a3389..5153902 100644 --- a/pom.xml +++ b/pom.xml @@ -1,192 +1,203 @@ - - - 4.0.0 - - me.plytki - VirtualRealty - 1.7.1 - jar - - VirtualRealty - - A plot creation and management plugin for Minecraft - - 1.8 - UTF-8 - - - - - - maven-compiler-plugin - 3.8.1 - - ${java.version} - ${java.version} - - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.4 - - - package - - shade - - - false - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.1 - - - - org.bstats - me.plytki.virtualrealty.utils - - org.apache.commons.io - me.plytki.virtualrealty.utils - - - org.h2 - me.plytki.virtualrealty.utils.h2 - - - - - - package - - shade - - - - - *:* - - META-INF/** - - - - - - - - - - - src/main/resources - true - - - - - - - papermc-repo - https://papermc.io/repo/repository/maven-public/ - - - sonatype - https://oss.sonatype.org/content/groups/public/ - - - panda-repository - https://repo.panda-lang.org/ - - - okaeri-repo - https://storehouse.okaeri.eu/repository/maven-public/ - - - dynmap-repo - http://repo.mikeprimm.com/ - - - placeholderapi - http://repo.extendedclip.com/content/repositories/placeholderapi/ - - - - - - org.jetbrains - annotations - 21.0.1 - provided - - - org.spigot - spigot - 1.13.2 - provided - - - org.bukkit - craftbukkit - 1.13.2-R0.1-SNAPSHOT - provided - - - com.h2database - h2 - 1.4.200 - compile - - - org.bstats - bstats-bukkit - 2.2.1 - compile - - - eu.okaeri - okaeri-configs-yaml-bukkit - 3.1.0 - - - eu.okaeri - okaeri-configs-serdes-commons - 3.1.0 - - - eu.okaeri - okaeri-configs-validator-okaeri - 3.1.0 - - - commons-io - commons-io - 2.11.0 - compile - - - org.apache.commons - commons-lang3 - 3.12.0 - compile - - - org.dynmap - dynmap-api - 2.0 - provided - - - me.clip - placeholderapi - 2.10.9 - provided - - - - + + + 4.0.0 + + com.modnmetl + virtualrealty + 1.8.0 + jar + + A plot creation and management plugin for Minecraft + + + 1.8 + UTF-8 + + + + + build + + ../target + + + + + + + + maven-compiler-plugin + 3.8.1 + + ${java.version} + ${java.version} + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + package + + shade + + + false + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.1 + + + + org.bstats + com.modnmetl.virtualrealty.utils + + + org.apache.commons.io + com.modnmetl.virtualrealty.utils + + + + + + package + + shade + + + + + *:* + + META-INF/** + + + + + + + + + + + src/main/resources + true + + + + + + + papermc-repo + https://papermc.io/repo/repository/maven-public/ + + + sonatype + https://oss.sonatype.org/content/groups/public/ + + + panda-repository + https://repo.panda-lang.org/ + + + okaeri-repo + https://storehouse.okaeri.eu/repository/maven-public/ + + + dynmap-repo + http://repo.mikeprimm.com/ + + + placeholderapi + http://repo.extendedclip.com/content/repositories/placeholderapi/ + + + + + + org.jetbrains + annotations + 21.0.1 + provided + + + org.spigot + spigot + 1.13.2 + provided + + + org.bukkit + craftbukkit + 1.13.2-R0.1-SNAPSHOT + provided + + + + + + + + + org.bstats + bstats-bukkit + 2.2.1 + compile + + + eu.okaeri + okaeri-configs-yaml-bukkit + 3.1.0 + + + eu.okaeri + okaeri-configs-serdes-commons + 3.1.0 + + + eu.okaeri + okaeri-configs-validator-okaeri + 3.1.0 + + + commons-io + commons-io + 2.11.0 + compile + + + org.apache.commons + commons-lang3 + 3.12.0 + compile + + + org.dynmap + dynmap-api + 2.0 + provided + + + me.clip + placeholderapi + 2.10.9 + provided + + + com.modnmetl + virtualrealty-premium + ${project.version} + provided + + + + diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 5cb9b40..f7c37b5 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ name: VirtualRealty version: ${project.version} -main: me.plytki.virtualrealty.VirtualRealty +main: com.modnmetl.virtualrealty.VirtualRealty prefix: Virtual Realty authors: [ plytki ] api-version: 1.13 From 0b974cd4e2b79941aa9981e5f2a07d51c63b9066 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 27 Jan 2022 15:18:00 +0100 Subject: [PATCH 06/23] Major changes to project structure --- .../modnmetl/virtualrealty/VirtualRealty.java | 567 +++++++++++++ .../virtualrealty/commands/PlotCommand.java | 369 ++++++++ .../commands/VirtualRealtyCommand.java | 734 ++++++++++++++++ .../configs/MessagesConfiguration.java | 69 ++ .../configs/PluginConfiguration.java | 174 ++++ .../configs/SizesConfiguration.java | 86 ++ .../virtualrealty/enums/Direction.java | 45 + .../modnmetl/virtualrealty/enums/Flag.java | 33 + .../virtualrealty/enums/HighlightType.java | 9 + .../virtualrealty/enums/Permission.java | 24 + .../virtualrealty/enums/PlotSize.java | 86 ++ .../exceptions/MaterialMatchException.java | 9 + .../listeners/ProtectionListener.java | 472 +++++++++++ .../listeners/VirtualListener.java | 22 + .../listeners/plot/BorderListener.java | 44 + .../listeners/plot/PlotListener.java | 100 +++ .../listeners/world/WorldListener.java | 49 ++ .../virtualrealty/managers/PlotManager.java | 186 ++++ .../virtualrealty/objects/Cuboid.java | 187 ++++ .../modnmetl/virtualrealty/objects/Plot.java | 796 ++++++++++++++++++ .../objects/math/BlockVector2.java | 44 + .../objects/math/BlockVector3.java | 59 ++ .../registry/VirtualPlaceholders.java | 123 +++ .../com/modnmetl/virtualrealty/sql/SQL.java | 120 +++ .../utils/ConfigurationFactory.java | 46 + .../virtualrealty/utils/Permissions.java | 27 + .../virtualrealty/utils/PlotUtil.java | 41 + .../virtualrealty/utils/ProtectionUtil.java | 40 + .../virtualrealty/utils/Reflections.java | 271 ++++++ .../virtualrealty/utils/SafeUtil.java | 27 + .../virtualrealty/utils/SchematicUtil.java | 150 ++++ .../virtualrealty/utils/UUIDUtils.java | 16 + .../virtualrealty/utils/UpdateChecker.java | 39 + .../virtualrealty/utils/data/Data.java | 31 + .../utils/multiversion/Chat.java | 44 + .../utils/multiversion/VMaterial.java | 60 ++ virtualrealty.iml | 43 + 37 files changed, 5242 insertions(+) create mode 100644 src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/Direction.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/Flag.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/HighlightType.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/Permission.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/exceptions/MaterialMatchException.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/Plot.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector2.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/sql/SQL.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/Permissions.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/UUIDUtils.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/UpdateChecker.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java create mode 100644 virtualrealty.iml diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java new file mode 100644 index 0000000..c6a6618 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -0,0 +1,567 @@ +package com.modnmetl.virtualrealty; + +import com.modnmetl.virtualrealty.commands.PlotCommand; +import com.modnmetl.virtualrealty.commands.VirtualRealtyCommand; +import com.modnmetl.virtualrealty.configs.MessagesConfiguration; +import com.modnmetl.virtualrealty.configs.PluginConfiguration; +import com.modnmetl.virtualrealty.configs.SizesConfiguration; +import com.modnmetl.virtualrealty.enums.Flag; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.exceptions.MaterialMatchException; +import com.modnmetl.virtualrealty.listeners.plot.BorderListener; +import com.modnmetl.virtualrealty.listeners.plot.PlotListener; +import com.modnmetl.virtualrealty.listeners.world.WorldListener; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.premiumloader.PremiumLoader; +import com.modnmetl.virtualrealty.registry.VirtualPlaceholders; +import com.modnmetl.virtualrealty.sql.SQL; +import com.modnmetl.virtualrealty.utils.ConfigurationFactory; +import com.modnmetl.virtualrealty.utils.SchematicUtil; +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import com.modnmetl.virtualrealty.listeners.ProtectionListener; +import com.modnmetl.virtualrealty.utils.UpdateChecker; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.LineIterator; +import org.bstats.bukkit.Metrics; +import org.bstats.charts.AdvancedPie; +import org.bstats.charts.SimplePie; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.permissions.Permission; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; +import org.dynmap.DynmapAPI; +import org.dynmap.markers.MarkerIcon; +import org.dynmap.markers.MarkerSet; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.Statement; +import java.util.*; +import java.util.concurrent.Callable; + +public final class VirtualRealty extends JavaPlugin { + + public final Locale locale = Locale.getDefault(); + public final List availableLocales = new ArrayList<>(Arrays.asList(new Locale("en", "GB"), new Locale("es", "ES"), new Locale("pl", "PL"))); + + //CORE + private static VirtualRealty instance; + public static final String PREFIX = "§a§lVR §8§l» §7"; + public static ArrayList tasks = new ArrayList<>(); + private static final ArrayList preVersions = new ArrayList<>(); + public static boolean isLegacy = false; + public static final Permission GLOBAL_PERMISSION = new Permission("virtualrealty"); + + //FILES + public static File plotsFolder; + public static File plotsSchemaFolder; + public PluginConfiguration pluginConfiguration; + public SizesConfiguration sizesConfiguration; + public MessagesConfiguration messagesConfiguration; + private final File pluginConfigurationFile = new File(this.getDataFolder(), "config.yml"); + private final File sizesConfigurationFile = new File(this.getDataFolder(), "sizes.yml"); + private final File languagesDirectory = new File(this.getDataFolder(), "messages"); + + //DYNMAP API + public static boolean isDynmapPresent = false; + public static DynmapAPI dapi = null; + public static MarkerSet markerset = null; + public static MarkerIcon markerIcon = null; + + @Override + public void onEnable() { + instance = this; + if (checkLegacyVersions()) { + isLegacy = true; + } + String[] updateCheck = UpdateChecker.getUpdate(); + if (updateCheck != null) { + if (!updateCheck[0].equals(this.getDescription().getVersion())) { + this.getLogger().info("A newer version is available!"); + this.getLogger().info("The current version you use: " + this.getDescription().getVersion()); + this.getLogger().info("Latest version available: " + updateCheck[0]); + this.getLogger().info("Download link: https://www.spigotmc.org/resources/virtual-realty.95599/"); + } else { + this.getLogger().info("Plugin is up to date!"); + } + } + try { + checkConfig(); + checkSizesConfig(); + } catch (IOException e) { + e.printStackTrace(); + } + plotsFolder = new File(getInstance().getDataFolder().getAbsolutePath(), "plots"); + plotsFolder.mkdirs(); + plotsSchemaFolder = new File(plotsFolder.getAbsolutePath(), "primary-terrain"); + plotsSchemaFolder.mkdirs(); + spawnLocales(); + reformatConfig(); + reloadConfigs(); + if (!pluginConfiguration.licenseKey.isEmpty()) { + //LOAD premium + } + registerMetrics(); + loadSizesConfiguration(); + connectToDatabase(); + PlotManager.loadPlots(); + if (pluginConfiguration.dynmapMarkers) { + registerDynmap(); + } + reloadFlags(); + registerCommands(); + registerListeners(); + registerTasks(); + checkForOldSchemas(); + //convertOldDatabase(); + if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")){ + new VirtualPlaceholders(this).register(); + debug("Registered new placeholders"); + } + debug("Server version: " + this.getServer().getBukkitVersion() + " | " + this.getServer().getVersion()); + try { + Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader"); + new PremiumLoader(); + } catch (ClassNotFoundException ignored) { + + } + } + + @Override + public void onDisable() { + PlotManager.plots.forEach(Plot::update); + tasks.forEach(BukkitTask::cancel); + SQL.closeConnection(); + pluginConfiguration.save(); + } + + public static void debug(String debugMessage) { + if (VirtualRealty.getPluginConfiguration().debugMode) + VirtualRealty.getInstance().getLogger().warning("DEBUG-MODE > " + debugMessage); + } + + public void spawnLocales() { + for (Locale availableLocale : availableLocales) { + if (availableLocale.toString().equalsIgnoreCase("en_GB")) { + File messagesConfigurationFile = new File(languagesDirectory, "messages_en_GB.yml"); + ConfigurationFactory configFactory = new ConfigurationFactory(); + configFactory.createMessagesConfiguration(messagesConfigurationFile); + } else { + File languageConfigurationFile = new File(languagesDirectory, "messages_" + availableLocale + ".yml"); + if (!languageConfigurationFile.exists()) { + saveResource("messages_" + availableLocale + ".yml", true); + File file = new File(this.getDataFolder(), "messages_" + availableLocale + ".yml"); + try { + FileUtils.moveFile(file, languageConfigurationFile); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + +// public void convertOldDatabase() { +// File oldDatabase = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.mv.db"); +// if (oldDatabase.exists()) { +// try { +// SQL.closeConnection(); +// Connection connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.db"); +// SQL.setConnection(connection); +// Statement statement = connection.createStatement(); +// SQL.setStatement(statement); +// statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); +// for (Plot plot : PlotManager.plots) { +// plot.insert(); +// } +// FileUtils.deleteQuietly(oldDatabase); +// debug("H2 database converted successfully to SQLITE"); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// } + + public void reloadConfigs() { + try { + ConfigurationFactory configFactory = new ConfigurationFactory(); + pluginConfiguration = configFactory.createPluginConfiguration(pluginConfigurationFile); + File messagesConfigurationFile = new File(languagesDirectory, "messages_" + pluginConfiguration.locale + ".yml"); + sizesConfiguration = configFactory.createSizesConfiguration(sizesConfigurationFile); + messagesConfiguration = configFactory.createMessagesConfiguration(messagesConfigurationFile); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public void reloadFlags() { + if (pluginConfiguration.allowOutPlotBuild) { + for (Flag.World value : Flag.World.values()) { + value.setAllowed(true); + } + } else { + for (Flag.World value : Flag.World.values()) { + value.setAllowed(false); + } + } + } + + public static void checkForOldSchemas() { + for (Plot plot : PlotManager.plots) { + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plot.getID() + ".schem"); + if (f.exists()) { + List data = SchematicUtil.oldLoad(plot.getID()); + FileUtils.deleteQuietly(f); + SchematicUtil.save(plot.getID(), data.toArray(new String[0])); + debug("Converted Plot #" + plot.getID() + " | File: " + f.getName()); + } + } + } + + public void registerDynmap() { + new BukkitRunnable() { + @Override + public void run() { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); + if (plugin != null) { + isDynmapPresent = true; + } + if (plugin != null && plugin.isEnabled()) { + dapi = (DynmapAPI) plugin; + if (dapi.markerAPIInitialized()) { + markerset = dapi.getMarkerAPI().getMarkerSet("virtualrealty.plots"); + if (markerset == null) + markerset = dapi.getMarkerAPI().createMarkerSet("virutalrealty.plots", "Plots", dapi.getMarkerAPI().getMarkerIcons(), false); + for (MarkerSet markerSet : dapi.getMarkerAPI().getMarkerSets()) { + if (markerSet.getMarkerSetLabel().equalsIgnoreCase("Plots")) { + markerset = markerSet; + } + } + try { + if (dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon") == null) { + InputStream in = this.getClass().getResourceAsStream("/ploticon.png"); + if (in.available() > 0) { + markerIcon = dapi.getMarkerAPI().createMarkerIcon("virtualrealty_main_icon", "Plots", in); + } + } + else { + markerIcon = dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon"); + } + } + catch (IOException ex) {} + VirtualRealty.debug("Registering plots markers.."); + for (Plot plot : PlotManager.plots) { + PlotManager.resetPlotMarker(plot); + } + VirtualRealty.debug("Registered plots markers"); + this.cancel(); + } + } + } + }.runTaskTimer(this, 20, 20*5); + } + + + private void registerCommands() { + this.getCommand("plot").setExecutor(new PlotCommand()); + this.getCommand("virtualrealty").setExecutor(new VirtualRealtyCommand()); + } + + private void registerListeners() { + new BorderListener(this).registerEvents(); + new PlotListener(this).registerEvents(); + new ProtectionListener(this).registerEvents(); + new WorldListener(this).registerEvents(); + debug("Registered listeners"); + } + + private void registerTasks() { + //debug("Registered tasks"); + } + + private void registerMetrics() { + Metrics metrics = new Metrics(this, 14066); + metrics.addCustomChart(new SimplePie("used_database", () -> pluginConfiguration.dataModel.name())); + metrics.addCustomChart(new AdvancedPie("created_plots", new Callable>() { + @Override + public Map call() throws Exception { + Map valueMap = new HashMap(); + int smallPlots = 0; + int mediumPlots = 0; + int largePlots = 0; + int customPlots = 0; + for (Plot plot : PlotManager.plots) { + switch (plot.getPlotSize()) { + case SMALL: { + smallPlots++; + break; + } + case MEDIUM: { + mediumPlots++; + break; + } + case LARGE: { + largePlots++; + break; + } + case CUSTOM: { + customPlots++; + break; + } + default: + throw new IllegalStateException("Unexpected value: " + plot.getPlotSize()); + } + } + valueMap.put("SMALL", smallPlots); + valueMap.put("MEDIUM", mediumPlots); + valueMap.put("LARGE", largePlots); + valueMap.put("CUSTOM", customPlots); + return valueMap; + } + })); + debug("Registered metrics"); + } + + private void connectToDatabase() { + SQL.connect(); + SQL.createTables(); + debug("Connected to database"); + } + + public void loadSizesConfiguration() { + for (PlotSize plotSize : PlotSize.values()) { + if (plotSize == PlotSize.CUSTOM) return; + SizesConfiguration.PlotSizes.Size classSize = null; + switch (plotSize) { + case SMALL: { + classSize = sizesConfiguration.plotSizes.SMALL; + break; + } + case MEDIUM: { + classSize = sizesConfiguration.plotSizes.MEDIUM; + break; + } + case LARGE: { + classSize = sizesConfiguration.plotSizes.LARGE; + break; + } + } + Material floorMaterial; + try { + floorMaterial = VMaterial.catchMaterial(classSize.floorMaterial.toUpperCase()); + } catch (MaterialMatchException e) { + floorMaterial = VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK; + e.printStackTrace(); + //throw new MaterialMatchException("Couldn't parse floor-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK)); + } + Material borderMaterial; + try { + borderMaterial = VMaterial.catchMaterial(classSize.borderMaterial.toUpperCase()); + } catch (MaterialMatchException e) { + borderMaterial = VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB; + e.printStackTrace(); + //throw new MaterialMatchException("Couldn't parse border-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB)); + } + plotSize.setFloorMaterial(floorMaterial); + plotSize.setFloorData(classSize.floorData); + plotSize.setBorderMaterial(borderMaterial); + plotSize.setBorderData(classSize.borderData); + plotSize.setLength(classSize.length); + plotSize.setWidth(classSize.width); + plotSize.setHeight(classSize.height); + } + debug("Loaded sizes config"); + } + + public static VirtualRealty getInstance() { + return instance; + } + + public static PluginConfiguration getPluginConfiguration() { + return VirtualRealty.getInstance().pluginConfiguration; + } + + public static File getPluginConfigurationFile() { + return VirtualRealty.getInstance().pluginConfigurationFile; + } + + public static SizesConfiguration getSizesConfiguration() { + return VirtualRealty.getInstance().sizesConfiguration; + } + + public static File getSizesConfigurationFile() { + return VirtualRealty.getInstance().sizesConfigurationFile; + } + + public static MessagesConfiguration getMessages() { + return getInstance().messagesConfiguration; + } + + public boolean checkLegacyVersions() { + setPostVersions(); + for (String preVersion : preVersions) { + if (Bukkit.getBukkitVersion().toLowerCase().contains(preVersion.toLowerCase())) { + return true; + } + } + return false; + } + + public static Locale getLocale() { + return getInstance().locale; + } + + public void setPostVersions() { + preVersions.add("1.12"); + preVersions.add("1.11"); + preVersions.add("1.10"); + preVersions.add("1.9"); + preVersions.add("1.8"); + } + + public void reformatConfig() { + File configFile = new File(this.getDataFolder(), "config.yml"); + File newFile = new File(this.getDataFolder(), "config.yml.new"); + if (configFile.exists()) { + try { + List lines = FileUtils.readLines(configFile, StandardCharsets.UTF_8); + for (int i = 0; i < lines.size(); i++) { + if (lines.get(i).startsWith("force-plot-gamemode:")) { + lines.set(i, lines.get(i).replaceAll("force-plot-gamemode:", "lock-plot-gamemode:")); + } + } + FileUtils.writeLines(newFile, lines); + FileUtils.deleteQuietly(configFile); + newFile.createNewFile(); + File newConfigFile = new File(this.getDataFolder(), "config.yml"); + FileUtils.copyFile(newFile, newConfigFile); + FileUtils.deleteQuietly(newFile); + } catch (IOException e) { + + } + } + } + + public void checkConfig() throws IOException { + File oldConfigFile = new File(this.getDataFolder(), "config.yml"); + if (!oldConfigFile.exists()) return; + String version = null; + boolean isOldVersion = true; + boolean updateConfigVersion = false; + FileReader fileReader = new FileReader(this.pluginConfigurationFile); + BufferedReader reader = new BufferedReader(fileReader); + String latestLine; + while((latestLine = reader.readLine()) != null) { + if (latestLine.contains("config-version")) { + version = latestLine.replaceAll("config-version: ", ""); + isOldVersion = false; + } + } + fileReader.close(); + reader.close(); + if (version == null) { + System.err.println(" "); + this.getLogger().warning("Config has been reset due to major config changes!"); + this.getLogger().warning("Old config has been renamed to config.yml.old"); + this.getLogger().warning("Please update your config file!"); + System.err.println(" "); + } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { + updateConfigVersion = true; + this.getLogger().info("Config has been updated!"); + } + + // save old config file + if (isOldVersion) { + File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml.old"); + if (newConfigFile.exists()) { + newConfigFile.delete(); + } + FileUtils.copyFile(oldConfigFile, newConfigFile); + oldConfigFile.delete(); + } + +// update config version + if (updateConfigVersion) { + List lines = new ArrayList<>(); + LineIterator iterator = FileUtils.lineIterator(oldConfigFile); + while (iterator.hasNext()) { + String line = iterator.next(); + lines.add(line); + } + for (String line : new ArrayList<>(lines)) { + if (line.contains("config-version")) { + int index = lines.indexOf(line); + lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); + } + } + File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml"); + FileUtils.deleteQuietly(newConfigFile); + FileUtils.writeLines(newConfigFile, lines); + newConfigFile.createNewFile(); + } + } + + public void checkSizesConfig() throws IOException { + File oldConfigFile = new File(this.getDataFolder(), "sizes.yml"); + if (!oldConfigFile.exists()) return; + String version = null; + boolean isOldVersion = true; + boolean updateConfigVersion = false; + BufferedReader reader = new BufferedReader(new FileReader(this.sizesConfigurationFile)); + String latestLine; + while((latestLine = reader.readLine()) != null) { + if (latestLine.contains("config-version")) { + version = latestLine.replaceAll("config-version: ", ""); + isOldVersion = false; + } + } + reader.close(); + if (version == null) { + System.err.println(" "); + this.getLogger().warning("Config has been reset due to major config changes!"); + this.getLogger().warning("Old config has been renamed to sizes.yml.old"); + this.getLogger().warning("Please update your config file!"); + System.err.println(" "); + } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { + updateConfigVersion = true; + this.getLogger().info("Plot sizes config has been updated!"); + } + + // save old config file + if (isOldVersion) { + File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml.old"); + if (newConfigFile.exists()) { + newConfigFile.delete(); + } + FileUtils.copyFile(oldConfigFile, newConfigFile); + oldConfigFile.delete(); + } + + // update config version + if (updateConfigVersion) { + List lines = new ArrayList<>(); + LineIterator iterator = FileUtils.lineIterator(oldConfigFile); + while (iterator.hasNext()) { + String line = iterator.next(); + lines.add(line); + } + for (String line : new ArrayList<>(lines)) { + if (line.contains("config-version")) { + int index = lines.indexOf(line); + lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); + } + } + File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml"); + FileUtils.deleteQuietly(newConfigFile); + FileUtils.writeLines(newConfigFile, lines); + newConfigFile.createNewFile(); + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java new file mode 100644 index 0000000..ce69dfa --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java @@ -0,0 +1,369 @@ +package com.modnmetl.virtualrealty.commands; + +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Plot; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public class PlotCommand implements CommandExecutor { + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (!(sender instanceof Player)) { + return false; + } + Player p = ((Player) sender); + if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { + printHelp(sender); + return false; + } + if (args.length == 1) { + switch (args[0].toUpperCase()) { + case "ADD": { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot add §8<§7player§8> §8<§7plot§8>"); + break; + } + case "KICK": { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot kick §8<§7player§8> §8<§7plot§8>"); + break; + } + case "TP": { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot tp §8<§7plotID§8>"); + break; + } + case "GM": { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot gm §8<§7gamemode§8>"); + break; + } + case "INFO": { + Plot plot = PlotManager.getPlot(p.getLocation()); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); + return false; + } + printInfo(sender, plot); + break; + } + case "LIST": { + boolean hasPlot = false; + for (Plot plot : PlotManager.plots) { + if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()) && plot.getOwnedUntilDate().isAfter(LocalDateTime.now())) { + hasPlot = true; + break; + } + } + boolean isMember = false; + for (Plot plot : PlotManager.plots) { + if (plot.getMembers().contains(p.getUniqueId())) { + isMember = true; + break; + } + } + if (!hasPlot && !isMember) { + sender.sendMessage(VirtualRealty.PREFIX + "§cYou don't have any plots!"); + return false; + } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" "); + if (hasPlot) { + sender.sendMessage("§7§m "); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + for (Plot plot : PlotManager.plots) { + if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + StringBuilder ownedBy = new StringBuilder(); + ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); + boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); + for (int i = ownedBy.length(); i < 16; i++) { + ownedBy.append(" "); + } + StringBuilder size = new StringBuilder(plot.getPlotSize().name()); + for (int i = size.length(); i < 6; i++) { + size.append(" "); + } + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + sender.sendMessage(textComponent.toLegacyText()); + } + } + sender.sendMessage("§7§m "); + } + if (isMember) { + sender.sendMessage(" "); + sender.sendMessage("§7 §fMember of §8§l↴"); + sender.sendMessage(" "); + sender.sendMessage("§7§m "); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + for (Plot plot : PlotManager.plots) { + if (plot.getPlotOwner() != null && !plot.getPlotOwner().getUniqueId().equals(p.getUniqueId()) && plot.getMembers().contains(p.getUniqueId())) { + StringBuilder ownedBy = new StringBuilder(); + ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); + boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); + for (int i = ownedBy.length(); i < 16; i++) { + ownedBy.append(" "); + } + StringBuilder size = new StringBuilder(plot.getPlotSize().name()); + for (int i = size.length(); i < 6; i++) { + size.append(" "); + } + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + ownedBy + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + sender.sendMessage(textComponent.toLegacyText()); + } + } + sender.sendMessage("§7§m "); + } + break; + } + default: { + printHelp(sender); + } + } + } + if (args.length >= 2) { + switch (args[0].toUpperCase()) { + case "ADD": { + if (args.length == 3) { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[2]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); + return false; + } + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return false; + } + if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantAddYourself); + return false; + } + if (plot.getMembers().contains(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().alreadyInMembers); + return false; + } + plot.addMember(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerAdd.replaceAll("%player%", offlinePlayer.getName())); + return false; + } + break; + } + case "KICK": { + if (args.length == 3) { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[2]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); + return false; + } + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return false; + } + if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantKickYourself); + return false; + } + if (!plot.getMembers().contains(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notInMembers); + return false; + } + plot.removeMember(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerKick.replaceAll("%player%", offlinePlayer.getName())); + return false; + } + break; + } + case "TP": { + if (args.length == 2) { + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (!plot.hasPlotMembership(p)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); + return false; + } + if (plot.isOwnershipExpired()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return false; + } + Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); + loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); + p.teleport(loc); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); + } + break; + } + case "GM": { + if (VirtualRealty.getPluginConfiguration().lockPlotGameMode) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeFeatureDisabled); + return false; + } + GameMode gameMode; + int gameModeID; + try { + gameMode = GameMode.valueOf(args[1]); + gameModeID = gameMode.getValue(); + } catch (IllegalArgumentException e) { + try { + gameModeID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException ex) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().incorrectGamemode); + return false; + } + } + GameMode defaultGamemode = VirtualRealty.getInstance().getServer().getDefaultGameMode(); + GameMode configGamemode = VirtualRealty.getPluginConfiguration().getGameMode(); + if (!(gameModeID != configGamemode.getValue() && gameModeID != defaultGamemode.getValue())) { + gameMode = GameMode.getByValue(Integer.parseInt(args[1])); + } else { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeDisabled); + return false; + } + Plot plot = PlotManager.getBorderedPlot(p.getLocation()); + if (plot != null) { + if (!plot.hasPlotMembership(p)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); + } else { + if (plot.isOwnershipExpired()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } else { + if (p.getGameMode().equals(gameMode)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeAlreadySelected); + return false; + } + if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { + plot.setSelectedGameMode(gameMode); + } + p.setGameMode(gameMode); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeSwitched); + } + } + } else { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); + } + break; + } + default: { + printHelp(sender); + } + } + } + return false; + } + + private static void printHelp(CommandSender sender) { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/plot add §8- §7Adds a member"); + sender.sendMessage(" §a/plot kick §8- §7Kicks a member"); + sender.sendMessage(" §a/plot list §8- §7Shows your plots"); + sender.sendMessage(" §a/plot info §8- §7Shows plot info"); + sender.sendMessage(" §a/plot gm §8- §7Changes gamemode"); + sender.sendMessage(" §a/plot tp §8- §7Teleports to the plot"); + } + + private static void printInfo(CommandSender sender, Plot plot) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); +// String assignedBy = VirtualRealty.getMessages().notAssigned; +// if (plot.getAssignedBy() != null) { +// switch (plot.getAssignedBy().toUpperCase()) { +// case "CONSOLE": { +// assignedBy = VirtualRealty.getMessages().assignedByConsole; +// break; +// } +// case "SHOP_PURCHASE": { +// assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; +// break; +// } +// default: { +// OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); +// assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); +// } +// } +// } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); + sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); + if (plot.getMembers().size() != 0) { + sender.sendMessage(" §7Members §8§l↴"); + for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { + sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); + } + } + //sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); + sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); + sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); + sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); + sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); + sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); + //sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); + //sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); + //sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); + //sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); + //sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java new file mode 100644 index 0000000..ba2a7f6 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java @@ -0,0 +1,734 @@ +package com.modnmetl.virtualrealty.commands; + +import com.modnmetl.virtualrealty.enums.Direction; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.utils.Permissions; +import com.modnmetl.virtualrealty.utils.PlotUtil; +import com.modnmetl.virtualrealty.utils.UUIDUtils; +import com.modnmetl.virtualrealty.utils.multiversion.Chat; +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Plot; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.*; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permission; +import org.jetbrains.annotations.NotNull; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.UUID; + +public class VirtualRealtyCommand implements CommandExecutor { + + private static final Permission commandPermission = new Permission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".vrplot"); + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + Permission tempPermission = new Permission(commandPermission.getName()); + if (!Permissions.hasPermission(sender, tempPermission.getName())) return false; + Player p = null; + Location location = null; + if(sender instanceof Player) { + p = (Player)sender; + location = p.getLocation(); + location.add(0, -1, 0); + } + if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { + printHelp(sender); + return false; + } + if (args.length == 1) { + switch (args[0].toUpperCase()) { + case "CREATE": { + if (!Permissions.hasPermission(sender, tempPermission, "create")) return false; + if (sender instanceof Player) { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot create §8<§7small/medium/large§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); + sender.sendMessage(" §a/vrplot create §8<§7length§8> §8<§7width§8> §8<§7height§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); + } + break; + } + case "REMOVE": { + if (!Permissions.hasPermission(sender, tempPermission, "remove")) return false; + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot remove §8<§7plotID§8>"); + break; + } + case "SET": { + if (!Permissions.hasPermission(sender, tempPermission, "set")) return false; + printSetHelp(sender); + break; + } + case "ASSIGN": { + if (!Permissions.hasPermission(sender, tempPermission, "assign")) return false; + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot assign §8<§7plotID§8> §8<§7username§8>"); + break; + } + case "UNASSIGN": { + if (!Permissions.hasPermission(sender, tempPermission, "unassign")) return false; + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot unassign §8<§7plotID§8>"); + break; + } + case "INFO": { + if (!Permissions.hasPermission(sender, tempPermission, "info")) return false; + Plot plot = PlotManager.getPlot(p.getLocation()); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); + return false; + } + printInfo(sender, plot); + break; + } + case "LIST": { + if (!Permissions.hasPermission(sender, tempPermission, "list")) return false; + if (PlotManager.plots.isEmpty()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); + return false; + } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" "); + sender.sendMessage("§7§m "); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + for (Plot plot : PlotManager.plots) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + StringBuilder ownedBy = new StringBuilder(); + ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); + boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); + for (int i = ownedBy.length(); i < 16; i++) { + ownedBy.append(" "); + } + StringBuilder size = new StringBuilder(plot.getPlotSize().name()); + for (int i = size.length(); i < 6; i++) { + size.append(" "); + } + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + ownedBy.substring(0, 14) + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); + textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); + new Chat(textComponent).sendTo(sender); + } + sender.sendMessage("§7§m "); + break; + } + case "TP": { + if (!Permissions.hasPermission(sender, tempPermission, "tp")) return false; + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot tp §8<§7plotID§8>"); + break; + } + case "RELOAD": { + if (!Permissions.hasPermission(sender, tempPermission, "reload")) return false; + try { + VirtualRealty.getInstance().reloadConfigs(); + if (VirtualRealty.getPluginConfiguration().dynmapMarkers) { + if (VirtualRealty.markerset != null) { + VirtualRealty.markerset.deleteMarkerSet(); + } + VirtualRealty.getInstance().registerDynmap(); + for (Plot plot : PlotManager.plots) { + PlotManager.resetPlotMarker(plot); + } + } else { + if (VirtualRealty.markerset != null) { + VirtualRealty.markerset.deleteMarkerSet(); + } + } + PlotManager.loadPlots(); + VirtualRealty.getInstance().reloadFlags(); + VirtualRealty.getInstance().loadSizesConfiguration(); + } catch (Exception exception) { + exception.printStackTrace(); + } + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().reloadCompleted); + break; + } + default: { + printHelp(sender); + break; + } + } + } + if (args.length > 1) { + switch (args[0].toUpperCase()) { + case "CREATE": { + if (!Permissions.hasPermission(sender, commandPermission, "create")) return false; + if (sender instanceof Player) { + if (Arrays.stream(PlotSize.values()).anyMatch(plotSize -> plotSize.name().equalsIgnoreCase(args[1])) && !args[1].equalsIgnoreCase(PlotSize.CUSTOM.name())) { + PlotSize plotSize = null; + try { + plotSize = PlotSize.valueOf(args[1].toUpperCase()); + } catch (IllegalArgumentException ignored) { + } + if (plotSize != null) { + if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), plotSize.getLength(), plotSize.getWidth(), plotSize.getHeight()))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); + return false; + } else { + Material floorMaterial = null; + byte floorData = 0; + if (args.length >= 3) { + try { + floorMaterial = VMaterial.getMaterial(args[2].split(":")[0].toUpperCase()); + if (floorMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return false; + } + if (args[2].split(":").length == 2) { + floorData = Byte.parseByte(args[2].split(":")[1]); + } + } + Material borderMaterial = null; + byte borderData = 0; + if (args.length >= 4) { + try { + borderMaterial = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); + if (borderMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return false; + } + if (args[3].split(":").length == 2) { + borderData = Byte.parseByte(args[3].split(":")[1]); + } + } + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); + long timeStart = System.currentTimeMillis(); + Plot plot = PlotManager.createPlot(location, plotSize); + if (floorMaterial != null) { + plot.setFloorMaterial(floorMaterial, floorData); + } + if (borderMaterial != null) { + plot.setBorder(borderMaterial, borderData); + } + long timeEnd = System.currentTimeMillis(); + BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); + BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); + BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); + textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); + textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); + textComponent.addExtra(textComponent2); + textComponent.addExtra(textComponent3); + new Chat(textComponent).sendTo(p); + } + } else { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().sizeNotRecognised); + return false; + } + } else { + int length; + int width; + int height; + try { + length = Integer.parseInt(args[1]); + width = Integer.parseInt(args[2]); + height = Integer.parseInt(args[3]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + if (length > 500 || width > 500 || height > 500) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().LWHHardLimit); + return false; + } + if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), length, width, height))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); + return false; + } else { + Material floorMaterial = null; + byte floorData = 0; + if (args.length >= 5) { + try { + floorMaterial = VMaterial.getMaterial(args[4].split(":")[0].toUpperCase()); + if (floorMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return false; + } + if (args[4].split(":").length == 2) { + floorData = Byte.parseByte(args[4].split(":")[1]); + } + } + Material borderMaterial = null; + byte borderData = 0; + if (args.length >= 6) { + try { + borderMaterial = VMaterial.getMaterial(args[5].split(":")[0].toUpperCase()); + if (borderMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return false; + } + if (args[5].split(":").length == 2) { + borderData = Byte.parseByte(args[5].split(":")[1]); + } + } + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); + long timeStart = System.currentTimeMillis(); + Plot plot = PlotManager.createPlot(location, length, width, height); + if (floorMaterial != null) { + plot.setFloorMaterial(floorMaterial, floorData); + } + if (borderMaterial != null) { + plot.setBorder(borderMaterial, borderData); + } + long timeEnd = System.currentTimeMillis(); + BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); + BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); + BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); + textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); + textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); + textComponent.addExtra(textComponent2); + textComponent.addExtra(textComponent3); + new Chat(textComponent).sendTo(p); + } + } + } + break; + } + case "REMOVE": { + if (!Permissions.hasPermission(sender, commandPermission, "remove")) return false; + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + plot.remove(); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().removedPlot); + break; + } + case "SET": { + if (!Permissions.hasPermission(sender, commandPermission, "set")) return false; + if (args.length >= 3) { + switch (args[2].toUpperCase()) { + case "OWNEDBY": { + if (!Permissions.hasPermission(sender, commandPermission, "set.ownedby")) return false; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyUsername); + return false; + } + int plotID; + OfflinePlayer offlinePlayer; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + try { + if (UUIDUtils.isValidUUID(args[3])) { + offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[3])); + } else { + offlinePlayer = Bukkit.getOfflinePlayer(args[3]); + } + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + } catch (NullPointerException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (args.length >= 5) { + String dateFormat = args[4]; + String timeFormat; + int year; + int month; + int dayOfMonth; + int hour = 0; + int minute = 0; + LocalDateTime localDateTime; + try { + year = Integer.parseInt(dateFormat.split("/")[2]); + month = Integer.parseInt(dateFormat.split("/")[1]); + dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); + if (args.length >= 6) { + timeFormat = args[5]; + hour = Integer.parseInt(timeFormat.split(":")[0]); + minute = Integer.parseInt(timeFormat.split(":")[1]); + } + localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); + return false; + } + plot.setOwnedUntilDate(localDateTime); + } + if (sender instanceof RemoteConsoleCommandSender && args.length >= 7 && args[6].equalsIgnoreCase("assign")) { + plot.setAssignedBy("SHOP_PURCHASE"); + } + plot.setOwnedBy(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedTo.replaceAll("%assigned_to%", offlinePlayer.getName())); + plot.update(); + break; + } + case "FLOORMATERIAL": { + if (!Permissions.hasPermission(sender, commandPermission, "set.floormaterial")) return false; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Material material; + try { + material = Material.matchMaterial(args[3].split(":")[0].toUpperCase()); + if (material == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + byte data = 0; + if (args[3].split(":").length == 2) { + data = Byte.parseByte(args[3].split(":")[1]); + } + plot.setFloorMaterial(material, data); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newFloorMaterialSet); + plot.update(); + break; + } + case "BORDERMATERIAL": { + if (!Permissions.hasPermission(sender, commandPermission, "set.bordermaterial")) + return false; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Material material; + try { + material = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); + if (material == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return false; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + byte data = 0; + if (args[3].split(":").length == 2) { + data = Byte.parseByte(args[3].split(":")[1]); + } + plot.setBorder(material, data); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newBorderMaterialSet); + plot.update(); + return false; + } + case "OWNERSHIPEXPIRES": { + if (!Permissions.hasPermission(sender, commandPermission, "set.ownerexpires")) return false; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyExpiryDate); + return false; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + String dateFormat = args[3]; + String timeFormat; + int year; + int month; + int dayOfMonth; + int hour = 0; + int minute = 0; + LocalDateTime localDateTime; + try { + year = Integer.parseInt(dateFormat.split("/")[2]); + month = Integer.parseInt(dateFormat.split("/")[1]); + dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); + if (args.length == 5) { + timeFormat = args[4]; + hour = Integer.parseInt(timeFormat.split(":")[0]); + minute = Integer.parseInt(timeFormat.split(":")[1]); + } + localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + plot.setOwnedUntilDate(localDateTime); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownedUntilUpdated); + plot.update(); + break; + } + default: { + printSetHelp(sender); + break; + } + } + } else { + printSetHelp(sender); + } + break; + } + case "ASSIGN": { + if (!Permissions.hasPermission(sender, commandPermission, "assign")) return false; + if (args.length == 3) { + int plotID; + OfflinePlayer offlinePlayer; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + try { + if (UUIDUtils.isValidUUID(args[2])) { + offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[2])); + } else { + offlinePlayer = Bukkit.getOfflinePlayer(args[2]); + } + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + } catch (NullPointerException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + if (sender instanceof Player) { + plot.setAssignedBy(p.getUniqueId().toString()); + } else if (sender instanceof ConsoleCommandSender){ + plot.setAssignedBy("CONSOLE"); + } else { + plot.setAssignedBy("SHOP_PURCHASE"); + } + plot.setOwnedBy(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedToBy.replaceAll("%assigned_to%", offlinePlayer.getName()).replaceAll("%assigned_by%", sender.getName())); + plot.update(); + } + break; + } + case "UNASSIGN": { + if (!Permissions.hasPermission(sender, commandPermission, "unassign")) return false; + if (args.length == 2) { + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + plot.setAssignedBy(null); + plot.setOwnedBy(null); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().unassigned); + plot.update(); + } + break; + } + case "INFO": { + if (!Permissions.hasPermission(sender, commandPermission, "info")) return false; + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + if (PlotManager.plots.isEmpty()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); + return false; + } + if (plotID < PlotManager.getPlotMinID()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().minPlotID.replaceAll("%min_id%", String.valueOf(PlotManager.getPlotMinID()))); + return false; + } + if (plotID > PlotManager.getPlotMaxID()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().maxPlotID.replaceAll("%max_id%", String.valueOf(PlotManager.getPlotMaxID()))); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + printInfo(sender, plot); + break; + } + case "TP": { + if (!Permissions.hasPermission(sender, commandPermission, "tp")) return false; + if (!(sender instanceof Player)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cmdOnlyPlayers); + return false; + } + if (args.length == 2) { + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return false; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return false; + } + Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); + loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); + p.teleport(loc); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); + } + break; + } + default: { + printHelp(sender); + break; + } + } + } + return false; + } + + private static void printInfo(CommandSender sender, Plot plot) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); + String assignedBy = VirtualRealty.getMessages().notAssigned; + if (plot.getAssignedBy() != null) { + switch (plot.getAssignedBy().toUpperCase()) { + case "CONSOLE": { + assignedBy = VirtualRealty.getMessages().assignedByConsole; + break; + } + case "SHOP_PURCHASE": { + assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; + break; + } + default: { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); + assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); + } + } + } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); + sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); + if (plot.getMembers().size() != 0) { + sender.sendMessage(" §7Members §8§l↴"); + for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { + sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); + } + } + sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); + sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); + sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); + sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); + sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); + sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); + sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); + sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); + sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); + sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); + sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); + } + + private static void printHelp(CommandSender sender) { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot create §8- §7Creates a plot"); + sender.sendMessage(" §a/vrplot remove §8- §7Removes a plot"); + sender.sendMessage(" §a/vrplot set §8- §7Sets a variable for the plot"); + sender.sendMessage(" §a/vrplot assign §8- §7Assigns a plot to player"); + sender.sendMessage(" §a/vrplot unassign §8- §7Sets assigned to and assigned by to null"); + sender.sendMessage(" §a/vrplot info §8- §7Prints info about plot"); + sender.sendMessage(" §a/vrplot list §8- §7Prints all plots"); + sender.sendMessage(" §a/vrplot tp §8- §7Teleports to the plot"); + sender.sendMessage(" §a/vrplot reload §8- §7Reloads plugin"); + } + + private static void printSetHelp(CommandSender sender) { + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownedBy §8<§7username§8>"); + sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7floorMaterial §8<§7material§8>"); + sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7borderMaterial §8<§7material§8>"); + sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownershipExpires §8<§7dd/mm/YYYY§8> §8<§7HH:mm (optional)§8>"); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java new file mode 100644 index 0000000..cd379df --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java @@ -0,0 +1,69 @@ +package com.modnmetl.virtualrealty.configs; + +import eu.okaeri.configs.OkaeriConfig; + +public class MessagesConfiguration extends OkaeriConfig { + + public String useNaturalNumbersOnly = "§cUse only natural numbers!"; + public String noPlotFound = "§cCouldn't get plot with specified ID!"; + public String notYourPlot = "§cIt's not your plot!"; + public String ownershipExpired = "§cYour ownership has expired!"; + public String teleportedToPlot = "§aYou have been teleported to the plot!"; + public String gamemodeFeatureDisabled = "§cGamemode feature is disabled!"; + public String incorrectGamemode = "§cIncorrect gamemode value!"; + public String gamemodeDisabled = "§cThis gamemode is disabled!"; + public String cantSwitchGamemode = "§cYou can't switch gamemode here!"; + public String notStandingOnPlot = "§cYou aren't standing on any plot!"; + public String assignedByConsole = "§eConsole"; + public String assignedByShopPurchase = "§eShop Purchase"; + public String noPlots = "§cThere are no plots!"; + public String available = "§cAvailable"; + public String reloadCompleted = "§aReload completed!"; + public String cantCreateOnExisting = "§cYou can't create new plot over an existing plot!"; + public String cantGetFloorMaterial = "§cCouldn't get floor material with specified name!"; + public String cantGetBorderMaterial = "§cCouldn't get border material with specified name!"; + public String cantGetMaterial = "§cCouldn't get material with specified name!"; + public String notCollidingCreating = "§aNot colliding. Creating plot.."; + public String clickToShowDetailedInfo = "§a§oClick to show detailed information about the plot! §8(§7ID: §f%plot_id%§8)"; + public String sizeNotRecognised = "§cSize not recognized!"; + public String LWHHardLimit = "§cL, W and H hard-limit is 500!"; + public String removedPlot = "§aSuccessfully removed plot!"; + public String specifyUsername = "§cSpecify username!"; + public String playerNotFoundWithUsername = "§cCouldn't find player with specified username!"; + public String invalidDateProvided = "§cInvalid date format provided!"; + public String assignedTo = "§aPlot has been assigned to §f%assigned_to%!"; + public String specifyMaterialName = "§cSpecify material name!"; + public String specifyExpiryDate = "§cSpecify expiry date!"; + public String newFloorMaterialSet = "§aNew floor material has been set!"; + public String newBorderMaterialSet = "§aNew border material has been set!"; + public String ownedUntilUpdated = "§aOwned until date has been updated!"; + public String assignedToBy = "§aPlot has been assigned to §f%assigned_to% §aby §f%assigned_by%!"; + public String notAssigned = "§cNot assigned"; + public String unassigned = "§aPlot has been unassigned!"; + public String minPlotID = "§cMinimum plot ID is %min_id%!"; + public String maxPlotID = "§cMaximum plot ID is %max_id%!"; + public String cmdOnlyPlayers = "§cCommand only for players!"; + + public String enteredAvailablePlot = "§2You have entered an available plot!"; + public String enteredOwnedPlot = "§7You have entered §2%owner%'s §7plot!"; + public String leftAvailablePlot = "§cYou have left an available plot!"; + public String leftOwnedPlot = "§7You have left §2%owner%'s §7plot!"; + public String cantInteract = "§cYou can't interact here!"; + public String cantBuildHere = "§cYou can't build here!"; + public String cantRideOnPlot = "§cYou can't ride on someones plot!"; + + public String creationPlotComponent1 = "§aPlot "; + public String creationPlotComponent2 = "§8#§7%plot_id%"; + public String creationPlotComponent3 = " §acreated! §8(§7%creation_time% ms§8)"; + + public String cantAddYourself = "§cYou can't add yourself to the plot!"; + public String cantKickYourself = "§cYou can't kick yourself from the plot!"; + public String alreadyInMembers = "§cThis player is already one of the plot members!"; + public String notInMembers = "§cThis player is not one of the plot members!"; + public String cantDoAnyDMG = "§cYou can't do any damage here!"; + public String playerKick = "§aPlayer §7%player% §ahas been kicked out of your plot!"; + public String playerAdd = "§aPlayer §7%player% §ahas been added to your plot!"; + public String gamemodeSwitched = "§aYour gamemode has changed!"; + public String gamemodeAlreadySelected = "§cThis gamemode is already selected!"; + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java new file mode 100644 index 0000000..639ff56 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java @@ -0,0 +1,174 @@ +package com.modnmetl.virtualrealty.configs; + +import com.modnmetl.virtualrealty.enums.HighlightType; +import eu.okaeri.configs.OkaeriConfig; +import eu.okaeri.configs.annotation.*; +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.GameMode; + +@Header("################################################################") +@Header("# #") +@Header("# Virtual Realty #") +@Header("# #") +@Header("################################################################") +@Names(strategy = NameStrategy.IDENTITY, modifier = NameModifier.TO_LOWER_CASE) +public class PluginConfiguration extends OkaeriConfig { + + @Comment(" ") + @Comment("-------------------------") + @Comment("Don't change this value!") + @CustomKey("config-version") + public String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); + + @Comment("-------------------------") + @Comment("Debug mode (Dev only)") + @CustomKey("debug-mode") + public boolean debugMode = false; + + @CustomKey("LICENSE-KEY") + public String licenseKey = ""; + + @Comment("Set player gamemode to change when they enter their plot") + @CustomKey("enable-plot-gamemode") + public boolean enablePlotGameMode = false; + + @Comment("Set your wanted language (locale)") + public String locale = VirtualRealty.getInstance().availableLocales.contains(VirtualRealty.getLocale()) ? VirtualRealty.getLocale().toString() : "en_GB"; + + @Comment("Set which gamemode players change to when they enter their plot") + @CustomKey("default-plot-gamemode") + public String plotGameMode = "SURVIVAL"; + + @Comment("Lock gamemode to plot default when player enters their plot (disables '/plot gm' command)") + @CustomKey("lock-plot-gamemode") + public boolean lockPlotGameMode = false; + + public GameMode getGameMode() { + try { + return GameMode.valueOf(plotGameMode); + } catch (Exception e) { + VirtualRealty.getInstance().getLogger().warning("Couldn't parse plot-gamemode from config.yml\nUsing default: SURVIVAL"); + return GameMode.SURVIVAL; + } + } + + @Comment("Allow players to build outside of their plots") + @CustomKey("allow-outplot-build") + public boolean allowOutPlotBuild = true; + + @Comment("Enables dynmap plots highlighting") + @CustomKey("enable-dynmap-markers") + public boolean dynmapMarkers = false; + + @Comment("Choose which type of plots should be highlighted on Dynmap page | Choose from: { ALL, AVAILABLE, OWNED }") + @CustomKey("dynmap-type") + public HighlightType dynmapType = HighlightType.ALL; + + @CustomKey("dynmap-markers") + public MarkerColor dynmapMarkersColor = new MarkerColor(new MarkerColor.Available("#80eb34", .3), new MarkerColor.Owned("#ffbf00", .45)); + + @Names(strategy = NameStrategy.IDENTITY) + public static class MarkerColor extends OkaeriConfig { + + public Available available; + + public Owned owned; + + public MarkerColor(Available available, Owned owned) { + this.available = available; + this.owned = owned; + } + + @Names(strategy = NameStrategy.IDENTITY) + public static class Available extends OkaeriConfig { + + public String color; + + public double opacity; + + public Available(String color, double opacity) { + this.color = color; + this.opacity = opacity; + } + + public int getHexColor() { + return Integer.decode("0x" + color.replaceAll("#", "")); + } + + } + + @Names(strategy = NameStrategy.IDENTITY) + public static class Owned extends OkaeriConfig { + + public String color; + + public double opacity; + + public Owned(String color, double opacity) { + this.color = color; + this.opacity = opacity; + } + + public int getHexColor() { + return Integer.decode("0x" + color.replaceAll("#", "")); + } + + } + + } + + @Comment("Enables plots enter/leave sounds") + @CustomKey("plot-sounds") + public boolean plotSound = true; + + @Comment("Type of data recording") + @Comment("SQLITE - Local database") + @Comment("MYSQL - External database") + @CustomKey("data-model") + public DataModel dataModel = DataModel.SQLITE; + + @Comment("Data required to connect to the database") + @Comment("The plotsTableName section is the name of the VR data table in the database") + @Comment("It is best to change these names only if you really need to (e.g. there is a conflict with another plugin)") + @Comment("To rename tables when you already have some VR data in the database:") + @Comment("1. Turn off the server") + @Comment("2. Change data in VR config") + @Comment("3. Rename database tables using phpMyAdmin for example") + @CustomKey("mysql") + public MySQL mysql = new MySQL("localhost", 3306, "db", "root", "passwd", true, "vr_plots"); + + public enum DataModel { + SQLITE, + MYSQL + } + + @Names(strategy = NameStrategy.IDENTITY) + public static class MySQL extends OkaeriConfig { + + @Variable("VR_MYSQL_HOSTNAME") + public String hostname; + @Variable("VR_MYSQL_PORT") + public int port; + @Variable("VR_MYSQL_DATABASE") + public String database; + @Variable("VR_MYSQL_USER") + public String user; + @Variable("VR_MYSQL_PASSWORD") + public String password; + @Variable("VR_MYSQL_USE_SSL") + public boolean useSSL; + @Variable("VR_MYSQL_USERS_TABLE_NAME") + public String plotsTableName; + + public MySQL(String hostname, int port, String database, String user, String password, boolean useSSL, String plotsTableName) { + this.hostname = hostname; + this.port = port; + this.database = database; + this.user = user; + this.password = password; + this.useSSL = useSSL; + this.plotsTableName = plotsTableName; + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java new file mode 100644 index 0000000..a09ca11 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java @@ -0,0 +1,86 @@ +package com.modnmetl.virtualrealty.configs; + +import eu.okaeri.configs.OkaeriConfig; +import eu.okaeri.configs.annotation.*; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.PlotSize; + +@Header("################################################################") +@Header("# #") +@Header("# Plot Sizes #") +@Header("# #") +@Header("################################################################") +public class SizesConfiguration extends OkaeriConfig { + + @Comment(" ") + @Comment("-------------------------") + @Comment("Don't change this value!") + @CustomKey("config-version") + public final String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); + @Comment("-------------------------") + + @Comment(" ") + @Comment("(<1.13) Legacy Materials: https://helpch.at/docs/1.8/org/bukkit/Material.html") + @Comment("(>1.12) Post-Legacy Materials: https://helpch.at/docs/1.13/org/bukkit/Material.html") + @Comment(" ") + @Comment("floor-data and border-data are only for legacy versions * <1.13 *") + @CustomKey("plot-sizes") + public PlotSizes plotSizes = new PlotSizes(); + + @Names(strategy = NameStrategy.IDENTITY) + public static class PlotSizes extends OkaeriConfig { + + @Variable("VR_SIZE_SMALL") + public Size SMALL = new Size(PlotSize.SMALL); + @Variable("VR_SIZE_MEDIUM") + public Size MEDIUM = new Size(PlotSize.MEDIUM); + @Variable("VR_SIZE_LARGE") + public Size LARGE = new Size(PlotSize.LARGE); + + public PlotSizes() { + } + + public PlotSizes(Size small, Size medium, Size large) { + this.SMALL = small; + this.MEDIUM = medium; + this.LARGE = large; + } + + public static class Size extends OkaeriConfig { + + @Variable("VR_SIZE_FLOORMATERIAL") + @CustomKey("floor-material") + public String floorMaterial; + @Variable("VR_SIZE_FLOORDATA") + @CustomKey("floor-data") + public byte floorData; + @Variable("VR_SIZE_BORDERMATERIAL") + @CustomKey("border-material") + public String borderMaterial; + @Variable("VR_SIZE_BORDERDATA") + @CustomKey("border-data") + public byte borderData; + @Variable("VR_SIZE_LENGTH") + public int length; + @Variable("VR_SIZE_WIDTH") + public int width; + @Variable("VR_SIZE_HEIGHT") + public int height; + + public Size() { + } + + public Size(PlotSize plotSize) { + this.floorMaterial = plotSize.getFloorMaterial().name(); + this.floorData = plotSize.getFloorData(); + this.borderMaterial = plotSize.getBorderMaterial().name(); + this.borderData = plotSize.getBorderData(); + this.length = plotSize.getLength(); + this.width = plotSize.getWidth(); + this.height = plotSize.getHeight(); + } + + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/Direction.java b/src/main/java/com/modnmetl/virtualrealty/enums/Direction.java new file mode 100644 index 0000000..772a253 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/Direction.java @@ -0,0 +1,45 @@ +package com.modnmetl.virtualrealty.enums; + +public enum Direction { + + SOUTH(315, 45), + WEST(45, 135), + NORTH(135, 225), + EAST(225, 315); + + private final float minYaw; + private final float maxYaw; + + Direction(float minYaw, float maxYaw) { + this.minYaw = minYaw; + this.maxYaw = maxYaw; + } + + public static Direction byYaw(float yaw) { + float absoluteYaw = Math.abs(yaw); + Direction direction = null; + if(absoluteYaw > 315 || absoluteYaw <= 45) { + //south + direction = SOUTH; + } else if(absoluteYaw > 45 && absoluteYaw <= 135) { + //west + direction = yaw > 0 ? WEST : EAST; + } else if(absoluteYaw > 135 && absoluteYaw <= 225) { + //north + direction = NORTH; + } else if(absoluteYaw > 225 && absoluteYaw <= 315) { + //east + direction = yaw > 0 ? EAST : WEST; + } + return direction; + } + + public float getMaxYaw() { + return maxYaw; + } + + public float getMinYaw() { + return minYaw; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/Flag.java b/src/main/java/com/modnmetl/virtualrealty/enums/Flag.java new file mode 100644 index 0000000..54e1a73 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/Flag.java @@ -0,0 +1,33 @@ +package com.modnmetl.virtualrealty.enums; + +public class Flag { + + public enum World { + + BLOCK_PLACE(false), + BLOCK_BREAK(false), + INTERACT(false), + IGNITE(false), + EXPLOSION_PRIME(false), + ENTITY_DAMAGE(false), + ARMOR_STAND_MANIPULATION(false), + ITEM_FRAME_DESTROY(false), + ITEM_FRAME_ROTATE(false); + + private boolean allowed; + + World(boolean allowed) { + this.allowed = allowed; + } + + public boolean isAllowed() { + return allowed; + } + + public void setAllowed(boolean allowed) { + this.allowed = allowed; + } + + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/HighlightType.java b/src/main/java/com/modnmetl/virtualrealty/enums/HighlightType.java new file mode 100644 index 0000000..d9e3bb9 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/HighlightType.java @@ -0,0 +1,9 @@ +package com.modnmetl.virtualrealty.enums; + +public enum HighlightType { + + ALL, + AVAILABLE, + OWNED + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/Permission.java b/src/main/java/com/modnmetl/virtualrealty/enums/Permission.java new file mode 100644 index 0000000..e84f66c --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/Permission.java @@ -0,0 +1,24 @@ +package com.modnmetl.virtualrealty.enums; + +public enum Permission { + + WORLD_BUILD("virtualrealty.build.world"), + PLOT_BUILD("virtualrealty.build.plot"), + BORDER_BUILD("virtualrealty.build.border"); + + private final String permission; + + Permission(String permission) { + this.permission = permission; + } + + public String getPermission() { + return permission; + } + + @Override + public String toString() { + return permission; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java b/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java new file mode 100644 index 0000000..4abf429 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java @@ -0,0 +1,86 @@ +package com.modnmetl.virtualrealty.enums; + +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.Material; + +public enum PlotSize { + + SMALL(10, 10, 10, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), + MEDIUM(25, 25, 25, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), + LARGE(50, 50, 50, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), + CUSTOM(0, 0, 0, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0); + + private int length; + private int width; + private int height; + private Material floorMaterial; + private byte floorData; + private Material borderMaterial; + private byte borderData; + + PlotSize(int length, int width, int height, Material floorMaterial, byte floorData, Material borderMaterial, byte borderData) { + this.length = length; + this.width = width; + this.height = height; + this.floorMaterial = floorMaterial; + this.floorData = floorData; + this.borderMaterial = borderMaterial; + this.borderData = borderData; + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + public Material getFloorMaterial() { + return floorMaterial; + } + + public void setFloorMaterial(Material floorMaterial) { + this.floorMaterial = floorMaterial; + } + + public byte getFloorData() { + return floorData; + } + + public void setFloorData(byte floorData) { + this.floorData = floorData; + } + + public Material getBorderMaterial() { + return borderMaterial; + } + + public void setBorderMaterial(Material borderMaterial) { + this.borderMaterial = borderMaterial; + } + + public byte getBorderData() { + return borderData; + } + + public void setBorderData(byte borderData) { + this.borderData = borderData; + } +} diff --git a/src/main/java/com/modnmetl/virtualrealty/exceptions/MaterialMatchException.java b/src/main/java/com/modnmetl/virtualrealty/exceptions/MaterialMatchException.java new file mode 100644 index 0000000..a95b1cb --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/exceptions/MaterialMatchException.java @@ -0,0 +1,9 @@ +package com.modnmetl.virtualrealty.exceptions; + +public class MaterialMatchException extends Exception { + + public MaterialMatchException(String exception) { + super(exception); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java new file mode 100644 index 0000000..79660f9 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java @@ -0,0 +1,472 @@ +package com.modnmetl.virtualrealty.listeners; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.Flag; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.ProtectionUtil; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.*; +import org.bukkit.event.hanging.HangingBreakByEntityEvent; +import org.bukkit.event.player.PlayerArmorStandManipulateEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.world.StructureGrowEvent; +import org.bukkit.util.Vector; + +import java.time.LocalDateTime; + +public class ProtectionListener extends VirtualListener { + + public ProtectionListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onBlockInteract(PlayerInteractEvent e) { + Player player = e.getPlayer(); + if (e.getClickedBlock() != null && (e.getAction() == Action.RIGHT_CLICK_BLOCK || (e.getAction() == Action.LEFT_CLICK_BLOCK && (!VirtualRealty.isLegacy && e.getClickedBlock().getType().isInteractable())))) { + Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { + if (!Flag.World.BLOCK_PLACE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent e) { + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlockPlaced().getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { + if (!Flag.World.BLOCK_PLACE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + + @EventHandler + public void onBlockBreak(BlockBreakEvent e) { + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_BREAK)) { + if (!Flag.World.BLOCK_BREAK.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + + @EventHandler + public void onBlockMove(BlockPistonExtendEvent e) { + if (VirtualRealty.isLegacy) { + if (e.getBlocks().isEmpty()) { + Location fromLocation = e.getBlock().getLocation(); + Location toLocation = e.getBlock().getLocation(); + toLocation.add(getDirection(e.getDirection())); + Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); + Plot toPlot = PlotManager.getBorderedPlot(toLocation); + Plot toUnborderedPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + if (fromPlot != null) { + if (toUnborderedPlot == null) { + e.setCancelled(true); + } + } + } else { + for (Block block : e.getBlocks()) { + Location fromLocation = block.getLocation(); + Location toLocation = block.getLocation(); + toLocation.add(getDirection(e.getDirection())); + Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); + Plot toPlot = PlotManager.getBorderedPlot(toLocation); + Plot toUnborderedPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } else { + e.setCancelled(true); + } + } + if (fromPlot != null) { + if (toUnborderedPlot == null) { + e.setCancelled(true); + } + } + } + } + } else { + if (e.getBlocks().isEmpty()) { + Location fromLocation = e.getBlock().getLocation(); + Location toLocation = e.getBlock().getLocation(); + toLocation.add(e.getDirection().getDirection()); + Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); + Plot toPlot = PlotManager.getBorderedPlot(toLocation); + Plot toUnborderedPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + if (fromPlot != null) { + if (toUnborderedPlot == null) { + e.setCancelled(true); + } + } + } else { + for (Block block : e.getBlocks()) { + Location fromLocation = block.getLocation(); + Location toLocation = block.getLocation(); + toLocation.add(e.getDirection().getDirection()); + Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); + Plot toPlot = PlotManager.getBorderedPlot(toLocation); + Plot toUnborderedPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } else { + e.setCancelled(true); + } + } + if (fromPlot != null) { + if (toUnborderedPlot == null) { + e.setCancelled(true); + } + } + } + } + } + } + + public Vector getDirection(BlockFace blockFace) { + Vector direction = new Vector(blockFace.getModX(), blockFace.getModY(), blockFace.getModZ()); + if (blockFace.getModX() != 0 || blockFace.getModY() != 0 || blockFace.getModZ() != 0) { + direction.normalize(); + } + + return direction; + } + + @EventHandler + public void onIgniteEvent(BlockIgniteEvent e) { + Player player = e.getPlayer(); + if (player != null) { + if (e.getIgnitingBlock() != null) { + Plot plot = PlotManager.getBorderedPlot(e.getIgnitingBlock().getLocation()); + if (plot != null) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + return; + } + e.setCancelled(!plot.hasPermissionToPlot(player)); + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.IGNITE)) { + if (!Flag.World.IGNITE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + } + + @EventHandler + public void onEntityExplode(ExplosionPrimeEvent e) { + Plot plot = PlotManager.getBorderedPlot(e.getEntity().getLocation()); + if (plot != null) { + e.setCancelled(true); + } else { + if (!Flag.World.EXPLOSION_PRIME.isAllowed()) { + e.setCancelled(true); + } + } + } + +// @EventHandler +// public void onPlotEnter(PlayerMoveEvent e) { +// Player player = e.getPlayer(); +// Plot plot = PlotManager.getPlot(e.getTo()); +// if (plot != null && e.getPlayer().isInsideVehicle()) { +// if (!plot.hasPermissionToPlot(player)) { +// e.getPlayer().getVehicle().eject(); +// player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantRideOnPlot); +// } +// } +// } + + @EventHandler + public void onTreeGrow(StructureGrowEvent e) { + for (BlockState block : e.getBlocks()) { + Location fromLocation = e.getLocation(); + Location toLocation = block.getLocation(); + Plot fromPlot = PlotManager.getPlot(fromLocation); + Plot toPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + } + } + + @EventHandler + public void onDragonEggMove(BlockFromToEvent e) { + Material block = e.getBlock().getType(); + if (block == Material.DRAGON_EGG || block == Material.LAVA || block == Material.WATER) { + Location fromLocation = e.getBlock().getLocation(); + Location toLocation = e.getToBlock().getLocation(); + Plot fromPlot = PlotManager.getPlot(fromLocation); + Plot toPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + } + } + + @EventHandler + public void onProjectileLaunch(ProjectileLaunchEvent e) { + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot != null) { + if (e.getEntity().getShooter() != null && e.getEntity().getShooter() instanceof Player) { + if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId()))) { + Player player = (Player) e.getEntity().getShooter(); + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.getEntity().remove(); + } + } else { + e.getEntity().remove(); + } + } + } + } + } + + @EventHandler + public void onProjectileHit(ProjectileHitEvent e) { + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot != null) { + if (e.getEntity().getShooter() != null && e.getEntity().getShooter() instanceof Player) { + if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId()))) { + Player player = (Player) e.getEntity().getShooter(); + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.getEntity().remove(); + } + } else { + e.getEntity().remove(); + } + } + } + } + } + + @EventHandler + public void onFireSpread(BlockSpreadEvent e) { + Location fromLocation = e.getSource().getLocation(); + Location toLocation = e.getBlock().getLocation(); + Plot fromPlot = PlotManager.getPlot(fromLocation); + Plot toPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + } + + @EventHandler + public void onArmorStandChange(PlayerArmorStandManipulateEvent e) { + Plot plot = PlotManager.getPlot(e.getPlayer().getLocation()); + Player player = e.getPlayer(); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ARMOR_STAND_MANIPULATION)) { + if (!Flag.World.ARMOR_STAND_MANIPULATION.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + + @EventHandler + public void onItemFrameDamage(HangingBreakByEntityEvent e) { + if (e.getRemover() instanceof Player) { + Player player = (Player) e.getRemover(); + Plot plot = PlotManager.getPlot(player.getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_DESTROY)) { + if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + + @EventHandler + public void onItemFrameRotate(PlayerInteractEntityEvent e) { + if (e.getRightClicked().getType().equals(EntityType.ITEM_FRAME)) { + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(player.getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_ROTATE)) { + if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + + + @EventHandler + public void onEntityDamage(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof Player) { + Player player = (Player) e.getDamager(); + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot != null) { + if (plot.hasPermissionToPlot(player)) { + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + } + } else { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { + if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + + @EventHandler + public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof Projectile) { + if (((Projectile) e.getDamager()).getShooter() instanceof Player) { + Player player = ((Player) ((Projectile) e.getDamager()).getShooter()); + Plot plot = PlotManager.getBorderedPlot(e.getDamager().getLocation()); + if (plot != null) { + if (!plot.hasPermissionToPlot(player)) { + e.getDamager().remove(); + e.setCancelled(true); + } + } else { + if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { + if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java new file mode 100644 index 0000000..4e2ee5d --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java @@ -0,0 +1,22 @@ +package com.modnmetl.virtualrealty.listeners; + +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.event.Listener; + +public class VirtualListener implements Listener { + + private final VirtualRealty plugin; + + public VirtualListener(VirtualRealty plugin) { + this.plugin = plugin; + } + + public void registerEvents() { + this.plugin.getServer().getPluginManager().registerEvents(this, this.plugin); + } + + protected VirtualRealty getPlugin() { + return this.plugin; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java new file mode 100644 index 0000000..9c19010 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java @@ -0,0 +1,44 @@ +package com.modnmetl.virtualrealty.listeners.plot; + +import com.modnmetl.virtualrealty.enums.Permission; +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; + +public class BorderListener extends VirtualListener { + + public BorderListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onBorderBreak(BlockBreakEvent e) { + Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); + if (plot != null) { + if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { + if (plot.getBorderBlocks().contains(e.getBlock())) { + e.setCancelled(true); + e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + } + + @EventHandler + public void onBorderPlace(BlockPlaceEvent e) { + Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); + if (plot != null) { + if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { + if (plot.getBorderBlocks().contains(e.getBlock())) { + e.setCancelled(true); + e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java new file mode 100644 index 0000000..0c8f181 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java @@ -0,0 +1,100 @@ +package com.modnmetl.virtualrealty.listeners.plot; + +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Plot; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerMoveEvent; + +import java.util.AbstractMap; +import java.util.HashMap; + +public class PlotListener extends VirtualListener { + + public HashMap> enteredPlot = new HashMap<>(); + + public PlotListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onPlotMove(PlayerMoveEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Location to = e.getTo(); + Plot plot = PlotManager.getPlot(to); + if (plot != null) { + OfflinePlayer offlinePlayer; + String enterPlotString = VirtualRealty.getMessages().enteredAvailablePlot; + if (plot.getOwnedBy() != null) { + offlinePlayer = Bukkit.getOfflinePlayer(plot.getOwnedBy()); + enterPlotString = VirtualRealty.getMessages().enteredOwnedPlot.replaceAll("%owner%", offlinePlayer.getName()).replaceAll("%plot_id%", plot.getID() + ""); + } + if (!enteredPlot.containsKey(player)) { + enteredPlot.put(player, new AbstractMap.SimpleEntry<>(plot, true)); + Plot newPlot = enteredPlot.get(player).getKey(); + if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { + if (newPlot.getOwnedBy() != null && newPlot.getOwnedBy().equals(player.getUniqueId())) { + if (newPlot.getSelectedGameMode() != VirtualRealty.getInstance().getServer().getDefaultGameMode() || newPlot.getSelectedGameMode() != VirtualRealty.getPluginConfiguration().getGameMode()) { + newPlot.setSelectedGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); + } + player.setGameMode(newPlot.getSelectedGameMode()); + } else if (newPlot.getMembers().contains(player.getUniqueId())) { + player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); + } + } + if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { + if (VirtualRealty.getPluginConfiguration().plotSound) { + player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, 0.4f, 0.8f); + } + } + if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(enterPlotString)); + } + } else { + if (!enteredPlot.get(player).getValue()) { + enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(plot, true)); + if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { + player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); + } + } + } + } else { + if (enteredPlot.containsKey(player)) { + if (enteredPlot.get(player).getValue()) { + OfflinePlayer offlinePlayer; + String leavePlotString = VirtualRealty.getMessages().leftAvailablePlot; + if (enteredPlot.get(player).getKey().getOwnedBy() != null) { + offlinePlayer = Bukkit.getOfflinePlayer(enteredPlot.get(player).getKey().getOwnedBy()); + leavePlotString = VirtualRealty.getMessages().leftOwnedPlot.replaceAll("%owner%", offlinePlayer.getName()).replaceAll("%plot_id%", enteredPlot.get(player).getKey().getID() + ""); + if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { + if (enteredPlot.get(player).getKey().hasPlotMembership(player)) { + player.setGameMode(Bukkit.getServer().getDefaultGameMode()); + } + } + } + if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { + if (VirtualRealty.getPluginConfiguration().plotSound) { + player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_CLOSE, 0.3f, 1f); + } + if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(leavePlotString)); + } + } + enteredPlot.remove(player); + return; + } + enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(enteredPlot.get(player).getKey(), false)); + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java new file mode 100644 index 0000000..2f2501b --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java @@ -0,0 +1,49 @@ +package com.modnmetl.virtualrealty.listeners.world; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.Permission; +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; + +public class WorldListener extends VirtualListener { + + public WorldListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onBlockBreak(BlockBreakEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); + if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { + if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { + if (plot == null) { + e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); + if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { + if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { + if (plot == null) { + e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java b/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java new file mode 100644 index 0000000..3e88546 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java @@ -0,0 +1,186 @@ +package com.modnmetl.virtualrealty.managers; + +import com.modnmetl.virtualrealty.enums.HighlightType; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.objects.math.BlockVector2; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Cuboid; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.objects.math.BlockVector3; +import com.modnmetl.virtualrealty.sql.SQL; +import org.bukkit.Location; +import org.bukkit.Material; +import org.dynmap.markers.AreaMarker; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + +public class PlotManager { + + private static final String markerString = "

Plot #%s

Owned By: Available"; + private static final String markerOwnedString = "

Plot #%s

Owned By: %s
Owned Until: %s"; + + public static Set areaMarkers = new HashSet<>(); + public static Set plots = new LinkedHashSet<>(); + + public static void loadPlots() { + plots.clear(); + try { + ResultSet rs = SQL.getStatement().executeQuery("SELECT * FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "`"); + while (rs.next()) { + plots.add(new Plot(rs)); + } + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + public static Plot createPlot(Location creationLocation, PlotSize plotSize) { + Plot plot = new Plot(creationLocation, plotSize.getFloorMaterial(), plotSize.getBorderMaterial(), plotSize); + plots.add(plot); + plot.insert(); + return plot; + } + + public static Plot createPlot(Location creationLocation, int length, int width, int height) { + Plot plot = new Plot(creationLocation, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), length, width, height); + plots.add(plot); + plot.insert(); + return plot; + } + + public static Plot getPlot(int ID) { + for (Plot plot : plots) { + if(plot.getID() == ID) { + return plot; + } + } + return null; + } + + public static int getPlotMinID() { + return plots.isEmpty() ? null : plots.stream().findFirst().get().getID(); + } + + public static int getPlotMaxID() { + Plot[] plotArray = PlotManager.plots.toArray(new Plot[PlotManager.plots.size()]); + Plot lastPlot = plotArray[plotArray.length - 1]; + return lastPlot.getID(); + } + + public static List getPlayerPlots(UUID owner) { + List playerPlots = new ArrayList<>(); + for (Plot plot : plots) { + if (plot.getOwnedBy() != null) { + if (plot.getOwnedBy().equals(owner)) { + playerPlots.add(plot); + } + } + } + return playerPlots; + } + + public static Plot getPlot(Location location) { + BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + for (Plot plot : plots) { + Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); + if(region.contains(newVector)) { + return plot; + } + } + return null; + } + + public static boolean isLocationInPlot(Location location, Plot plot) { + BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); + return region.contains(newVector); + } + + public static Plot getBorderedPlot(Location location) { + BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + for (Plot plot : plots) { + Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), location.getWorld()); + if(region.contains(newVector)) { + return plot; + } + } + return null; + } + + public static boolean isLocationInBorderedPlot(Location location, Plot plot) { + BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), location.getWorld()); + return region.contains(newVector); + } + + public static boolean isColliding(Cuboid newPlot) { + for (Plot plot : plots) { + Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), plot.getCreatedLocation().getWorld()); + for (BlockVector2 vector2 : region.getWalls()) { + if (vector2.containedWithin(newPlot.getMinimumPoint(), newPlot.getMaximumPoint())) { + return true; + } + } + } + return false; + } + + private static AreaMarker getAreaMarker(String areaMarkerName) { + for (AreaMarker areaMarker : VirtualRealty.markerset.getAreaMarkers()) { + if (areaMarker.getMarkerID().equalsIgnoreCase(areaMarkerName)) { + return areaMarker; + } + } + return null; + } + + public static void resetPlotMarker(Plot plot) { + if (!VirtualRealty.isDynmapPresent) return; + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + String ownedBy; + double opacity; + int color; + if (plot.getOwnedBy() == null) { + ownedBy = "Available"; + color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.getHexColor(); + opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.opacity; + } else { + ownedBy = plot.getPlotOwner().getName(); + color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.getHexColor(); + opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.opacity; + } + if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.OWNED && plot.getOwnedBy() == null) return; + if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.AVAILABLE && plot.getOwnedBy() != null) return; + AreaMarker marker = getAreaMarker("virtualrealty.plots." + plot.getID()); + if (marker == null) { + marker = VirtualRealty.markerset.createAreaMarker("virtualrealty.plots." + plot.getID(), + + plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true, + + plot.getCreatedWorld(), new double[]{plot.getXMin(), plot.getXMax()}, new double[]{plot.getZMin(), plot.getZMax()}, true); + + areaMarkers.add(marker); + } else { + marker.setLabel( + + plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true); + + } + marker.setFillStyle(opacity, color); + marker.setLineStyle(2, 0.8, 0x474747); + marker.setMarkerSet(VirtualRealty.markerset); + } + + public static void removeDynMapMarker(Plot plot) { + if (!VirtualRealty.isDynmapPresent || VirtualRealty.dapi == null || VirtualRealty.markerset == null) return; + AreaMarker marker = VirtualRealty.markerset.findAreaMarker("virtualrealty.plots." + plot.getID()); + areaMarkers.remove(marker); + marker.deleteMarker(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java b/src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java new file mode 100644 index 0000000..7c0868b --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java @@ -0,0 +1,187 @@ +package com.modnmetl.virtualrealty.objects; + +import com.modnmetl.virtualrealty.objects.math.BlockVector2; +import com.modnmetl.virtualrealty.objects.math.BlockVector3; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class Cuboid { + + private final int xMin; + private final int xMax; + private final int yMin; + private final int yMax; + private final int zMin; + private final int zMax; + private final double xMinCentered; + private final double xMaxCentered; + private final double yMinCentered; + private final double yMaxCentered; + private final double zMinCentered; + private final double zMaxCentered; + private final World world; + + public Cuboid(Location point1, Location point2) { + this.xMin = Math.min(point1.getBlockX(), point2.getBlockX()); + this.xMax = Math.max(point1.getBlockX(), point2.getBlockX()); + this.yMin = Math.min(point1.getBlockY(), point2.getBlockY()); + this.yMax = Math.max(point1.getBlockY(), point2.getBlockY()); + this.zMin = Math.min(point1.getBlockZ(), point2.getBlockZ()); + this.zMax = Math.max(point1.getBlockZ(), point2.getBlockZ()); + this.world = point1.getWorld(); + this.xMinCentered = this.xMin + 0.5; + this.xMaxCentered = this.xMax + 0.5; + this.yMinCentered = this.yMin + 0.5; + this.yMaxCentered = this.yMax + 0.5; + this.zMinCentered = this.zMin + 0.5; + this.zMaxCentered = this.zMax + 0.5; + } + + public Cuboid(BlockVector3 point1, BlockVector3 point2, World world) { + this.xMin = Math.min(point1.getBlockX(), point2.getBlockX()); + this.xMax = Math.max(point1.getBlockX(), point2.getBlockX()); + this.yMin = Math.min(point1.getBlockY(), point2.getBlockY()); + this.yMax = Math.max(point1.getBlockY(), point2.getBlockY()); + this.zMin = Math.min(point1.getBlockZ(), point2.getBlockZ()); + this.zMax = Math.max(point1.getBlockZ(), point2.getBlockZ()); + this.world = world; + this.xMinCentered = this.xMin + 0.5; + this.xMaxCentered = this.xMax + 0.5; + this.yMinCentered = this.yMin + 0.5; + this.yMaxCentered = this.yMax + 0.5; + this.zMinCentered = this.zMin + 0.5; + this.zMaxCentered = this.zMax + 0.5; + } + + + public List blockList() { + ArrayList bL = new ArrayList<>((xMax - xMin) * (yMax - yMin) * (zMax - zMin)); + for(int x = this.xMin; x <= this.xMax; ++x) { + for(int y = this.yMin; y <= this.yMax; ++y) { + for(int z = this.zMin; z <= this.zMax; ++z) { + Block b = this.world.getBlockAt(x, y, z); + bL.add(b); + } + } + } + return bL; + } + + public Location getCenter() { + return new Location(this.world, (this.xMax - this.xMin) / 2 + this.xMin + 1, (this.yMax - this.yMin) / 2 + this.yMin, (this.zMax - this.zMin) / 2 + this.zMin + 1); + } + + public BlockVector3 getCenterVector() { + return BlockVector3.at((this.xMax - this.xMin) / 2 + this.xMin + 1, (this.yMax - this.yMin) / 2 + this.yMin, (this.zMax - this.zMin) / 2 + this.zMin + 1); + } + + public double getDistance() { + return this.getPoint1().distance(this.getPoint2()); + } + + public double getDistanceSquared() { + return this.getPoint1().distanceSquared(this.getPoint2()); + } + + public int getHeight() { + return this.yMax - this.yMin + 1; + } + + public BlockVector3 getMinimumPoint() { + return BlockVector3.at(this.xMin, this.yMin, this.zMin); + } + + public BlockVector3 getMaximumPoint() { + return BlockVector3.at(this.xMax, this.yMax, this.zMax); + } + + public Location getPoint1() { + return new Location(this.world, this.xMin, this.yMin, this.zMin); + } + + public Location getPoint2() { + return new Location(this.world, this.xMax, this.yMax, this.zMax); + } + + public Location getRandomLocation() { + Random rand = new Random(); + int x = rand.nextInt(Math.abs(this.xMax - this.xMin) + 1) + this.xMin; + int y = rand.nextInt(Math.abs(this.yMax - this.yMin) + 1) + this.yMin; + int z = rand.nextInt(Math.abs(this.zMax - this.zMin) + 1) + this.zMin; + return new Location(this.world, x, y, z); + } + + public boolean contains(BlockVector3 vector3) { + return vector3.getBlockX() >= this.xMin && vector3.getBlockX() <= this.xMax && vector3.getBlockY() >= this.yMin && vector3.getBlockY() <= this.yMax && vector3 + .getBlockZ() >= this.zMin && vector3.getBlockZ() <= this.zMax; + } + + public boolean contains(BlockVector3 vector3, World world) { + return world == this.world && vector3.getBlockX() >= this.xMin && vector3.getBlockX() <= this.xMax && vector3.getBlockY() >= this.yMin && vector3.getBlockY() <= this.yMax && vector3 + .getBlockZ() >= this.zMin && vector3.getBlockZ() <= this.zMax; + } + + public int getTotalBlockSize() { + return this.getHeight() * this.getXWidth() * this.getZWidth(); + } + + public int getXWidth() { + return this.xMax - this.xMin + 1; + } + + public int getZWidth() { + return this.zMax - this.zMin + 1; + } + + public boolean isIn(Location loc) { + return loc.getWorld() == this.world && loc.getBlockX() >= this.xMin && loc.getBlockX() <= this.xMax && loc.getBlockY() >= this.yMin && loc.getBlockY() <= this.yMax && loc + .getBlockZ() >= this.zMin && loc.getBlockZ() <= this.zMax; + } + + public boolean isIn(Player player) { + return this.isIn(player.getLocation()); + } + + public boolean isInWithMarge(Location loc, double marge) { + return loc.getWorld() == this.world && loc.getX() >= this.xMinCentered - marge && loc.getX() <= this.xMaxCentered + marge && loc.getY() >= this.yMinCentered - marge && loc + .getY() <= this.yMaxCentered + marge && loc.getZ() >= this.zMinCentered - marge && loc.getZ() <= this.zMaxCentered + marge; + } + + public boolean isColliding(Cuboid region) { + List flatRegion1 = new ArrayList<>(this.getFlatRegion()); + List flatRegion2 = new ArrayList<>(region.getFlatRegion()); + for (BlockVector2 vector1 : flatRegion1) { + for (BlockVector2 vector2 : flatRegion2) + if (vector1.getBlockX() == vector2.getBlockX() && vector1.getBlockZ() == vector2.getBlockZ()) return true; + } + return false; + } + + public List getFlatRegion() { + List blocksVector = new ArrayList<>(); + for (Block block : blockList()) { + blocksVector.add(BlockVector2.at(block.getLocation().getBlockX(), block.getLocation().getBlockZ())); + } + return blocksVector; + } + + public List getWalls() { + List walls = new ArrayList<>(); + for (int z = zMin; z <= zMax; z++) { + walls.add(BlockVector2.at(xMin, z)); + walls.add(BlockVector2.at(xMax, z)); + } + for (int x = xMin; x < xMax; x++) { + walls.add(BlockVector2.at(x, zMin)); + walls.add(BlockVector2.at(x, zMax)); + } + return walls; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java b/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java new file mode 100644 index 0000000..96f0949 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java @@ -0,0 +1,796 @@ +package com.modnmetl.virtualrealty.objects; + +import com.modnmetl.virtualrealty.enums.Direction; +import com.modnmetl.virtualrealty.enums.Permission; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.sql.SQL; +import com.modnmetl.virtualrealty.utils.SchematicUtil; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.math.BlockVector3; +import org.apache.commons.io.FileUtils; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.*; + +public class Plot { + + private int ID; + private UUID ownedBy; + private Set members; + private String assignedBy; + private LocalDateTime ownedUntilDate; + private PlotSize plotSize; + private int length; + private int width; + private int height; + private Material floorMaterial; + private byte floorData; + private Material borderMaterial; + private byte borderData; + private Location createdLocation; + private Direction createdDirection; + private BlockVector3 bottomLeftCorner; + private BlockVector3 topRightCorner; + private BlockVector3 borderBottomLeftCorner; + private BlockVector3 borderTopRightCorner; + private GameMode selectedGameMode; + private String createdWorld; + private Instant modified; + + @Override + public String toString() { + return "{ ID: " + ID + ", ownedBy: " + ownedBy + "}"; + } + + public Plot(Location location, Material floorMaterial, Material borderMaterial, PlotSize plotSize) { + this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; + this.ownedBy = null; + this.members = new HashSet<>(); + this.assignedBy = null; + this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); + this.floorMaterial = floorMaterial; + this.floorData = 0; + this.borderMaterial = borderMaterial; + this.borderData = 0; + this.plotSize = plotSize; + this.length = plotSize.getLength(); + this.width = plotSize.getWidth(); + this.height = plotSize.getHeight(); + this.createdLocation = location; + this.createdDirection = Direction.byYaw(location.getYaw()); + this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); + this.createdWorld = location.getWorld().getName(); + this.modified = Instant.now(); + initialize(); + initializeCorners(); + if (VirtualRealty.markerset != null) { + PlotManager.resetPlotMarker(this); + } + } + + public Plot(Location location, Material floorMaterial, Material borderMaterial, int length, int width, int height) { + this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; + this.ownedBy = null; + this.members = new HashSet<>(); + this.assignedBy = null; + this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); + this.floorMaterial = floorMaterial; + this.floorData = 0; + this.borderMaterial = borderMaterial; + this.borderData = 0; + this.plotSize = PlotSize.CUSTOM; + this.length = length; + this.width = width; + this.height = height; + this.createdLocation = location; + this.createdDirection = Direction.byYaw(location.getYaw()); + this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); + this.createdWorld = location.getWorld().getName(); + this.modified = Instant.now(); + initialize(); + initializeCorners(); + if (VirtualRealty.markerset != null) { + PlotManager.resetPlotMarker(this); + } + } + + + public Plot(ResultSet rs) { + try { + this.ID = rs.getInt("ID"); + this.ownedBy = rs.getString("ownedBy").isEmpty() ? null : UUID.fromString(rs.getString("ownedBy")); + this.members = new HashSet<>(); + String membersString = rs.getString("members"); + if (membersString != null && !membersString.isEmpty()) { + String[] membersArray = membersString.substring(0, membersString.length() - 1).split(";"); + for (String s : membersArray) { + members.add(UUID.fromString(s)); + } + } + this.assignedBy = rs.getString("assignedBy").equalsIgnoreCase("null") ? null : rs.getString("assignedBy"); + this.ownedUntilDate = rs.getTimestamp("ownedUntilDate").toLocalDateTime(); + this.floorMaterial = Material.getMaterial(rs.getString("floorMaterial").split(":")[0]); + this.floorData = rs.getString("floorMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("floorMaterial").split(":")[1]); + if (rs.getString("borderMaterial") != null) { + this.borderMaterial = Material.getMaterial(rs.getString("borderMaterial").split(":")[0]); + this.borderData = rs.getString("borderMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("borderMaterial").split(":")[1]); + } + this.plotSize = PlotSize.valueOf(rs.getString("plotSize")); + this.length = rs.getInt("length"); + this.width = rs.getInt("width"); + this.height = rs.getInt("height"); + ArrayList location = new ArrayList<>(Arrays.asList(rs.getString("createdLocation").subSequence(0, rs.getString("createdLocation").length() - 1).toString().split(";"))); + Location createLocation = new Location(Bukkit.getWorld(location.get(0)), Double.parseDouble(location.get(1)), Double.parseDouble(location.get(2)), Double.parseDouble(location.get(3)), Float.parseFloat(location.get(4)), Float.parseFloat(location.get(5))); + this.createdLocation = rs.getString("createdLocation").isEmpty() ? null : createLocation; + this.createdDirection = Direction.byYaw(createdLocation.getYaw()); + this.selectedGameMode = GameMode.CREATIVE; + this.createdWorld = location.get(0); + if (floorMaterial == null) { + floorMaterial = plotSize.getFloorMaterial(); + floorData = plotSize.getFloorData(); + } + if (borderMaterial == null) { + borderMaterial = plotSize.getBorderMaterial(); + borderData = plotSize.getBorderData(); + } + initializeCorners(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public boolean hasPermissionToPlot(Player player) { + if (player.hasPermission(Permission.PLOT_BUILD.getPermission())) return true; + if (members.contains(player.getUniqueId())) return true; + return ownedBy != null && ownedBy.equals(player.getUniqueId()); + } + + public boolean hasPlotMembership(Player player) { + if (members.contains(player.getUniqueId())) return true; + return ownedBy != null && ownedBy.equals(player.getUniqueId()); + } + + public boolean isOwnershipExpired() { + return ownedUntilDate.isBefore(LocalDateTime.now()); + } + + public int getXMin() { + return Math.min(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); + } + + public int getXMax() { + return Math.max(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); + } + + public int getZMin() { + return Math.min(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); + } + + public int getZMax() { + return Math.max(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); + } + + public int getID() { + return ID; + } + + public void setID(int ID) { + this.ID = ID; + } + + public UUID getOwnedBy() { + return ownedBy; + } + + public void setOwnedBy(UUID ownedBy) { + this.ownedBy = ownedBy; + members.remove(ownedBy); + updateMarker(); + modified(); + } + + public String getAssignedBy() { + return assignedBy; + } + + public void setAssignedBy(String assignedBy) { + this.assignedBy = assignedBy; + modified(); + } + + public LocalDateTime getOwnedUntilDate() { + return ownedUntilDate; + } + + public void setOwnedUntilDate(LocalDateTime ownedUntilDate) { + this.ownedUntilDate = ownedUntilDate; + updateMarker(); + modified(); + } + + public PlotSize getPlotSize() { + return plotSize; + } + + public void setPlotSize(PlotSize plotSize) { + this.plotSize = plotSize; + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + public Material getFloorMaterial() { + return floorMaterial; + } + + public void setFloorMaterial(Material floorMaterial, byte data) { + this.floorMaterial = floorMaterial; + this.floorData = data; + initializeFloor(); + modified(); + } + + public Location getCreatedLocation() { + return createdLocation; + } + + public void setBorderMaterial(Material borderMaterial, byte data) { + this.borderMaterial = borderMaterial; + this.borderData = data; + modified(); + } + + public Material getBorderMaterial() { + return borderMaterial; + } + + public void setCreatedLocation(Location createdLocation) { + this.createdLocation = createdLocation; + } + + public BlockVector3 getBottomLeftCorner() { + return bottomLeftCorner; + } + + public void setBottomLeftCorner(BlockVector3 bottomLeftCorner) { + this.bottomLeftCorner = bottomLeftCorner; + } + + public BlockVector3 getTopRightCorner() { + return topRightCorner; + } + + public void setTopRightCorner(BlockVector3 topRightCorner) { + this.topRightCorner = topRightCorner; + } + + public BlockVector3 getBorderBottomLeftCorner() { + return borderBottomLeftCorner; + } + + public void setBorderBottomLeftCorner(BlockVector3 borderBottomLeftCorner) { + this.borderBottomLeftCorner = borderBottomLeftCorner; + } + + public BlockVector3 getBorderTopRightCorner() { + return borderTopRightCorner; + } + + public void setBorderTopRightCorner(BlockVector3 borderTopRightCorner) { + this.borderTopRightCorner = borderTopRightCorner; + } + + public BlockVector3 getBorderedCenter() { + return new Cuboid(borderBottomLeftCorner, borderTopRightCorner, createdLocation.getWorld()).getCenterVector(); + } + + public BlockVector3 getCenter() { + return new Cuboid(bottomLeftCorner, topRightCorner, createdLocation.getWorld()).getCenterVector(); + } + + public GameMode getSelectedGameMode() { + return selectedGameMode; + } + + public String getCreatedWorld() { + return createdWorld; + } + + public OfflinePlayer getPlotOwner() { + return ownedBy == null ? null : Bukkit.getOfflinePlayer(ownedBy); + } + + public void setSelectedGameMode(GameMode selectedGameMode) { + this.selectedGameMode = selectedGameMode; + } + + public void addMember(UUID uuid) { + members.add(uuid); + modified(); + } + + public void removeMember(UUID uuid) { + members.remove(uuid); + } + + public Set getMembers() { + return members; + } + + public Set getMembersPlayer() { + Set offlinePlayers = new HashSet<>(); + for (UUID member : members) { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(member); + offlinePlayers.add(offlinePlayer); + } + return offlinePlayers; + } + + private void setFloorBlock(Block floorBlock) { + if (VirtualRealty.isLegacy) { + try { + Method m = Block.class.getDeclaredMethod("setType", Material.class); + m.setAccessible(true); + m.invoke(floorBlock, this.floorMaterial); + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(floorBlock, this.floorData); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + floorBlock.setType(floorMaterial); + } + modified(); + } + + private void initializeFloor() { + Location location = createdLocation; + Direction direction = Direction.byYaw(location.getYaw()); + switch(direction) { + case SOUTH: { + for (int x = location.getBlockX() - width + 1; x < location.getBlockX() + 1; x++) { + for (int z = location.getBlockZ(); z < location.getBlockZ() + length; z++) { + Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); + setFloorBlock(floorBlock); + } + } + break; + } + case WEST: { + for (int x = location.getBlockX() - length + 1; x < location.getBlockX() + 1; x++) { + for (int z = location.getBlockZ() - width + 1; z < location.getBlockZ() + 1; z++) { + Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); + setFloorBlock(floorBlock); + } + } + break; + } + case NORTH: { + for (int x = location.getBlockX(); x < location.getBlockX() + width; x++) { + for (int z = location.getBlockZ() - length + 1; z < location.getBlockZ() + 1; z++) { + Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); + setFloorBlock(floorBlock); + } + } + break; + } + case EAST: { + for (int x = location.getBlockX(); x < location.getBlockX() + length; x++) { + for (int z = location.getBlockZ(); z < location.getBlockZ() + width; z++) { + Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); + setFloorBlock(floorBlock); + } + } + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + } + + public void initializeCorners() { + Location location = createdLocation; + Direction direction = Direction.byYaw(location.getYaw()); + Location location1; + Location location2; + Location border1; + Location border2; + switch(direction) { + case SOUTH: { + location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); + location2 = new Location(location.getWorld(), location.getBlockX() - width + 1, location.getBlockY() + height, location.getBlockZ() + length - 1); + border1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); + border2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); + break; + } + case WEST: { + location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); + location2 = new Location(location.getWorld(), location.getBlockX() - length + 1, location.getBlockY() + height, location.getBlockZ() - width + 1); + border1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); + border2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); + break; + } + case NORTH: { + location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); + location2 = new Location(location.getWorld(), location.getBlockX() + width - 1, location.getBlockY() + height, location.getBlockZ() - length + 1); + border1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); + border2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); + break; + } + case EAST: { + location1 = new Location(location.getWorld(), location.getBlockX() + length - 1, location.getBlockY() - 10, location.getBlockZ()); + location2 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() + height, location.getBlockZ() + width - 1); + border1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); + border2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + this.bottomLeftCorner = BlockVector3.at(location1.getBlockX(), location1.getBlockY(), location1.getBlockZ()); + this.topRightCorner = BlockVector3.at(location2.getBlockX(), location2.getBlockY(), location2.getBlockZ()); + this.borderBottomLeftCorner = BlockVector3.at(border1.getBlockX(), border1.getBlockY(), border1.getBlockZ()); + this.borderTopRightCorner = BlockVector3.at(border2.getBlockX(), border2.getBlockY(), border2.getBlockZ()); + } + + public void initialize() { + prepareBlocks(createdLocation); + } + + public Set getBorderBlocks() { + Set blocks = new HashSet<>(); + Location location = this.getCreatedLocation(); + Direction direction = Direction.byYaw(location.getYaw()); + int maxX; + int maxZ; + int minX; + int minZ; + switch(direction) { + case SOUTH: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + length + 1; + minX = location.getBlockX() - width + 1; + minZ = location.getBlockZ() - 1; + break; + } + case WEST: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX() - length + 1; + minZ = location.getBlockZ() - width; + break; + } + case NORTH: { + maxX = location.getBlockX() + width + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - length; + break; + } + case EAST: { + maxX = location.getBlockX() + length + 1; + maxZ = location.getBlockZ() + width + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - 1; + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + for (int x = minX - 1; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { + blocks.add(location.getWorld().getBlockAt(x, location.getBlockY() + 1, z)); + } + } + } + return blocks; + } + + public Set getFloorBlocks() { + Set blocks = new HashSet<>(); + Location location = this.getCreatedLocation(); + Direction direction = Direction.byYaw(location.getYaw()); + int maxX; + int maxZ; + int minX; + int minZ; + switch(direction) { + case SOUTH: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + length + 1; + minX = location.getBlockX() - width + 1; + minZ = location.getBlockZ() - 1; + break; + } + case WEST: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX() - length + 1; + minZ = location.getBlockZ() - width; + break; + } + case NORTH: { + maxX = location.getBlockX() + width + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - length; + break; + } + case EAST: { + maxX = location.getBlockX() + length + 1; + maxZ = location.getBlockZ() + width + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - 1; + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + for (int x = minX - 1; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + blocks.add(location.getWorld().getBlockAt(x, location.getBlockY(), z)); + } + } + return blocks; + } + + public void setBorder(Material material, byte data) { + borderMaterial = material; + borderData = data; + for (Block borderBlock : getBorderBlocks()) { + if (VirtualRealty.isLegacy) { + borderBlock.setType(material); + try { + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(borderBlock, data); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } else { + borderBlock.setType(material); + } + } + modified(); + } + + public void prepareBlocks(Location location) { + Direction direction = Direction.byYaw(location.getYaw()); + Location location1; + Location location2; + switch (direction) { + case SOUTH: { + location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); + location2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); + break; + } + case WEST: { + location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); + location2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); + break; + } + case NORTH: { + location1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); + location2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); + break; + } + case EAST: { + location1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); + location2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); + SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); + break; + } + } + for (Block floorBlock : getFloorBlocks()) { + for (int y = location.getBlockY() + height; y > location.getBlockY() - 1; y--) { + Block airBlock = location.getWorld().getBlockAt(floorBlock.getX(), y, floorBlock.getZ()); + airBlock.setType(Material.AIR); + } + floorBlock.setType(floorMaterial); + if (VirtualRealty.isLegacy) { + try { + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(floorBlock, plotSize.getFloorData()); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } + } + int maxX = 0; + int maxZ = 0; + int minX = 0; + int minZ = 0; + switch(direction) { + case SOUTH: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + length + 1; + minX = location.getBlockX() - width + 1; + minZ = location.getBlockZ() - 1; + break; + } + case WEST: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX() - length + 1; + minZ = location.getBlockZ() - width; + break; + } + case NORTH: { + maxX = location.getBlockX() + width + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - length; + break; + } + case EAST: { + maxX = location.getBlockX() + length + 1; + maxZ = location.getBlockZ() + width + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - 1; + break; + } + } + for (int x = minX - 1; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { + Block borderBlock = location.getWorld().getBlockAt(x, location.getBlockY() + 1, z); + if (VirtualRealty.isLegacy) { + borderBlock.setType(plotSize.getBorderMaterial()); + try { + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(borderBlock, plotSize.getBorderData()); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } else { + borderBlock.setType(plotSize.getBorderMaterial()); + } + } + } + } + } + + public void unloadPlot() { + switch (createdDirection) { + case SOUTH: { + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - width, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); + break; + } + case WEST: { + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - length, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - width)); + break; + } + case NORTH: { + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - length)); + break; + } + case EAST: { + SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), + createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); + break; + } + } + } + + public String getMembersString() { + StringBuilder stringBuilder = new StringBuilder(); + for (UUID member : members) { + stringBuilder.append(member.toString()).append(";"); + } + return stringBuilder.toString(); + } + + public void insert() { + StringBuilder builder = new StringBuilder(); + builder.append(this.createdLocation.getWorld().getName() + ";"); + builder.append(this.createdLocation.getX() + ";"); + builder.append(this.createdLocation.getY() + ";"); + builder.append(this.createdLocation.getZ() + ";"); + builder.append(this.createdLocation.getYaw() + ";"); + builder.append(this.createdLocation.getPitch() + ";"); + try { + SQL.getStatement().execute("INSERT INTO `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + + "` (`ID`, `ownedBy`, `members`, `assignedBy`, `ownedUntilDate`," + + " `floorMaterial`, `borderMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`, `created`, `modified`) " + + "VALUES ('" + this.ID + "', '" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "','" + getMembersString() + "', '" + this.assignedBy + "', " + + "'" + Timestamp.valueOf(this.ownedUntilDate) + "', '" + this.floorMaterial + ":" + this.floorData + "', '" + this.borderMaterial + ":" + this.borderData + "'," + + " '" + this.plotSize + "', '" + this.length + "', '" + this.width + "', '" + this.height + "', '" + builder + "', '" + Timestamp.from(Instant.now()) + "', '" + Timestamp.from(Instant.now()) + "')"); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void update() { + try { + SQL.getStatement().execute("UPDATE `" + + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + + "` SET `ownedBy`='" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "'," + + " `members`='" + getMembersString() + "', `assignedBy`='" + this.assignedBy + "'," + + " `ownedUntilDate`='" + Timestamp.valueOf(this.ownedUntilDate) + "'," + + " `floorMaterial`='" + this.floorMaterial + ":" + this.floorData + "'," + + " `borderMaterial`='" + this.borderMaterial + ":" + this.borderData + "'," + + " `plotSize`='" + this.plotSize + "'," + + " `length`='" + this.length + "'," + + " `width`='" + this.width + "'," + + " `height`='" + this.height + "'," + + " `modified`='" + (this.modified != null ? Timestamp.from(this.modified) : Timestamp.from(Instant.now())) + "'" + + " WHERE `ID`='" + this.ID + "'"); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void remove() { + this.unloadPlot(); + PlotManager.removeDynMapMarker(this); + try { + SQL.getStatement().execute("DELETE FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` WHERE `ID` = '" + ID + "';"); + } catch (SQLException e) { + e.printStackTrace(); + } + int id = ID; + File file = new File(VirtualRealty.plotsSchemaFolder, "plot" + id + ".region"); + if (file.exists()) + FileUtils.deleteQuietly(file); + PlotManager.plots.remove(this); + } + + public Direction getCreatedDirection() { + return createdDirection; + } + + public void setCreatedDirection(Direction createdDirection) { + this.createdDirection = createdDirection; + } + + public void updateMarker() { + PlotManager.resetPlotMarker(this); + } + + public void modified() { + this.modified = Instant.now(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector2.java b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector2.java new file mode 100644 index 0000000..6512d7e --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector2.java @@ -0,0 +1,44 @@ +package com.modnmetl.virtualrealty.objects.math; + +import java.util.Vector; + +public class BlockVector2 extends Vector { + + private int x; + private int z; + + public BlockVector2(int x, int z) { + this.x = x; + this.z = z; + } + + public static BlockVector2 at(int x, int z) { + return new BlockVector2(x, z); + } + + public int getBlockX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getBlockZ() { + return z; + } + + public void setZ(int z) { + this.z = z; + } + + public boolean containedWithin(BlockVector2 min, BlockVector2 max) { + return this.x >= min.x && this.x <= max.x && this.z >= min.z && this.z <= max.z; + } + + @Override + public String toString() { + return "(" + x + ", " + z + ")"; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java new file mode 100644 index 0000000..8c217a9 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java @@ -0,0 +1,59 @@ +package com.modnmetl.virtualrealty.objects.math; + +import org.bukkit.Location; + +public class BlockVector3 extends BlockVector2 { + + private int x; + private int y; + private int z; + + private BlockVector3(int x, int y, int z) { + super(x, z); + this.x = x; + this.y = y; + this.z = z; + } + + public static BlockVector3 at(int x, int y, int z) { + return new BlockVector3(x, y, z); + } + + public static BlockVector3 locationToVector(Location location) { + return new BlockVector3(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + } + + public int getBlockX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getBlockY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + public int getBlockZ() { + return z; + } + + public void setZ(int z) { + this.z = z; + } + + @Override + public String toString() { + return "(" + x + ", " + y + ", " + z + ")"; + } + + public String toSimpleString() { + return x + ", " + y + ", " + z; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java b/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java new file mode 100644 index 0000000..8c7d23b --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java @@ -0,0 +1,123 @@ +package com.modnmetl.virtualrealty.registry; + +import com.modnmetl.virtualrealty.managers.PlotManager; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.entity.Player; + +public class VirtualPlaceholders extends PlaceholderExpansion { + + private final VirtualRealty plugin; + + /** + * Since we register the expansion inside our own plugin, we + * can simply use this method here to get an instance of our + * plugin. + * + * @param plugin + * The instance of our plugin. + */ + public VirtualPlaceholders(VirtualRealty plugin){ + this.plugin = plugin; + } + + /** + * Because this is an internal class, + * you must override this method to let PlaceholderAPI know to not unregister your expansion class when + * PlaceholderAPI is reloaded + * + * @return true to persist through reloads + */ + @Override + public boolean persist(){ + return true; + } + + /** + * Because this is a internal class, this check is not needed + * and we can simply return {@code true} + * + * @return Always true since it's an internal class. + */ + @Override + public boolean canRegister(){ + return true; + } + + /** + * The name of the person who created this expansion should go here. + *
For convienience do we return the author from the plugin.yml + * + * @return The name of the author as a String. + */ + @Override + public String getAuthor(){ + return plugin.getDescription().getAuthors().toString(); + } + + /** + * The placeholder identifier should go here. + *
This is what tells PlaceholderAPI to call our onRequest + * method to obtain a value if a placeholder starts with our + * identifier. + *
The identifier has to be lowercase and can't contain _ or % + * + * @return The identifier in {@code %_%} as String. + */ + @Override + public String getIdentifier(){ + return "virtualrealty"; + } + + /** + * This is the version of the expansion. + *
You don't have to use numbers, since it is set as a String. + * + * For convienience do we return the version from the plugin.yml + * + * @return The version as a String. + */ + @Override + public String getVersion(){ + return plugin.getDescription().getVersion(); + } + + /** + * This is the method called when a placeholder with our identifier + * is found and needs a value. + *
We specify the value identifier in this method. + *
Since version 2.9.1 can you use OfflinePlayers in your requests. + * + * @param player + * A {@link org.bukkit.entity.Player Player}. + * @param identifier + * A String containing the identifier/value. + * + * @return possibly-null String of the requested identifier. + */ + @Override + public String onPlaceholderRequest(Player player, String identifier){ + if(player == null) + return ""; + + Plot plot = PlotManager.getBorderedPlot(player.getLocation()); + if (identifier.equals("plot_id")) { + if (plot == null) return ""; + return String.valueOf(plot.getID()); + } + if (identifier.equals("plot_owner")) { + if (plot == null) return ""; + if (plot.getOwnedBy() == null) return ""; + return String.valueOf(plot.getPlotOwner().getName()); + } + if (identifier.equals("is_plot_owner")) { + if (plot == null) return ""; + if (plot.getOwnedBy() == null) return "false"; + if (plot.getOwnedBy().equals(player.getUniqueId())) return "true"; + return "false"; + } + return null; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/sql/SQL.java b/src/main/java/com/modnmetl/virtualrealty/sql/SQL.java new file mode 100644 index 0000000..17d4854 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/sql/SQL.java @@ -0,0 +1,120 @@ +package com.modnmetl.virtualrealty.sql; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.configs.PluginConfiguration; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +public class SQL { + + private static Connection connection; + private static Statement statement; + public static final long MYSQL_TIMEOUT_MS = 28800000; + private static long lastQuery = System.currentTimeMillis(); + + public static void connect() { + try { + switch (VirtualRealty.getPluginConfiguration().dataModel) { + case SQLITE: { + Class.forName("org.sqlite.JDBC"); + File dataDir = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + File.separator + "data"); + if (!dataDir.exists()) { + dataDir.mkdirs(); + } + connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + File.separator + "data" + File.separator + "data.db"); + break; + } + case MYSQL: { + Class.forName("com.mysql.jdbc.Driver"); + connection = DriverManager.getConnection("jdbc:mysql://" + VirtualRealty.getPluginConfiguration().mysql.hostname + ":" + VirtualRealty.getPluginConfiguration().mysql.port + "/" + VirtualRealty.getPluginConfiguration().mysql.database + "?useSSL=" + VirtualRealty.getPluginConfiguration().mysql.useSSL + "&autoReconnect=true", VirtualRealty.getPluginConfiguration().mysql.user, VirtualRealty.getPluginConfiguration().mysql.password); + break; + } + } + createStatement(); + } catch (SQLException | ClassNotFoundException ex) { + ex.printStackTrace(); + } + } + + public static void createStatement() { + try { + statement = connection.createStatement(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + public static void closeConnection() { + try { + if (statement != null && (VirtualRealty.getPluginConfiguration().dataModel != PluginConfiguration.DataModel.SQLITE && !statement.isClosed())) { + statement.close(); + } + if (connection != null) + connection.close(); + VirtualRealty.debug("Database connection closed"); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + public static void createTables() { + try { + statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); + updateTables(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + public static void updateTables() { + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `borderMaterial` VARCHAR(32) AFTER `floorMaterial`;"); + } catch (SQLException ignored) { + + } + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `members` TEXT AFTER `ownedBy`;"); + } catch (SQLException ignored) { + + } + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `created` DATETIME AFTER `createdLocation`;"); + } catch (SQLException ignored) { + + } + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `modified` DATETIME AFTER `created`;"); + } catch (SQLException ignored) { + + } + } + + public static Statement getStatement() { + try { + if (System.currentTimeMillis() - lastQuery > MYSQL_TIMEOUT_MS) { + connection.close(); + statement.close(); + connect(); + } else if(connection.isClosed()) { + connect(); + } + lastQuery = System.currentTimeMillis(); + } catch (SQLException e) { + e.printStackTrace(); + } + return statement; + } + + + public static void setConnection(Connection connection) { + SQL.connection = connection; + } + + public static void setStatement(Statement statement) { + SQL.statement = statement; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java b/src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java new file mode 100644 index 0000000..1e1b393 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java @@ -0,0 +1,46 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.configs.SizesConfiguration; +import eu.okaeri.configs.ConfigManager; +import eu.okaeri.configs.serdes.commons.SerdesCommons; +import eu.okaeri.configs.validator.okaeri.OkaeriValidator; +import eu.okaeri.configs.yaml.bukkit.YamlBukkitConfigurer; +import com.modnmetl.virtualrealty.configs.MessagesConfiguration; +import com.modnmetl.virtualrealty.configs.PluginConfiguration; + +import java.io.File; + +public class ConfigurationFactory { + + public ConfigurationFactory() { + + } + + public PluginConfiguration createPluginConfiguration(File pluginConfigurationFile) { + return ConfigManager.create(PluginConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); + it.withBindFile(pluginConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + + public SizesConfiguration createSizesConfiguration(File sizesConfigurationFile) { + return ConfigManager.create(SizesConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); + it.withBindFile(sizesConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + + public MessagesConfiguration createMessagesConfiguration(File messagesConfigurationFile) { + return ConfigManager.create(MessagesConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); + it.withBindFile(messagesConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/Permissions.java b/src/main/java/com/modnmetl/virtualrealty/utils/Permissions.java new file mode 100644 index 0000000..d1cc936 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/Permissions.java @@ -0,0 +1,27 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; + +public class Permissions { + + public static boolean hasPermission(CommandSender sender, Permission basePermission, String permission) { + Permission finalPermission = new Permission(basePermission.getName() + "." + permission); + if (!sender.hasPermission(finalPermission)) { + sender.sendMessage(VirtualRealty.PREFIX + "§cInsufficient permissions! §8(§7" + finalPermission.getName() + "§8)"); + return false; + } + return true; + } + + public static boolean hasPermission(CommandSender sender, String permission) { + Permission finalPermission = new Permission(permission); + if (!sender.hasPermission(finalPermission)) { + sender.sendMessage(VirtualRealty.PREFIX + "§cInsufficient permissions! §8(§7" + finalPermission.getName() + "§8)"); + return false; + } + return true; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java new file mode 100644 index 0000000..a4cc196 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java @@ -0,0 +1,41 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.enums.Direction; +import com.modnmetl.virtualrealty.objects.Cuboid; +import com.modnmetl.virtualrealty.objects.math.BlockVector3; +import org.bukkit.Location; + +public class PlotUtil { + + public static Cuboid getPlotRegion(Location location, Direction direction, int length, int width, int height) { + Location location1; + Location location2; + switch(direction) { + case SOUTH: { + location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); + location2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); + break; + } + case WEST: { + location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); + location2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); + break; + } + case NORTH: { + location1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); + location2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); + break; + } + case EAST: { + location1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); + location2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + return new Cuboid(BlockVector3.at(location1.getBlockX(), location1.getBlockY(), location1.getBlockZ()), + BlockVector3.at(location2.getBlockX(), location2.getBlockY(), location2.getBlockZ()), location.getWorld()); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java new file mode 100644 index 0000000..84c2450 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java @@ -0,0 +1,40 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.enums.Permission; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.Flag; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.time.LocalDateTime; + +public class ProtectionUtil { + + public static boolean canBuild(Player player, Location location) { + Plot plot = PlotManager.getBorderedPlot(location); + if (plot != null) { + if (plot.getOwnedBy() != null) { + if (!plot.getOwnedBy().equals(player.getUniqueId())) { + return false; + } else { + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + return false; + } + } + } else { + return false; + } + } + return true; + } + + public static boolean hasPermissionToWorld(Player player, Flag.World flag) { + if (player.hasPermission(Permission.WORLD_BUILD.getPermission())) return true; + if (player.hasPermission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".world." + flag.name().toLowerCase())) return true; + if (player.isOp()) return true; + return false; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java b/src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java new file mode 100644 index 0000000..95bd794 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java @@ -0,0 +1,271 @@ +package com.modnmetl.virtualrealty.utils; + +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.entity.Entity; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public final class Reflections { + + public static final String SERVER_VERSION = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + public static final boolean USE_PRE_13_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 13; + public static final boolean USE_PRE_12_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 12; + public static final boolean USE_PRE_9_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 9; + + private static final Map> CLASS_CACHE = new HashMap<>(); + private static final Map FIELD_CACHE = new HashMap<>(); + private static final Map> FIELD_ACCESSOR_CACHE = new HashMap<>(); + private static final Map METHOD_CACHE = new HashMap<>(); + private static final Class INVALID_CLASS = InvalidMarker.class; + private static final Method INVALID_METHOD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredMethod("invalidMethodMaker")); + private static final Field INVALID_FIELD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredField("invalidFieldMarker")); + private static final FieldAccessor INVALID_FIELD_ACCESSOR = getField(INVALID_CLASS, Void.class, 0); + + public static Class getClassOmitCache(String className) { + CLASS_CACHE.remove(className); + return getClass(className); + } + + public static Class getClass(String className) { + Class c = CLASS_CACHE.get(className); + + if (c != null) { + return c != INVALID_CLASS ? c : null; + } + + try { + c = Class.forName(className); + CLASS_CACHE.put(className, c); + } + catch (Exception ex) { + System.err.println("Could not retrieve class"); + + CLASS_CACHE.put(className, INVALID_CLASS); + } + return c; + } + + public static Class getNMSClass(String name) { + return getClass("net.minecraft.server." + SERVER_VERSION + "." + name); + } + + public static Class getCraftBukkitClass(String name) { + return getClass("org.bukkit.craftbukkit." + SERVER_VERSION + "." + name); + } + + public static Class getBukkitClass(String name) { + return getClass("org.bukkit." + name); + } + + public static Object getHandle(Entity entity) { + try { + return getMethod(entity.getClass(), "getHandle").invoke(entity); + } + catch (Exception ex) { + System.err.println("Could not get entity handle"); + return null; + } + } + + public static Object getHandle(World world) { + try { + return getMethod(world.getClass(), "getHandle").invoke(world); + } + catch (Exception ex) { + System.err.println("Could not get world handle"); + + return null; + } + } + + private static String constructFieldCacheKey(Class cl, String fieldName) { + return cl.getName() + "." + fieldName; + } + + public static Field getField(Class cl, String fieldName) { + String cacheKey = constructFieldCacheKey(cl, fieldName); + + Field field = FIELD_CACHE.get(cacheKey); + + if (field != null) { + return field != INVALID_FIELD ? field : null; + } + + try { + field = cl.getDeclaredField(fieldName); + FIELD_CACHE.put(cacheKey, field); + } + catch (Exception ex) { + System.err.println("Could not retrieve field"); + + FIELD_CACHE.put(cacheKey, INVALID_FIELD); + } + + return field; + } + + public static FieldAccessor getField(Class target, Class fieldType, int index) { + return getField(target, null, fieldType, index); + } + + @SuppressWarnings("unchecked") + private static FieldAccessor getField(Class target, String name, Class fieldType, int index) { + final String cacheKey = target.getName() + "." + (name != null ? name : "NONE") + "." + fieldType.getName() + "." + index; + + FieldAccessor output = (FieldAccessor) FIELD_ACCESSOR_CACHE.get(cacheKey); + + if (output != null) { + if (output == INVALID_FIELD_ACCESSOR) { + throw new IllegalArgumentException("Cannot find field with type " + fieldType); + } + + return output; + } + + for (final Field field : target.getDeclaredFields()) { + if ((name == null || field.getName().equals(name)) && fieldType.isAssignableFrom(field.getType()) && index-- <= 0) { + field.setAccessible(true); + + output = new FieldAccessor() { + + @Override + public T get(Object target) { + try { + return (T) field.get(target); + } catch (IllegalAccessException e) { + throw new RuntimeException("Cannot access reflection.", e); + } + } + + @Override + public void set(Object target, Object value) { + try { + field.set(target, value); + } catch (IllegalAccessException e) { + throw new RuntimeException("Cannot access reflection.", e); + } + } + + @Override + public boolean hasField(Object target) { + return field.getDeclaringClass().isAssignableFrom(target.getClass()); + } + }; + + break; + } + } + + if (output == null && target.getSuperclass() != null) { + output = getField(target.getSuperclass(), name, fieldType, index); + } + + FIELD_ACCESSOR_CACHE.put(cacheKey, output != null ? output : INVALID_FIELD_ACCESSOR); + + if (output == null) { + throw new IllegalArgumentException("Cannot find field with type " + fieldType); + } + + return output; + } + + public static Field getPrivateField(Class cl, String fieldName) { + String cacheKey = constructFieldCacheKey(cl, fieldName); + + Field c = FIELD_CACHE.get(cacheKey); + if (c != null) { + return c != INVALID_FIELD ? c : null; + } + + try { + c = cl.getDeclaredField(fieldName); + c.setAccessible(true); + FIELD_CACHE.put(cacheKey, c); + } + catch (Exception ex) { + System.err.println("Could not retrieve field"); + + FIELD_CACHE.put(cacheKey, INVALID_FIELD); + } + + return c; + } + + public static Method getMethod(Class cl, String method, Class... args) { + String cacheKey = cl.getName() + "." + method + "." + (args == null ? "NONE" : Arrays.toString(args)); + + Method output = METHOD_CACHE.get(cacheKey); + if (output != null) { + return output != INVALID_METHOD ? output : null; + } + + for (Method m : cl.getMethods()) { + if (m.getName().equals(method) && (args == null || classListEqual(args, m.getParameterTypes()))) { + output = m; + break; + } + } + + METHOD_CACHE.put(cacheKey, output == null ? INVALID_METHOD : output); + return output; + } + + public static Method getMethod(Class cl, String method) { + return getMethod(cl, method, null); + } + + public static Constructor getConstructor(Class clazz, Class... arguments) { + for (Constructor constructor : clazz.getDeclaredConstructors()) { + if (Arrays.equals(constructor.getParameterTypes(), arguments)) { + return constructor; + } + } + + return null; + } + + public static boolean classListEqual(Class[] l1, Class[] l2) { + if (l1.length != l2.length) { + return false; + } + + for (int i = 0; i < l1.length; i++) { + if (l1[i] != l2[i]) { + return false; + } + } + + return true; + } + + public interface ConstructorInvoker { + Object invoke(Object... arguments); + } + + public interface MethodInvoker { + Object invoke(Object target, Object... arguments); + } + + public interface FieldAccessor { + T get(Object target); + + void set(Object target, Object value); + + boolean hasField(Object target); + } + + private static class InvalidMarker { + public Void invalidFieldMarker; + public void invalidMethodMaker() {} + } + + private Reflections() {} + +} + diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java new file mode 100644 index 0000000..bfe1722 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java @@ -0,0 +1,27 @@ +package com.modnmetl.virtualrealty.utils; + +public class SafeUtil { + + private static void reportUnsafe(Throwable th) { + try { + throw new Exception(th.getMessage()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static T safeInit(SafeInitializer initializer) { + try { + return initializer.initialize(); + } catch (Exception e) { + reportUnsafe(e); + return null; + } + } + + @FunctionalInterface + public interface SafeInitializer { + T initialize() throws Exception; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java new file mode 100644 index 0000000..28f0670 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java @@ -0,0 +1,150 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.data.Data; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; + +import java.io.*; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.util.*; + +public class SchematicUtil { + + public static String[] getStructure(Block block, Block block2) { + long time = System.currentTimeMillis(); + int minX = Math.min(block.getX(), block2.getX()); + int minZ = Math.min(block.getZ(), block2.getZ()); + int minY = Math.min(block.getY(), block2.getY()); + int maxX = Math.max(block.getX(), block2.getX()); + int maxZ = Math.max(block.getZ(), block2.getZ()); + int maxY = Math.max(block.getY(), block2.getY()); + List blocks = new ArrayList<>(); + for (int x = minX; x <= maxX; ++x) { + for (int y = minY; y <= maxY; ++y) { + for (int z = minZ; z <= maxZ; ++z) { + Block b = block.getWorld().getBlockAt(x, y, z); + if (b.getType() != Material.AIR) { + if (VirtualRealty.isLegacy) { + blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getType().getId() + ";" + b.getData()); + } else { + blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getBlockData().getAsString().substring(10)); + } + } + } + } + } + VirtualRealty.debug("Getted and serialized blocks in: " + (System.currentTimeMillis() - time) + " ms"); + return blocks.toArray(new String[0]); + } + + public static void paste(int plotID, Location l) { + long time = System.currentTimeMillis(); + String[] blocks = load(plotID); + if (blocks == null) return; + Plot plot = PlotManager.getPlot(plotID); + Location location = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderBottomLeftCorner().getBlockX(), plot.getBorderBottomLeftCorner().getBlockY(), plot.getBorderBottomLeftCorner().getBlockZ()); + Location location2 = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderTopRightCorner().getBlockX(), plot.getBorderTopRightCorner().getBlockY(), plot.getBorderTopRightCorner().getBlockZ()); + Block pos1Block = location.getBlock(); + Block pos2Block = location2.getBlock(); + int minX = Math.min(pos1Block.getX(), pos2Block.getX()); + int minZ = Math.min(pos1Block.getZ(), pos2Block.getZ()); + int minY = Math.min(pos1Block.getY(), pos2Block.getY()); + int maxX = Math.max(pos1Block.getX(), pos2Block.getX()); + int maxZ = Math.max(pos1Block.getZ(), pos2Block.getZ()); + int maxY = Math.max(pos1Block.getY(), pos2Block.getY()); + for (int x = minX; x <= maxX; ++x) { + for (int y = minY; y <= maxY; ++y) { + for (int z = minZ; z <= maxZ; ++z) { + Block b = location.getWorld().getBlockAt(x, y, z); + b.setType(Material.AIR); + } + } + } + if (blocks[0].isEmpty()) return; + for (String block : blocks) { + String[] cords = block.split(";"); + int x = Integer.parseInt(cords[0]); + int y = Integer.parseInt(cords[1]); + int z = Integer.parseInt(cords[2]); + Location displaced = l.clone(); + displaced.add(x, y, z); + Block b = displaced.getBlock(); + if (VirtualRealty.isLegacy) { + try { + Method m = Block.class.getDeclaredMethod("setType", Material.class); + m.setAccessible(true); + m.invoke(b, VMaterial.getMaterial(Integer.parseInt(cords[3]))); + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(b, (byte) Integer.parseInt(cords[4])); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + BlockData blockData = Bukkit.createBlockData("minecraft:" + cords[3]); + b.setBlockData(blockData); + } + b.getState().update(true); + } + VirtualRealty.debug("Pasted in: " + (System.currentTimeMillis() - time) + " ms"); + } + + public static void save(int plotID, String[] blocks) { + long time = System.currentTimeMillis(); + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); + + StringBuilder stringBuilder = new StringBuilder(); + for (String s : blocks) { + stringBuilder.append(s).append("|"); + } + String plotString = stringBuilder.toString(); + if (plotString.isEmpty()) + plotString = "clear|"; + try { + new Data().compressData(plotString.substring(0, plotString.length() - 1).getBytes(StandardCharsets.UTF_8), f); + } catch (IOException e) { + e.printStackTrace(); + } + VirtualRealty.debug("Saved in: " + (System.currentTimeMillis() - time) + " ms"); + } + + public static String[] load(int plotID) { + long time = System.currentTimeMillis(); + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); + if (f.exists()) { + String loaded = null; + try { + loaded = new String(new Data().decompressData(f)); + } catch (IOException e) { + e.printStackTrace(); + } + if (loaded.equalsIgnoreCase("clear")) return new String[]{""}; + VirtualRealty.debug("Loaded in: " + (System.currentTimeMillis() - time) + " ms"); + return loaded.split("\\|"); + } + return null; + } + + public static List oldLoad(int plotID) { + File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".schem"); + List loaded = new ArrayList<>(); + try { + FileInputStream streamIn = new FileInputStream(f); + ObjectInputStream objectinputstream = new ObjectInputStream(streamIn); + loaded = (List)objectinputstream.readObject(); + objectinputstream.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return loaded; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/UUIDUtils.java b/src/main/java/com/modnmetl/virtualrealty/utils/UUIDUtils.java new file mode 100644 index 0000000..f39d2a8 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/UUIDUtils.java @@ -0,0 +1,16 @@ +package com.modnmetl.virtualrealty.utils; + +import java.util.UUID; + +public class UUIDUtils { + + public static boolean isValidUUID(String uuidString) { + try { + UUID.fromString(uuidString); + return true; + } catch (Exception e) { + return false; + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/UpdateChecker.java b/src/main/java/com/modnmetl/virtualrealty/utils/UpdateChecker.java new file mode 100644 index 0000000..052b0f4 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/UpdateChecker.java @@ -0,0 +1,39 @@ +package com.modnmetl.virtualrealty.utils; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.modnmetl.virtualrealty.VirtualRealty; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +public class UpdateChecker { + + private static final String VERSION_URL = "https://api.spiget.org/v2/resources/95599/versions/latest"; + private static final String DESCRIPTION_URL = "https://api.spiget.org/v2/resources/95599/updates/latest"; + + public static String[] getUpdate() { + try { + JsonObject latestVersionObj = getURLResults(VERSION_URL); + String newVersion = latestVersionObj.get("name").getAsString(); + JsonObject updateDesc = getURLResults(DESCRIPTION_URL); + String updateName = updateDesc.get("title").getAsString(); + return new String[] { newVersion, updateName }; + } catch (IOException ex) { + VirtualRealty.getInstance().getLogger().severe("Failed to get plugin update information, is Spiget down?"); + return null; + } + } + + private static JsonObject getURLResults(String urlStr) throws IOException { + URL url = new URL(urlStr); + HttpURLConnection connection = (HttpURLConnection)url.openConnection(); + connection.addRequestProperty("User-Agent", "AdvancedTeleportPA"); + return new JsonParser().parse(new InputStreamReader(connection.getInputStream())).getAsJsonObject(); + } + +} + + diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java b/src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java new file mode 100644 index 0000000..f13a3ef --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java @@ -0,0 +1,31 @@ +package com.modnmetl.virtualrealty.utils.data; + +import java.io.*; +import java.util.zip.*; + +public class Data { + + public void compressData(byte[] data, File file) throws IOException { + try (OutputStream outputStream = new FileOutputStream(file)) { + Deflater d = new Deflater(); + DeflaterOutputStream dout = new DeflaterOutputStream(outputStream, d); + dout.write(data); + dout.close(); + } + } + + public byte[] decompressData(File file) throws IOException { + try (InputStream inputStream = new FileInputStream(file)) { + InflaterInputStream newInput = new InflaterInputStream(inputStream); + ByteArrayOutputStream bout = new ByteArrayOutputStream(512); + int b; + while ((b = newInput.read()) != -1) { + bout.write(b); + } + newInput.close(); + bout.close(); + return bout.toByteArray(); + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java new file mode 100644 index 0000000..159f406 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java @@ -0,0 +1,44 @@ +package com.modnmetl.virtualrealty.utils.multiversion; + +import com.modnmetl.virtualrealty.VirtualRealty; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class Chat { + + private final BaseComponent text; + + public Chat(BaseComponent text) { + this.text = text; + } + + public Chat(String text) { + this.text = new TextComponent(text); + } + + public void sendTo(CommandSender sender) { + if (sender instanceof Player) { + Player player = (Player) sender; + if (VirtualRealty.isLegacy) { + try { + Method m = Player.class.getDeclaredMethod("sendMessage", BaseComponent.class); + m.setAccessible(true); + m.invoke(player, text); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } else { + player.spigot().sendMessage(text); + } + } else { + sender.sendMessage(text.toLegacyText()); + } + } + + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java new file mode 100644 index 0000000..feac87d --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java @@ -0,0 +1,60 @@ +package com.modnmetl.virtualrealty.utils.multiversion; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.exceptions.MaterialMatchException; +import org.bukkit.Material; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class VMaterial { + + public static Material getMaterial(int materialID) throws MaterialMatchException { + if (VirtualRealty.isLegacy) { + try { + Method m = Material.class.getDeclaredMethod("getMaterial", int.class); + m.setAccessible(true); + return (Material) m.invoke(Material.class, materialID); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } else { + int counter = 1; + for (Material material : Material.values()) { + if (counter == materialID) { + return material; + } + counter++; + } + } + throw new MaterialMatchException("Couldn't parse material: " + materialID); + } + + public static Material catchMaterial(String material) throws MaterialMatchException { + try { + Method m = Material.class.getDeclaredMethod("getMaterial", String.class); + m.setAccessible(true); + Material mat = (Material) m.invoke(Material.class, material); + if (mat == null) { + throw new MaterialMatchException("Couldn't parse material: \"" + material + "\""); + } + return mat; + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + public static Material getMaterial(String material) { + try { + Method m = Material.class.getDeclaredMethod("getMaterial", String.class); + m.setAccessible(true); + return (Material) m.invoke(Material.class, material); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + +} diff --git a/virtualrealty.iml b/virtualrealty.iml new file mode 100644 index 0000000..84ca1fd --- /dev/null +++ b/virtualrealty.iml @@ -0,0 +1,43 @@ + + + + + + + SPIGOT + BUKKIT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 95ccd3564bdeb442ef25ec6fbd5b7b098effc6bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 27 Jan 2022 15:19:29 +0100 Subject: [PATCH 07/23] Renamed classpath --- .../plytki/virtualrealty/VirtualRealty.java | 560 ------------ .../virtualrealty/commands/PlotCommand.java | 370 -------- .../commands/VirtualRealtyCommand.java | 735 ---------------- .../configs/MessagesConfiguration.java | 69 -- .../configs/PluginConfiguration.java | 172 ---- .../configs/SizesConfiguration.java | 89 -- .../plytki/virtualrealty/enums/Direction.java | 45 - .../me/plytki/virtualrealty/enums/Flag.java | 33 - .../virtualrealty/enums/HighlightType.java | 9 - .../virtualrealty/enums/Permission.java | 24 - .../plytki/virtualrealty/enums/PlotSize.java | 86 -- .../exceptions/MaterialMatchException.java | 9 - .../listeners/ProtectionListener.java | 448 ---------- .../listeners/VirtualListener.java | 22 - .../listeners/plot/BorderListener.java | 44 - .../listeners/plot/PlotListener.java | 100 --- .../listeners/world/WorldListener.java | 49 -- .../virtualrealty/managers/PlotManager.java | 186 ---- .../plytki/virtualrealty/objects/Cuboid.java | 187 ---- .../me/plytki/virtualrealty/objects/Plot.java | 796 ------------------ .../objects/math/BlockVector2.java | 44 - .../objects/math/BlockVector3.java | 59 -- .../registry/VirtualPlaceholders.java | 123 --- .../java/me/plytki/virtualrealty/sql/SQL.java | 125 --- .../utils/ConfigurationFactory.java | 46 - .../virtualrealty/utils/Permissions.java | 27 - .../plytki/virtualrealty/utils/PlotUtil.java | 41 - .../virtualrealty/utils/ProtectionUtil.java | 40 - .../virtualrealty/utils/Reflections.java | 271 ------ .../plytki/virtualrealty/utils/SafeUtil.java | 27 - .../virtualrealty/utils/SchematicUtil.java | 154 ---- .../plytki/virtualrealty/utils/UUIDUtils.java | 16 - .../virtualrealty/utils/UpdateChecker.java | 39 - .../plytki/virtualrealty/utils/data/Data.java | 31 - .../utils/multiversion/Chat.java | 44 - .../utils/multiversion/VMaterial.java | 60 -- 36 files changed, 5180 deletions(-) delete mode 100644 src/main/java/me/plytki/virtualrealty/VirtualRealty.java delete mode 100644 src/main/java/me/plytki/virtualrealty/commands/PlotCommand.java delete mode 100644 src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java delete mode 100644 src/main/java/me/plytki/virtualrealty/configs/MessagesConfiguration.java delete mode 100644 src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java delete mode 100644 src/main/java/me/plytki/virtualrealty/configs/SizesConfiguration.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/Direction.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/Flag.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/HighlightType.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/Permission.java delete mode 100644 src/main/java/me/plytki/virtualrealty/enums/PlotSize.java delete mode 100644 src/main/java/me/plytki/virtualrealty/exceptions/MaterialMatchException.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/ProtectionListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/VirtualListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/plot/BorderListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/plot/PlotListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/listeners/world/WorldListener.java delete mode 100644 src/main/java/me/plytki/virtualrealty/managers/PlotManager.java delete mode 100644 src/main/java/me/plytki/virtualrealty/objects/Cuboid.java delete mode 100644 src/main/java/me/plytki/virtualrealty/objects/Plot.java delete mode 100644 src/main/java/me/plytki/virtualrealty/objects/math/BlockVector2.java delete mode 100644 src/main/java/me/plytki/virtualrealty/objects/math/BlockVector3.java delete mode 100644 src/main/java/me/plytki/virtualrealty/registry/VirtualPlaceholders.java delete mode 100644 src/main/java/me/plytki/virtualrealty/sql/SQL.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/ConfigurationFactory.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/Permissions.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/PlotUtil.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/ProtectionUtil.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/Reflections.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/SafeUtil.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/UUIDUtils.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/UpdateChecker.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/data/Data.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java delete mode 100644 src/main/java/me/plytki/virtualrealty/utils/multiversion/VMaterial.java diff --git a/src/main/java/me/plytki/virtualrealty/VirtualRealty.java b/src/main/java/me/plytki/virtualrealty/VirtualRealty.java deleted file mode 100644 index 3376005..0000000 --- a/src/main/java/me/plytki/virtualrealty/VirtualRealty.java +++ /dev/null @@ -1,560 +0,0 @@ -package me.plytki.virtualrealty; - -import me.plytki.virtualrealty.commands.PlotCommand; -import me.plytki.virtualrealty.commands.VirtualRealtyCommand; -import me.plytki.virtualrealty.configs.MessagesConfiguration; -import me.plytki.virtualrealty.configs.PluginConfiguration; -import me.plytki.virtualrealty.configs.SizesConfiguration; -import me.plytki.virtualrealty.enums.Flag; -import me.plytki.virtualrealty.enums.PlotSize; -import me.plytki.virtualrealty.exceptions.MaterialMatchException; -import me.plytki.virtualrealty.listeners.plot.BorderListener; -import me.plytki.virtualrealty.listeners.plot.PlotListener; -import me.plytki.virtualrealty.listeners.ProtectionListener; -import me.plytki.virtualrealty.listeners.world.WorldListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.registry.VirtualPlaceholders; -import me.plytki.virtualrealty.sql.SQL; -import me.plytki.virtualrealty.utils.ConfigurationFactory; -import me.plytki.virtualrealty.utils.SchematicUtil; -import me.plytki.virtualrealty.utils.UpdateChecker; -import me.plytki.virtualrealty.utils.multiversion.VMaterial; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.LineIterator; -import org.bstats.bukkit.Metrics; -import org.bstats.charts.AdvancedPie; -import org.bstats.charts.SimplePie; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.permissions.Permission; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; -import org.dynmap.DynmapAPI; -import org.dynmap.markers.MarkerIcon; -import org.dynmap.markers.MarkerSet; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.Statement; -import java.util.*; -import java.util.concurrent.Callable; - -public final class VirtualRealty extends JavaPlugin { - - public final Locale locale = Locale.getDefault(); - public final List availableLocales = new ArrayList<>(Arrays.asList(new Locale("en", "GB"), new Locale("es", "ES"), new Locale("pl", "PL"))); - - //CORE - private static VirtualRealty instance; - public static final String PREFIX = "§a§lVR §8§l» §7"; - public static ArrayList tasks = new ArrayList<>(); - private static final ArrayList preVersions = new ArrayList<>(); - public static boolean isLegacy = false; - public static final Permission GLOBAL_PERMISSION = new Permission("virtualrealty"); - - //FILES - public static File plotsFolder; - public static File plotsSchemaFolder; - public PluginConfiguration pluginConfiguration; - public SizesConfiguration sizesConfiguration; - public MessagesConfiguration messagesConfiguration; - private final File pluginConfigurationFile = new File(this.getDataFolder(), "config.yml"); - private final File sizesConfigurationFile = new File(this.getDataFolder(), "sizes.yml"); - private final File languagesDirectory = new File(this.getDataFolder(), "messages"); - - //DYNMAP API - public static boolean isDynmapPresent = false; - public static DynmapAPI dapi = null; - public static MarkerSet markerset = null; - public static MarkerIcon markerIcon = null; - - @Override - public void onEnable() { - instance = this; - if (checkLegacyVersions()) { - isLegacy = true; - } - String[] updateCheck = UpdateChecker.getUpdate(); - if (updateCheck != null) { - if (!updateCheck[0].equals(this.getDescription().getVersion())) { - this.getLogger().info("A newer version is available!"); - this.getLogger().info("The current version you use: " + this.getDescription().getVersion()); - this.getLogger().info("Latest version available: " + updateCheck[0]); - this.getLogger().info("Download link: https://www.spigotmc.org/resources/virtual-realty.95599/"); - } else { - this.getLogger().info("Plugin is up to date!"); - } - } - try { - checkConfig(); - checkSizesConfig(); - } catch (IOException e) { - e.printStackTrace(); - } - plotsFolder = new File(getInstance().getDataFolder().getAbsolutePath(), "plots"); - plotsFolder.mkdirs(); - plotsSchemaFolder = new File(plotsFolder.getAbsolutePath(), "primary-terrain"); - plotsSchemaFolder.mkdirs(); - spawnLocales(); - reformatConfig(); - reloadConfigs(); - registerMetrics(); - loadSizesConfiguration(); - connectToDatabase(); - PlotManager.loadPlots(); - if (pluginConfiguration.dynmapMarkers) { - registerDynmap(); - } - reloadFlags(); - registerCommands(); - registerListeners(); - registerTasks(); - checkForOldSchemas(); - convertOldDatabase(); - if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")){ - new VirtualPlaceholders(this).register(); - debug("Registered new placeholders"); - } - debug("Server version: " + this.getServer().getBukkitVersion() + " | " + this.getServer().getVersion()); - } - - @Override - public void onDisable() { - PlotManager.plots.forEach(Plot::update); - tasks.forEach(BukkitTask::cancel); - SQL.closeConnection(); - if (pluginConfiguration.dataModel == PluginConfiguration.DataModel.H2) { - pluginConfiguration.dataModel = PluginConfiguration.DataModel.SQLITE; - } - pluginConfiguration.save(); - } - - public static void debug(String debugMessage) { - if (VirtualRealty.getPluginConfiguration().debugMode) - VirtualRealty.getInstance().getLogger().warning("DEBUG-MODE > " + debugMessage); - } - - public void spawnLocales() { - for (Locale availableLocale : availableLocales) { - if (availableLocale.toString().equalsIgnoreCase("en_GB")) { - File messagesConfigurationFile = new File(languagesDirectory, "messages_en_GB.yml"); - ConfigurationFactory configFactory = new ConfigurationFactory(); - configFactory.createMessagesConfiguration(messagesConfigurationFile); - } else { - File languageConfigurationFile = new File(languagesDirectory, "messages_" + availableLocale + ".yml"); - if (!languageConfigurationFile.exists()) { - saveResource("messages_" + availableLocale + ".yml", true); - File file = new File(this.getDataFolder(), "messages_" + availableLocale + ".yml"); - try { - FileUtils.moveFile(file, languageConfigurationFile); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - } - - public void convertOldDatabase() { - File oldDatabase = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.mv.db"); - if (oldDatabase.exists()) { - try { - SQL.closeConnection(); - Connection connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.db"); - SQL.setConnection(connection); - Statement statement = connection.createStatement(); - SQL.setStatement(statement); - statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); - for (Plot plot : PlotManager.plots) { - plot.insert(); - } - FileUtils.deleteQuietly(oldDatabase); - debug("H2 database converted successfully to SQLITE"); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void reloadConfigs() { - try { - ConfigurationFactory configFactory = new ConfigurationFactory(); - pluginConfiguration = configFactory.createPluginConfiguration(pluginConfigurationFile); - File messagesConfigurationFile = new File(languagesDirectory, "messages_" + pluginConfiguration.locale + ".yml"); - sizesConfiguration = configFactory.createSizesConfiguration(sizesConfigurationFile); - messagesConfiguration = configFactory.createMessagesConfiguration(messagesConfigurationFile); - } catch (Exception exception) { - exception.printStackTrace(); - } - } - - public void reloadFlags() { - if (pluginConfiguration.allowOutPlotBuild) { - for (Flag.World value : Flag.World.values()) { - value.setAllowed(true); - } - } else { - for (Flag.World value : Flag.World.values()) { - value.setAllowed(false); - } - } - } - - public static void checkForOldSchemas() { - for (Plot plot : PlotManager.plots) { - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plot.getID() + ".schem"); - if (f.exists()) { - List data = SchematicUtil.oldLoad(plot.getID()); - FileUtils.deleteQuietly(f); - SchematicUtil.save(plot.getID(), data.toArray(new String[0])); - debug("Converted Plot #" + plot.getID() + " | File: " + f.getName()); - } - } - } - - public void registerDynmap() { - new BukkitRunnable() { - @Override - public void run() { - Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); - if (plugin != null) { - isDynmapPresent = true; - } - if (plugin != null && plugin.isEnabled()) { - dapi = (DynmapAPI) plugin; - if (dapi.markerAPIInitialized()) { - markerset = dapi.getMarkerAPI().getMarkerSet("virtualrealty.plots"); - if (markerset == null) - markerset = dapi.getMarkerAPI().createMarkerSet("virutalrealty.plots", "Plots", dapi.getMarkerAPI().getMarkerIcons(), false); - for (MarkerSet markerSet : dapi.getMarkerAPI().getMarkerSets()) { - if (markerSet.getMarkerSetLabel().equalsIgnoreCase("Plots")) { - markerset = markerSet; - } - } - try { - if (dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon") == null) { - InputStream in = this.getClass().getResourceAsStream("/ploticon.png"); - if (in.available() > 0) { - markerIcon = dapi.getMarkerAPI().createMarkerIcon("virtualrealty_main_icon", "Plots", in); - } - } - else { - markerIcon = dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon"); - } - } - catch (IOException ex) {} - VirtualRealty.debug("Registering plots markers.."); - for (Plot plot : PlotManager.plots) { - PlotManager.resetPlotMarker(plot); - } - VirtualRealty.debug("Registered plots markers"); - this.cancel(); - } - } - } - }.runTaskTimer(this, 20, 20*5); - } - - - private void registerCommands() { - this.getCommand("plot").setExecutor(new PlotCommand()); - this.getCommand("virtualrealty").setExecutor(new VirtualRealtyCommand()); - } - - private void registerListeners() { - new BorderListener(this).registerEvents(); - new PlotListener(this).registerEvents(); - new ProtectionListener(this).registerEvents(); - new WorldListener(this).registerEvents(); - debug("Registered listeners"); - } - - private void registerTasks() { - //debug("Registered tasks"); - } - - private void registerMetrics() { - Metrics metrics = new Metrics(this, 12578); - metrics.addCustomChart(new SimplePie("used_database", () -> pluginConfiguration.dataModel.name())); - metrics.addCustomChart(new AdvancedPie("created_plots", new Callable>() { - @Override - public Map call() throws Exception { - Map valueMap = new HashMap(); - int smallPlots = 0; - int mediumPlots = 0; - int largePlots = 0; - int customPlots = 0; - for (Plot plot : PlotManager.plots) { - switch (plot.getPlotSize()) { - case SMALL: { - smallPlots++; - break; - } - case MEDIUM: { - mediumPlots++; - break; - } - case LARGE: { - largePlots++; - break; - } - case CUSTOM: { - customPlots++; - break; - } - default: - throw new IllegalStateException("Unexpected value: " + plot.getPlotSize()); - } - } - valueMap.put("SMALL", smallPlots); - valueMap.put("MEDIUM", mediumPlots); - valueMap.put("LARGE", largePlots); - valueMap.put("CUSTOM", customPlots); - return valueMap; - } - })); - debug("Registered metrics"); - } - - private void connectToDatabase() { - SQL.connect(); - SQL.createTables(); - debug("Connected to database"); - } - - public void loadSizesConfiguration() { - for (PlotSize plotSize : PlotSize.values()) { - if (plotSize == PlotSize.CUSTOM) return; - SizesConfiguration.PlotSizes.Size classSize = null; - switch (plotSize) { - case SMALL: { - classSize = sizesConfiguration.plotSizes.SMALL; - break; - } - case MEDIUM: { - classSize = sizesConfiguration.plotSizes.MEDIUM; - break; - } - case LARGE: { - classSize = sizesConfiguration.plotSizes.LARGE; - break; - } - } - Material floorMaterial; - try { - floorMaterial = VMaterial.catchMaterial(classSize.floorMaterial.toUpperCase()); - } catch (MaterialMatchException e) { - floorMaterial = VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK; - e.printStackTrace(); - //throw new MaterialMatchException("Couldn't parse floor-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK)); - } - Material borderMaterial; - try { - borderMaterial = VMaterial.catchMaterial(classSize.borderMaterial.toUpperCase()); - } catch (MaterialMatchException e) { - borderMaterial = VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB; - e.printStackTrace(); - //throw new MaterialMatchException("Couldn't parse border-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB)); - } - plotSize.setFloorMaterial(floorMaterial); - plotSize.setFloorData(classSize.floorData); - plotSize.setBorderMaterial(borderMaterial); - plotSize.setBorderData(classSize.borderData); - plotSize.setLength(classSize.length); - plotSize.setWidth(classSize.width); - plotSize.setHeight(classSize.height); - } - debug("Loaded sizes config"); - } - - public static VirtualRealty getInstance() { - return instance; - } - - public static PluginConfiguration getPluginConfiguration() { - return VirtualRealty.getInstance().pluginConfiguration; - } - - public static File getPluginConfigurationFile() { - return VirtualRealty.getInstance().pluginConfigurationFile; - } - - public static SizesConfiguration getSizesConfiguration() { - return VirtualRealty.getInstance().sizesConfiguration; - } - - public static File getSizesConfigurationFile() { - return VirtualRealty.getInstance().sizesConfigurationFile; - } - - public static MessagesConfiguration getMessages() { - return getInstance().messagesConfiguration; - } - - public boolean checkLegacyVersions() { - setPostVersions(); - for (String preVersion : preVersions) { - if (Bukkit.getBukkitVersion().toLowerCase().contains(preVersion.toLowerCase())) { - return true; - } - } - return false; - } - - public static Locale getLocale() { - return getInstance().locale; - } - - public void setPostVersions() { - preVersions.add("1.12"); - preVersions.add("1.11"); - preVersions.add("1.10"); - preVersions.add("1.9"); - preVersions.add("1.8"); - } - - public void reformatConfig() { - File configFile = new File(this.getDataFolder(), "config.yml"); - File newFile = new File(this.getDataFolder(), "config.yml.new"); - if (configFile.exists()) { - try { - List lines = FileUtils.readLines(configFile, StandardCharsets.UTF_8); - for (int i = 0; i < lines.size(); i++) { - if (lines.get(i).startsWith("force-plot-gamemode:")) { - lines.set(i, lines.get(i).replaceAll("force-plot-gamemode:", "lock-plot-gamemode:")); - } - } - FileUtils.writeLines(newFile, lines); - FileUtils.deleteQuietly(configFile); - newFile.createNewFile(); - File newConfigFile = new File(this.getDataFolder(), "config.yml"); - FileUtils.copyFile(newFile, newConfigFile); - FileUtils.deleteQuietly(newFile); - } catch (IOException e) { - - } - } - } - - public void checkConfig() throws IOException { - File oldConfigFile = new File(this.getDataFolder(), "config.yml"); - if (!oldConfigFile.exists()) return; - String version = null; - boolean isOldVersion = true; - boolean updateConfigVersion = false; - FileReader fileReader = new FileReader(this.pluginConfigurationFile); - BufferedReader reader = new BufferedReader(fileReader); - String latestLine; - while((latestLine = reader.readLine()) != null) { - if (latestLine.contains("config-version")) { - version = latestLine.replaceAll("config-version: ", ""); - isOldVersion = false; - } - } - fileReader.close(); - reader.close(); - if (version == null) { - System.err.println(" "); - this.getLogger().warning("Config has been reset due to major config changes!"); - this.getLogger().warning("Old config has been renamed to config.yml.old"); - this.getLogger().warning("Please update your config file!"); - System.err.println(" "); - } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { - updateConfigVersion = true; - this.getLogger().info("Config has been updated!"); - } - - // save old config file - if (isOldVersion) { - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml.old"); - if (newConfigFile.exists()) { - newConfigFile.delete(); - } - FileUtils.copyFile(oldConfigFile, newConfigFile); - oldConfigFile.delete(); - } - -// update config version - if (updateConfigVersion) { - List lines = new ArrayList<>(); - LineIterator iterator = FileUtils.lineIterator(oldConfigFile); - while (iterator.hasNext()) { - String line = iterator.next(); - lines.add(line); - } - for (String line : new ArrayList<>(lines)) { - if (line.contains("config-version")) { - int index = lines.indexOf(line); - lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); - } - } - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml"); - FileUtils.deleteQuietly(newConfigFile); - FileUtils.writeLines(newConfigFile, lines); - newConfigFile.createNewFile(); - } - } - - public void checkSizesConfig() throws IOException { - File oldConfigFile = new File(this.getDataFolder(), "sizes.yml"); - if (!oldConfigFile.exists()) return; - String version = null; - boolean isOldVersion = true; - boolean updateConfigVersion = false; - BufferedReader reader = new BufferedReader(new FileReader(this.sizesConfigurationFile)); - String latestLine; - while((latestLine = reader.readLine()) != null) { - if (latestLine.contains("config-version")) { - version = latestLine.replaceAll("config-version: ", ""); - isOldVersion = false; - } - } - reader.close(); - if (version == null) { - System.err.println(" "); - this.getLogger().warning("Config has been reset due to major config changes!"); - this.getLogger().warning("Old config has been renamed to sizes.yml.old"); - this.getLogger().warning("Please update your config file!"); - System.err.println(" "); - } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { - updateConfigVersion = true; - this.getLogger().info("Plot sizes config has been updated!"); - } - - // save old config file - if (isOldVersion) { - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml.old"); - if (newConfigFile.exists()) { - newConfigFile.delete(); - } - FileUtils.copyFile(oldConfigFile, newConfigFile); - oldConfigFile.delete(); - } - - // update config version - if (updateConfigVersion) { - List lines = new ArrayList<>(); - LineIterator iterator = FileUtils.lineIterator(oldConfigFile); - while (iterator.hasNext()) { - String line = iterator.next(); - lines.add(line); - } - for (String line : new ArrayList<>(lines)) { - if (line.contains("config-version")) { - int index = lines.indexOf(line); - lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); - } - } - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml"); - FileUtils.deleteQuietly(newConfigFile); - FileUtils.writeLines(newConfigFile, lines); - newConfigFile.createNewFile(); - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/commands/PlotCommand.java b/src/main/java/me/plytki/virtualrealty/commands/PlotCommand.java deleted file mode 100644 index 71aca23..0000000 --- a/src/main/java/me/plytki/virtualrealty/commands/PlotCommand.java +++ /dev/null @@ -1,370 +0,0 @@ -package me.plytki.virtualrealty.commands; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.UUID; - -public class PlotCommand implements CommandExecutor { - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (!(sender instanceof Player)) { - return false; - } - Player p = ((Player) sender); - if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { - printHelp(sender); - return false; - } - if (args.length == 1) { - switch (args[0].toUpperCase()) { - case "ADD": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot add §8<§7player§8> §8<§7plot§8>"); - break; - } - case "KICK": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot kick §8<§7player§8> §8<§7plot§8>"); - break; - } - case "TP": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot tp §8<§7plotID§8>"); - break; - } - case "GM": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot gm §8<§7gamemode§8>"); - break; - } - case "INFO": { - Plot plot = PlotManager.getPlot(p.getLocation()); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); - return false; - } - printInfo(sender, plot); - break; - } - case "LIST": { - boolean hasPlot = false; - for (Plot plot : PlotManager.plots) { - if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()) && plot.getOwnedUntilDate().isAfter(LocalDateTime.now())) { - hasPlot = true; - break; - } - } - boolean isMember = false; - for (Plot plot : PlotManager.plots) { - if (plot.getMembers().contains(p.getUniqueId())) { - isMember = true; - break; - } - } - if (!hasPlot && !isMember) { - sender.sendMessage(VirtualRealty.PREFIX + "§cYou don't have any plots!"); - return false; - } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" "); - if (hasPlot) { - sender.sendMessage("§7§m "); - sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); - for (Plot plot : PlotManager.plots) { - if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - StringBuilder ownedBy = new StringBuilder(); - ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); - boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); - for (int i = ownedBy.length(); i < 16; i++) { - ownedBy.append(" "); - } - StringBuilder size = new StringBuilder(plot.getPlotSize().name()); - for (int i = size.length(); i < 6; i++) { - size.append(" "); - } - BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); - sender.sendMessage(textComponent.toLegacyText()); - } - } - sender.sendMessage("§7§m "); - } - if (isMember) { - sender.sendMessage(" "); - sender.sendMessage("§7 §fMember of §8§l↴"); - sender.sendMessage(" "); - sender.sendMessage("§7§m "); - sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); - for (Plot plot : PlotManager.plots) { - if (plot.getPlotOwner() != null && !plot.getPlotOwner().getUniqueId().equals(p.getUniqueId()) && plot.getMembers().contains(p.getUniqueId())) { - StringBuilder ownedBy = new StringBuilder(); - ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); - boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); - for (int i = ownedBy.length(); i < 16; i++) { - ownedBy.append(" "); - } - StringBuilder size = new StringBuilder(plot.getPlotSize().name()); - for (int i = size.length(); i < 6; i++) { - size.append(" "); - } - BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + ownedBy + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); - sender.sendMessage(textComponent.toLegacyText()); - } - } - sender.sendMessage("§7§m "); - } - break; - } - default: { - printHelp(sender); - } - } - } - if (args.length >= 2) { - switch (args[0].toUpperCase()) { - case "ADD": { - if (args.length == 3) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[2]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); - return false; - } - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - return false; - } - if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantAddYourself); - return false; - } - if (plot.getMembers().contains(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().alreadyInMembers); - return false; - } - plot.addMember(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerAdd.replaceAll("%player%", offlinePlayer.getName())); - return false; - } - break; - } - case "KICK": { - if (args.length == 3) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[2]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); - return false; - } - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - return false; - } - if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantKickYourself); - return false; - } - if (!plot.getMembers().contains(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notInMembers); - return false; - } - plot.removeMember(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerKick.replaceAll("%player%", offlinePlayer.getName())); - return false; - } - break; - } - case "TP": { - if (args.length == 2) { - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (!plot.hasPlotMembership(p)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); - return false; - } - if (plot.isOwnershipExpired()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - return false; - } - Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); - loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); - p.teleport(loc); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); - } - break; - } - case "GM": { - if (VirtualRealty.getPluginConfiguration().lockPlotGameMode) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeFeatureDisabled); - return false; - } - GameMode gameMode; - int gameModeID; - try { - gameMode = GameMode.valueOf(args[1]); - gameModeID = gameMode.getValue(); - } catch (IllegalArgumentException e) { - try { - gameModeID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException ex) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().incorrectGamemode); - return false; - } - } - GameMode defaultGamemode = VirtualRealty.getInstance().getServer().getDefaultGameMode(); - GameMode configGamemode = VirtualRealty.getPluginConfiguration().getGameMode(); - if (!(gameModeID != configGamemode.getValue() && gameModeID != defaultGamemode.getValue())) { - gameMode = GameMode.getByValue(Integer.parseInt(args[1])); - } else { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeDisabled); - return false; - } - Plot plot = PlotManager.getBorderedPlot(p.getLocation()); - if (plot != null) { - if (!plot.hasPlotMembership(p)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); - } else { - if (plot.isOwnershipExpired()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } else { - if (p.getGameMode().equals(gameMode)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeAlreadySelected); - return false; - } - if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { - plot.setSelectedGameMode(gameMode); - } - p.setGameMode(gameMode); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeSwitched); - } - } - } else { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); - } - break; - } - default: { - printHelp(sender); - } - } - } - return false; - } - - private static void printHelp(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot add §8- §7Adds a member"); - sender.sendMessage(" §a/plot kick §8- §7Kicks a member"); - sender.sendMessage(" §a/plot list §8- §7Shows your plots"); - sender.sendMessage(" §a/plot info §8- §7Shows plot info"); - sender.sendMessage(" §a/plot gm §8- §7Changes gamemode"); - sender.sendMessage(" §a/plot tp §8- §7Teleports to the plot"); - } - - private static void printInfo(CommandSender sender, Plot plot) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); -// String assignedBy = VirtualRealty.getMessages().notAssigned; -// if (plot.getAssignedBy() != null) { -// switch (plot.getAssignedBy().toUpperCase()) { -// case "CONSOLE": { -// assignedBy = VirtualRealty.getMessages().assignedByConsole; -// break; -// } -// case "SHOP_PURCHASE": { -// assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; -// break; -// } -// default: { -// OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); -// assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); -// } -// } -// } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); - sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); - if (plot.getMembers().size() != 0) { - sender.sendMessage(" §7Members §8§l↴"); - for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { - sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); - } - } - //sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); - sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); - sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); - sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); - sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); - sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); - //sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); - //sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); - //sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); - //sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); - //sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java b/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java deleted file mode 100644 index b790ba2..0000000 --- a/src/main/java/me/plytki/virtualrealty/commands/VirtualRealtyCommand.java +++ /dev/null @@ -1,735 +0,0 @@ -package me.plytki.virtualrealty.commands; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Direction; -import me.plytki.virtualrealty.enums.PlotSize; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.utils.ConfigurationFactory; -import me.plytki.virtualrealty.utils.Permissions; -import me.plytki.virtualrealty.utils.PlotUtil; -import me.plytki.virtualrealty.utils.UUIDUtils; -import me.plytki.virtualrealty.utils.multiversion.Chat; -import me.plytki.virtualrealty.utils.multiversion.VMaterial; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.*; -import org.bukkit.entity.Player; -import org.bukkit.permissions.Permission; -import org.jetbrains.annotations.NotNull; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.UUID; - -public class VirtualRealtyCommand implements CommandExecutor { - - private static final Permission commandPermission = new Permission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".vrplot"); - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - Permission tempPermission = new Permission(commandPermission.getName()); - if (!Permissions.hasPermission(sender, tempPermission.getName())) return false; - Player p = null; - Location location = null; - if(sender instanceof Player) { - p = (Player)sender; - location = p.getLocation(); - location.add(0, -1, 0); - } - if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { - printHelp(sender); - return false; - } - if (args.length == 1) { - switch (args[0].toUpperCase()) { - case "CREATE": { - if (!Permissions.hasPermission(sender, tempPermission, "create")) return false; - if (sender instanceof Player) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot create §8<§7small/medium/large§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); - sender.sendMessage(" §a/vrplot create §8<§7length§8> §8<§7width§8> §8<§7height§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); - } - break; - } - case "REMOVE": { - if (!Permissions.hasPermission(sender, tempPermission, "remove")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot remove §8<§7plotID§8>"); - break; - } - case "SET": { - if (!Permissions.hasPermission(sender, tempPermission, "set")) return false; - printSetHelp(sender); - break; - } - case "ASSIGN": { - if (!Permissions.hasPermission(sender, tempPermission, "assign")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot assign §8<§7plotID§8> §8<§7username§8>"); - break; - } - case "UNASSIGN": { - if (!Permissions.hasPermission(sender, tempPermission, "unassign")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot unassign §8<§7plotID§8>"); - break; - } - case "INFO": { - if (!Permissions.hasPermission(sender, tempPermission, "info")) return false; - Plot plot = PlotManager.getPlot(p.getLocation()); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); - return false; - } - printInfo(sender, plot); - break; - } - case "LIST": { - if (!Permissions.hasPermission(sender, tempPermission, "list")) return false; - if (PlotManager.plots.isEmpty()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); - return false; - } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" "); - sender.sendMessage("§7§m "); - sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); - for (Plot plot : PlotManager.plots) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - StringBuilder ownedBy = new StringBuilder(); - ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); - boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); - for (int i = ownedBy.length(); i < 16; i++) { - ownedBy.append(" "); - } - StringBuilder size = new StringBuilder(plot.getPlotSize().name()); - for (int i = size.length(); i < 6; i++) { - size.append(" "); - } - BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + ownedBy.substring(0, 14) + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); - textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); - textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - new Chat(textComponent).sendTo(sender); - } - sender.sendMessage("§7§m "); - break; - } - case "TP": { - if (!Permissions.hasPermission(sender, tempPermission, "tp")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot tp §8<§7plotID§8>"); - break; - } - case "RELOAD": { - if (!Permissions.hasPermission(sender, tempPermission, "reload")) return false; - try { - VirtualRealty.getInstance().reloadConfigs(); - if (VirtualRealty.getPluginConfiguration().dynmapMarkers) { - if (VirtualRealty.markerset != null) { - VirtualRealty.markerset.deleteMarkerSet(); - } - VirtualRealty.getInstance().registerDynmap(); - for (Plot plot : PlotManager.plots) { - PlotManager.resetPlotMarker(plot); - } - } else { - if (VirtualRealty.markerset != null) { - VirtualRealty.markerset.deleteMarkerSet(); - } - } - PlotManager.loadPlots(); - VirtualRealty.getInstance().reloadFlags(); - VirtualRealty.getInstance().loadSizesConfiguration(); - } catch (Exception exception) { - exception.printStackTrace(); - } - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().reloadCompleted); - break; - } - default: { - printHelp(sender); - break; - } - } - } - if (args.length > 1) { - switch (args[0].toUpperCase()) { - case "CREATE": { - if (!Permissions.hasPermission(sender, commandPermission, "create")) return false; - if (sender instanceof Player) { - if (Arrays.stream(PlotSize.values()).anyMatch(plotSize -> plotSize.name().equalsIgnoreCase(args[1])) && !args[1].equalsIgnoreCase(PlotSize.CUSTOM.name())) { - PlotSize plotSize = null; - try { - plotSize = PlotSize.valueOf(args[1].toUpperCase()); - } catch (IllegalArgumentException ignored) { - } - if (plotSize != null) { - if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), plotSize.getLength(), plotSize.getWidth(), plotSize.getHeight()))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); - return false; - } else { - Material floorMaterial = null; - byte floorData = 0; - if (args.length >= 3) { - try { - floorMaterial = VMaterial.getMaterial(args[2].split(":")[0].toUpperCase()); - if (floorMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - if (args[2].split(":").length == 2) { - floorData = Byte.parseByte(args[2].split(":")[1]); - } - } - Material borderMaterial = null; - byte borderData = 0; - if (args.length >= 4) { - try { - borderMaterial = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); - if (borderMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - if (args[3].split(":").length == 2) { - borderData = Byte.parseByte(args[3].split(":")[1]); - } - } - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); - long timeStart = System.currentTimeMillis(); - Plot plot = PlotManager.createPlot(location, plotSize); - if (floorMaterial != null) { - plot.setFloorMaterial(floorMaterial, floorData); - } - if (borderMaterial != null) { - plot.setBorder(borderMaterial, borderData); - } - long timeEnd = System.currentTimeMillis(); - BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); - BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); - BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); - textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); - textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - textComponent.addExtra(textComponent2); - textComponent.addExtra(textComponent3); - new Chat(textComponent).sendTo(p); - } - } else { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().sizeNotRecognised); - return false; - } - } else { - int length; - int width; - int height; - try { - length = Integer.parseInt(args[1]); - width = Integer.parseInt(args[2]); - height = Integer.parseInt(args[3]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - if (length > 500 || width > 500 || height > 500) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().LWHHardLimit); - return false; - } - if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), length, width, height))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); - return false; - } else { - Material floorMaterial = null; - byte floorData = 0; - if (args.length >= 5) { - try { - floorMaterial = VMaterial.getMaterial(args[4].split(":")[0].toUpperCase()); - if (floorMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - if (args[4].split(":").length == 2) { - floorData = Byte.parseByte(args[4].split(":")[1]); - } - } - Material borderMaterial = null; - byte borderData = 0; - if (args.length >= 6) { - try { - borderMaterial = VMaterial.getMaterial(args[5].split(":")[0].toUpperCase()); - if (borderMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - if (args[5].split(":").length == 2) { - borderData = Byte.parseByte(args[5].split(":")[1]); - } - } - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); - long timeStart = System.currentTimeMillis(); - Plot plot = PlotManager.createPlot(location, length, width, height); - if (floorMaterial != null) { - plot.setFloorMaterial(floorMaterial, floorData); - } - if (borderMaterial != null) { - plot.setBorder(borderMaterial, borderData); - } - long timeEnd = System.currentTimeMillis(); - BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); - BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); - BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); - textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); - textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - textComponent.addExtra(textComponent2); - textComponent.addExtra(textComponent3); - new Chat(textComponent).sendTo(p); - } - } - } - break; - } - case "REMOVE": { - if (!Permissions.hasPermission(sender, commandPermission, "remove")) return false; - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - plot.remove(); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().removedPlot); - break; - } - case "SET": { - if (!Permissions.hasPermission(sender, commandPermission, "set")) return false; - if (args.length >= 3) { - switch (args[2].toUpperCase()) { - case "OWNEDBY": { - if (!Permissions.hasPermission(sender, commandPermission, "set.ownedby")) return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyUsername); - return false; - } - int plotID; - OfflinePlayer offlinePlayer; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - try { - if (UUIDUtils.isValidUUID(args[3])) { - offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[3])); - } else { - offlinePlayer = Bukkit.getOfflinePlayer(args[3]); - } - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - } catch (NullPointerException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (args.length >= 5) { - String dateFormat = args[4]; - String timeFormat; - int year; - int month; - int dayOfMonth; - int hour = 0; - int minute = 0; - LocalDateTime localDateTime; - try { - year = Integer.parseInt(dateFormat.split("/")[2]); - month = Integer.parseInt(dateFormat.split("/")[1]); - dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); - if (args.length >= 6) { - timeFormat = args[5]; - hour = Integer.parseInt(timeFormat.split(":")[0]); - minute = Integer.parseInt(timeFormat.split(":")[1]); - } - localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); - return false; - } - plot.setOwnedUntilDate(localDateTime); - } - if (sender instanceof RemoteConsoleCommandSender && args.length >= 7 && args[6].equalsIgnoreCase("assign")) { - plot.setAssignedBy("SHOP_PURCHASE"); - } - plot.setOwnedBy(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedTo.replaceAll("%assigned_to%", offlinePlayer.getName())); - plot.update(); - break; - } - case "FLOORMATERIAL": { - if (!Permissions.hasPermission(sender, commandPermission, "set.floormaterial")) return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Material material; - try { - material = Material.matchMaterial(args[3].split(":")[0].toUpperCase()); - if (material == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - byte data = 0; - if (args[3].split(":").length == 2) { - data = Byte.parseByte(args[3].split(":")[1]); - } - plot.setFloorMaterial(material, data); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newFloorMaterialSet); - plot.update(); - break; - } - case "BORDERMATERIAL": { - if (!Permissions.hasPermission(sender, commandPermission, "set.bordermaterial")) - return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Material material; - try { - material = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); - if (material == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - byte data = 0; - if (args[3].split(":").length == 2) { - data = Byte.parseByte(args[3].split(":")[1]); - } - plot.setBorder(material, data); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newBorderMaterialSet); - plot.update(); - return false; - } - case "OWNERSHIPEXPIRES": { - if (!Permissions.hasPermission(sender, commandPermission, "set.ownerexpires")) return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyExpiryDate); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - String dateFormat = args[3]; - String timeFormat; - int year; - int month; - int dayOfMonth; - int hour = 0; - int minute = 0; - LocalDateTime localDateTime; - try { - year = Integer.parseInt(dateFormat.split("/")[2]); - month = Integer.parseInt(dateFormat.split("/")[1]); - dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); - if (args.length == 5) { - timeFormat = args[4]; - hour = Integer.parseInt(timeFormat.split(":")[0]); - minute = Integer.parseInt(timeFormat.split(":")[1]); - } - localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - plot.setOwnedUntilDate(localDateTime); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownedUntilUpdated); - plot.update(); - break; - } - default: { - printSetHelp(sender); - break; - } - } - } else { - printSetHelp(sender); - } - break; - } - case "ASSIGN": { - if (!Permissions.hasPermission(sender, commandPermission, "assign")) return false; - if (args.length == 3) { - int plotID; - OfflinePlayer offlinePlayer; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - try { - if (UUIDUtils.isValidUUID(args[2])) { - offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[2])); - } else { - offlinePlayer = Bukkit.getOfflinePlayer(args[2]); - } - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - } catch (NullPointerException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (sender instanceof Player) { - plot.setAssignedBy(p.getUniqueId().toString()); - } else if (sender instanceof ConsoleCommandSender){ - plot.setAssignedBy("CONSOLE"); - } else { - plot.setAssignedBy("SHOP_PURCHASE"); - } - plot.setOwnedBy(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedToBy.replaceAll("%assigned_to%", offlinePlayer.getName()).replaceAll("%assigned_by%", sender.getName())); - plot.update(); - } - break; - } - case "UNASSIGN": { - if (!Permissions.hasPermission(sender, commandPermission, "unassign")) return false; - if (args.length == 2) { - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - plot.setAssignedBy(null); - plot.setOwnedBy(null); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().unassigned); - plot.update(); - } - break; - } - case "INFO": { - if (!Permissions.hasPermission(sender, commandPermission, "info")) return false; - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - if (PlotManager.plots.isEmpty()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); - return false; - } - if (plotID < PlotManager.getPlotMinID()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().minPlotID.replaceAll("%min_id%", String.valueOf(PlotManager.getPlotMinID()))); - return false; - } - if (plotID > PlotManager.getPlotMaxID()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().maxPlotID.replaceAll("%max_id%", String.valueOf(PlotManager.getPlotMaxID()))); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - printInfo(sender, plot); - break; - } - case "TP": { - if (!Permissions.hasPermission(sender, commandPermission, "tp")) return false; - if (!(sender instanceof Player)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cmdOnlyPlayers); - return false; - } - if (args.length == 2) { - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); - loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); - p.teleport(loc); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); - } - break; - } - default: { - printHelp(sender); - break; - } - } - } - return false; - } - - private static void printInfo(CommandSender sender, Plot plot) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); - String assignedBy = VirtualRealty.getMessages().notAssigned; - if (plot.getAssignedBy() != null) { - switch (plot.getAssignedBy().toUpperCase()) { - case "CONSOLE": { - assignedBy = VirtualRealty.getMessages().assignedByConsole; - break; - } - case "SHOP_PURCHASE": { - assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; - break; - } - default: { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); - assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); - } - } - } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); - sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); - if (plot.getMembers().size() != 0) { - sender.sendMessage(" §7Members §8§l↴"); - for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { - sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); - } - } - sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); - sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); - sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); - sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); - sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); - sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); - sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); - sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); - sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); - sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); - sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); - } - - private static void printHelp(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot create §8- §7Creates a plot"); - sender.sendMessage(" §a/vrplot remove §8- §7Removes a plot"); - sender.sendMessage(" §a/vrplot set §8- §7Sets a variable for the plot"); - sender.sendMessage(" §a/vrplot assign §8- §7Assigns a plot to player"); - sender.sendMessage(" §a/vrplot unassign §8- §7Sets assigned to and assigned by to null"); - sender.sendMessage(" §a/vrplot info §8- §7Prints info about plot"); - sender.sendMessage(" §a/vrplot list §8- §7Prints all plots"); - sender.sendMessage(" §a/vrplot tp §8- §7Teleports to the plot"); - sender.sendMessage(" §a/vrplot reload §8- §7Reloads plugin"); - } - - private static void printSetHelp(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownedBy §8<§7username§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7floorMaterial §8<§7material§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7borderMaterial §8<§7material§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownershipExpires §8<§7dd/mm/YYYY§8> §8<§7HH:mm (optional)§8>"); - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/configs/MessagesConfiguration.java b/src/main/java/me/plytki/virtualrealty/configs/MessagesConfiguration.java deleted file mode 100644 index cdfa228..0000000 --- a/src/main/java/me/plytki/virtualrealty/configs/MessagesConfiguration.java +++ /dev/null @@ -1,69 +0,0 @@ -package me.plytki.virtualrealty.configs; - -import eu.okaeri.configs.OkaeriConfig; - -public class MessagesConfiguration extends OkaeriConfig { - - public String useNaturalNumbersOnly = "§cUse only natural numbers!"; - public String noPlotFound = "§cCouldn't get plot with specified ID!"; - public String notYourPlot = "§cIt's not your plot!"; - public String ownershipExpired = "§cYour ownership has expired!"; - public String teleportedToPlot = "§aYou have been teleported to the plot!"; - public String gamemodeFeatureDisabled = "§cGamemode feature is disabled!"; - public String incorrectGamemode = "§cIncorrect gamemode value!"; - public String gamemodeDisabled = "§cThis gamemode is disabled!"; - public String cantSwitchGamemode = "§cYou can't switch gamemode here!"; - public String notStandingOnPlot = "§cYou aren't standing on any plot!"; - public String assignedByConsole = "§eConsole"; - public String assignedByShopPurchase = "§eShop Purchase"; - public String noPlots = "§cThere are no plots!"; - public String available = "§cAvailable"; - public String reloadCompleted = "§aReload completed!"; - public String cantCreateOnExisting = "§cYou can't create new plot over an existing plot!"; - public String cantGetFloorMaterial = "§cCouldn't get floor material with specified name!"; - public String cantGetBorderMaterial = "§cCouldn't get border material with specified name!"; - public String cantGetMaterial = "§cCouldn't get material with specified name!"; - public String notCollidingCreating = "§aNot colliding. Creating plot.."; - public String clickToShowDetailedInfo = "§a§oClick to show detailed information about the plot! §8(§7ID: §f%plot_id%§8)"; - public String sizeNotRecognised = "§cSize not recognized!"; - public String LWHHardLimit = "§cL, W and H hard-limit is 500!"; - public String removedPlot = "§aSuccessfully removed plot!"; - public String specifyUsername = "§cSpecify username!"; - public String playerNotFoundWithUsername = "§cCouldn't find player with specified username!"; - public String invalidDateProvided = "§cInvalid date format provided!"; - public String assignedTo = "§aPlot has been assigned to §f%assigned_to%!"; - public String specifyMaterialName = "§cSpecify material name!"; - public String specifyExpiryDate = "§cSpecify expiry date!"; - public String newFloorMaterialSet = "§aNew floor material has been set!"; - public String newBorderMaterialSet = "§aNew border material has been set!"; - public String ownedUntilUpdated = "§aOwned until date has been updated!"; - public String assignedToBy = "§aPlot has been assigned to §f%assigned_to% §aby §f%assigned_by%!"; - public String notAssigned = "§cNot assigned"; - public String unassigned = "§aPlot has been unassigned!"; - public String minPlotID = "§cMinimum plot ID is %min_id%!"; - public String maxPlotID = "§cMaximum plot ID is %max_id%!"; - public String cmdOnlyPlayers = "§cCommand only for players!"; - - public String enteredAvailablePlot = "§2You have entered an available plot!"; - public String enteredOwnedPlot = "§7You have entered §2%owner%'s §7plot!"; - public String leftAvailablePlot = "§cYou have left an available plot!"; - public String leftOwnedPlot = "§7You have left §2%owner%'s §7plot!"; - public String cantInteract = "§cYou can't interact here!"; - public String cantBuildHere = "§cYou can't build here!"; - public String cantRideOnPlot = "§cYou can't ride on someones plot!"; - - public String creationPlotComponent1 = "§aPlot "; - public String creationPlotComponent2 = "§8#§7%plot_id%"; - public String creationPlotComponent3 = " §acreated! §8(§7%creation_time% ms§8)"; - - public String cantAddYourself = "§cYou can't add yourself to the plot!"; - public String cantKickYourself = "§cYou can't kick yourself from the plot!"; - public String alreadyInMembers = "§cThis player is already one of the plot members!"; - public String notInMembers = "§cThis player is not one of the plot members!"; - public String cantDoAnyDMG = "§cYou can't do any damage here!"; - public String playerKick = "§aPlayer §7%player% §ahas been kicked out of your plot!"; - public String playerAdd = "§aPlayer §7%player% §ahas been added to your plot!"; - public String gamemodeSwitched = "§aYour gamemode has changed!"; - public String gamemodeAlreadySelected = "§cThis gamemode is already selected!"; - -} diff --git a/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java b/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java deleted file mode 100644 index fcf9693..0000000 --- a/src/main/java/me/plytki/virtualrealty/configs/PluginConfiguration.java +++ /dev/null @@ -1,172 +0,0 @@ -package me.plytki.virtualrealty.configs; - -import eu.okaeri.configs.OkaeriConfig; -import eu.okaeri.configs.annotation.*; -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.HighlightType; -import org.bukkit.GameMode; - -@Header("################################################################") -@Header("# #") -@Header("# Virtual Realty #") -@Header("# #") -@Header("################################################################") -@Names(strategy = NameStrategy.IDENTITY, modifier = NameModifier.TO_LOWER_CASE) -public class PluginConfiguration extends OkaeriConfig { - - @Comment(" ") - @Comment("-------------------------") - @Comment("Don't change this value!") - @CustomKey("config-version") - public String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); - - @Comment("-------------------------") - @Comment("Debug mode (Dev only)") - @CustomKey("debug-mode") - public boolean debugMode = false; - - @Comment("Set player gamemode to change when they enter their plot") - @CustomKey("enable-plot-gamemode") - public boolean enablePlotGameMode = false; - - @Comment("Set your wanted language (locale)") - public String locale = VirtualRealty.getInstance().availableLocales.contains(VirtualRealty.getLocale()) ? VirtualRealty.getLocale().toString() : "en_GB"; - - @Comment("Set which gamemode players change to when they enter their plot") - @CustomKey("default-plot-gamemode") - public String plotGameMode = "SURVIVAL"; - - @Comment("Lock gamemode to plot default when player enters their plot (disables '/plot gm' command)") - @CustomKey("lock-plot-gamemode") - public boolean lockPlotGameMode = false; - - public GameMode getGameMode() { - try { - return GameMode.valueOf(plotGameMode); - } catch (Exception e) { - VirtualRealty.getInstance().getLogger().warning("Couldn't parse plot-gamemode from config.yml\nUsing default: SURVIVAL"); - return GameMode.SURVIVAL; - } - } - - @Comment("Allow players to build outside of their plots") - @CustomKey("allow-outplot-build") - public boolean allowOutPlotBuild = true; - - @Comment("Enables dynmap plots highlighting") - @CustomKey("enable-dynmap-markers") - public boolean dynmapMarkers = false; - - @Comment("Choose which type of plots should be highlighted on Dynmap page | Choose from: { ALL, AVAILABLE, OWNED }") - @CustomKey("dynmap-type") - public HighlightType dynmapType = HighlightType.ALL; - - @CustomKey("dynmap-markers") - public MarkerColor dynmapMarkersColor = new MarkerColor(new MarkerColor.Available("#80eb34", .3), new MarkerColor.Owned("#ffbf00", .45)); - - @Names(strategy = NameStrategy.IDENTITY) - public static class MarkerColor extends OkaeriConfig { - - public Available available; - - public Owned owned; - - public MarkerColor(Available available, Owned owned) { - this.available = available; - this.owned = owned; - } - - @Names(strategy = NameStrategy.IDENTITY) - public static class Available extends OkaeriConfig { - - public String color; - - public double opacity; - - public Available(String color, double opacity) { - this.color = color; - this.opacity = opacity; - } - - public int getHexColor() { - return Integer.decode("0x" + color.replaceAll("#", "")); - } - - } - - @Names(strategy = NameStrategy.IDENTITY) - public static class Owned extends OkaeriConfig { - - public String color; - - public double opacity; - - public Owned(String color, double opacity) { - this.color = color; - this.opacity = opacity; - } - - public int getHexColor() { - return Integer.decode("0x" + color.replaceAll("#", "")); - } - - } - - } - - @Comment("Enables plots enter/leave sounds") - @CustomKey("plot-sounds") - public boolean plotSound = true; - - @Comment("Type of data recording") - @Comment("SQLITE - Local database") - @Comment("MYSQL - External database") - @CustomKey("data-model") - public DataModel dataModel = DataModel.SQLITE; - - @Comment("Data required to connect to the database") - @Comment("The plotsTableName section is the name of the VR data table in the database") - @Comment("It is best to change these names only if you really need to (e.g. there is a conflict with another plugin)") - @Comment("To rename tables when you already have some VR data in the database:") - @Comment("1. Turn off the server") - @Comment("2. Change data in VR config") - @Comment("3. Rename database tables using phpMyAdmin for example") - @CustomKey("mysql") - public MySQL mysql = new MySQL("localhost", 3306, "db", "root", "passwd", true, "vr_plots"); - - public enum DataModel { - SQLITE, - H2, - MYSQL - } - - @Names(strategy = NameStrategy.IDENTITY) - public static class MySQL extends OkaeriConfig { - - @Variable("VR_MYSQL_HOSTNAME") - public String hostname; - @Variable("VR_MYSQL_PORT") - public int port; - @Variable("VR_MYSQL_DATABASE") - public String database; - @Variable("VR_MYSQL_USER") - public String user; - @Variable("VR_MYSQL_PASSWORD") - public String password; - @Variable("VR_MYSQL_USE_SSL") - public boolean useSSL; - @Variable("VR_MYSQL_USERS_TABLE_NAME") - public String plotsTableName; - - public MySQL(String hostname, int port, String database, String user, String password, boolean useSSL, String plotsTableName) { - this.hostname = hostname; - this.port = port; - this.database = database; - this.user = user; - this.password = password; - this.useSSL = useSSL; - this.plotsTableName = plotsTableName; - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/configs/SizesConfiguration.java b/src/main/java/me/plytki/virtualrealty/configs/SizesConfiguration.java deleted file mode 100644 index 1751108..0000000 --- a/src/main/java/me/plytki/virtualrealty/configs/SizesConfiguration.java +++ /dev/null @@ -1,89 +0,0 @@ -package me.plytki.virtualrealty.configs; - -import eu.okaeri.configs.OkaeriConfig; -import eu.okaeri.configs.annotation.*; -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.PlotSize; -import org.bukkit.Material; - -import java.time.Instant; - -@Header("################################################################") -@Header("# #") -@Header("# Plot Sizes #") -@Header("# #") -@Header("################################################################") -public class SizesConfiguration extends OkaeriConfig { - - @Comment(" ") - @Comment("-------------------------") - @Comment("Don't change this value!") - @CustomKey("config-version") - public final String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); - @Comment("-------------------------") - - @Comment(" ") - @Comment("(<1.13) Legacy Materials: https://helpch.at/docs/1.8/org/bukkit/Material.html") - @Comment("(>1.12) Post-Legacy Materials: https://helpch.at/docs/1.13/org/bukkit/Material.html") - @Comment(" ") - @Comment("floor-data and border-data are only for legacy versions * <1.13 *") - @CustomKey("plot-sizes") - public PlotSizes plotSizes = new PlotSizes(); - - @Names(strategy = NameStrategy.IDENTITY) - public static class PlotSizes extends OkaeriConfig { - - @Variable("VR_SIZE_SMALL") - public Size SMALL = new Size(PlotSize.SMALL); - @Variable("VR_SIZE_MEDIUM") - public Size MEDIUM = new Size(PlotSize.MEDIUM); - @Variable("VR_SIZE_LARGE") - public Size LARGE = new Size(PlotSize.LARGE); - - public PlotSizes() { - } - - public PlotSizes(Size small, Size medium, Size large) { - this.SMALL = small; - this.MEDIUM = medium; - this.LARGE = large; - } - - public static class Size extends OkaeriConfig { - - @Variable("VR_SIZE_FLOORMATERIAL") - @CustomKey("floor-material") - public String floorMaterial; - @Variable("VR_SIZE_FLOORDATA") - @CustomKey("floor-data") - public byte floorData; - @Variable("VR_SIZE_BORDERMATERIAL") - @CustomKey("border-material") - public String borderMaterial; - @Variable("VR_SIZE_BORDERDATA") - @CustomKey("border-data") - public byte borderData; - @Variable("VR_SIZE_LENGTH") - public int length; - @Variable("VR_SIZE_WIDTH") - public int width; - @Variable("VR_SIZE_HEIGHT") - public int height; - - public Size() { - } - - public Size(PlotSize plotSize) { - this.floorMaterial = plotSize.getFloorMaterial().name(); - this.floorData = plotSize.getFloorData(); - this.borderMaterial = plotSize.getBorderMaterial().name(); - this.borderData = plotSize.getBorderData(); - this.length = plotSize.getLength(); - this.width = plotSize.getWidth(); - this.height = plotSize.getHeight(); - } - - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/Direction.java b/src/main/java/me/plytki/virtualrealty/enums/Direction.java deleted file mode 100644 index a3d0c11..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/Direction.java +++ /dev/null @@ -1,45 +0,0 @@ -package me.plytki.virtualrealty.enums; - -public enum Direction { - - SOUTH(315, 45), - WEST(45, 135), - NORTH(135, 225), - EAST(225, 315); - - private final float minYaw; - private final float maxYaw; - - Direction(float minYaw, float maxYaw) { - this.minYaw = minYaw; - this.maxYaw = maxYaw; - } - - public static Direction byYaw(float yaw) { - float absoluteYaw = Math.abs(yaw); - Direction direction = null; - if(absoluteYaw > 315 || absoluteYaw <= 45) { - //south - direction = SOUTH; - } else if(absoluteYaw > 45 && absoluteYaw <= 135) { - //west - direction = yaw > 0 ? WEST : EAST; - } else if(absoluteYaw > 135 && absoluteYaw <= 225) { - //north - direction = NORTH; - } else if(absoluteYaw > 225 && absoluteYaw <= 315) { - //east - direction = yaw > 0 ? EAST : WEST; - } - return direction; - } - - public float getMaxYaw() { - return maxYaw; - } - - public float getMinYaw() { - return minYaw; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/Flag.java b/src/main/java/me/plytki/virtualrealty/enums/Flag.java deleted file mode 100644 index 5409fc1..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/Flag.java +++ /dev/null @@ -1,33 +0,0 @@ -package me.plytki.virtualrealty.enums; - -public class Flag { - - public enum World { - - BLOCK_PLACE(false), - BLOCK_BREAK(false), - INTERACT(false), - IGNITE(false), - EXPLOSION_PRIME(false), - ENTITY_DAMAGE(false), - ARMOR_STAND_MANIPULATION(false), - ITEM_FRAME_DESTROY(false), - ITEM_FRAME_ROTATE(false); - - private boolean allowed; - - World(boolean allowed) { - this.allowed = allowed; - } - - public boolean isAllowed() { - return allowed; - } - - public void setAllowed(boolean allowed) { - this.allowed = allowed; - } - - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/HighlightType.java b/src/main/java/me/plytki/virtualrealty/enums/HighlightType.java deleted file mode 100644 index dc8f244..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/HighlightType.java +++ /dev/null @@ -1,9 +0,0 @@ -package me.plytki.virtualrealty.enums; - -public enum HighlightType { - - ALL, - AVAILABLE, - OWNED - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/Permission.java b/src/main/java/me/plytki/virtualrealty/enums/Permission.java deleted file mode 100644 index 3f0c433..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/Permission.java +++ /dev/null @@ -1,24 +0,0 @@ -package me.plytki.virtualrealty.enums; - -public enum Permission { - - WORLD_BUILD("virtualrealty.build.world"), - PLOT_BUILD("virtualrealty.build.plot"), - BORDER_BUILD("virtualrealty.build.border"); - - private final String permission; - - Permission(String permission) { - this.permission = permission; - } - - public String getPermission() { - return permission; - } - - @Override - public String toString() { - return permission; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/enums/PlotSize.java b/src/main/java/me/plytki/virtualrealty/enums/PlotSize.java deleted file mode 100644 index ad59d12..0000000 --- a/src/main/java/me/plytki/virtualrealty/enums/PlotSize.java +++ /dev/null @@ -1,86 +0,0 @@ -package me.plytki.virtualrealty.enums; - -import me.plytki.virtualrealty.VirtualRealty; -import org.bukkit.Material; - -public enum PlotSize { - - SMALL(10, 10, 10, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), - MEDIUM(25, 25, 25, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), - LARGE(50, 50, 50, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), - CUSTOM(0, 0, 0, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0); - - private int length; - private int width; - private int height; - private Material floorMaterial; - private byte floorData; - private Material borderMaterial; - private byte borderData; - - PlotSize(int length, int width, int height, Material floorMaterial, byte floorData, Material borderMaterial, byte borderData) { - this.length = length; - this.width = width; - this.height = height; - this.floorMaterial = floorMaterial; - this.floorData = floorData; - this.borderMaterial = borderMaterial; - this.borderData = borderData; - } - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public Material getFloorMaterial() { - return floorMaterial; - } - - public void setFloorMaterial(Material floorMaterial) { - this.floorMaterial = floorMaterial; - } - - public byte getFloorData() { - return floorData; - } - - public void setFloorData(byte floorData) { - this.floorData = floorData; - } - - public Material getBorderMaterial() { - return borderMaterial; - } - - public void setBorderMaterial(Material borderMaterial) { - this.borderMaterial = borderMaterial; - } - - public byte getBorderData() { - return borderData; - } - - public void setBorderData(byte borderData) { - this.borderData = borderData; - } -} diff --git a/src/main/java/me/plytki/virtualrealty/exceptions/MaterialMatchException.java b/src/main/java/me/plytki/virtualrealty/exceptions/MaterialMatchException.java deleted file mode 100644 index bfe84ec..0000000 --- a/src/main/java/me/plytki/virtualrealty/exceptions/MaterialMatchException.java +++ /dev/null @@ -1,9 +0,0 @@ -package me.plytki.virtualrealty.exceptions; - -public class MaterialMatchException extends Exception { - - public MaterialMatchException(String exception) { - super(exception); - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/ProtectionListener.java b/src/main/java/me/plytki/virtualrealty/listeners/ProtectionListener.java deleted file mode 100644 index 5892906..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/ProtectionListener.java +++ /dev/null @@ -1,448 +0,0 @@ -package me.plytki.virtualrealty.listeners; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Flag; -import me.plytki.virtualrealty.listeners.VirtualListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.utils.ProtectionUtil; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.*; -import org.bukkit.event.entity.*; -import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.player.PlayerArmorStandManipulateEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.world.StructureGrowEvent; -import org.bukkit.util.Vector; - -import java.time.LocalDateTime; - -public class ProtectionListener extends VirtualListener { - - public ProtectionListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onBlockInteract(PlayerInteractEvent e) { - Player player = e.getPlayer(); - if (e.getClickedBlock() != null && (e.getAction() == Action.RIGHT_CLICK_BLOCK || (e.getAction() == Action.LEFT_CLICK_BLOCK && (!VirtualRealty.isLegacy && e.getClickedBlock().getType().isInteractable())))) { - Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { - if (!Flag.World.BLOCK_PLACE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - @EventHandler - public void onBlockPlace(BlockPlaceEvent e) { - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlockPlaced().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { - if (!Flag.World.BLOCK_PLACE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - - @EventHandler - public void onBlockBreak(BlockBreakEvent e) { - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_BREAK)) { - if (!Flag.World.BLOCK_BREAK.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - - @EventHandler - public void onBlockMove(BlockPistonExtendEvent e) { - if (VirtualRealty.isLegacy) { - if (e.getBlocks().isEmpty()) { - Location fromLocation = e.getBlock().getLocation(); - Location toLocation = e.getBlock().getLocation(); - toLocation.add(getDirection(e.getDirection())); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } else { - for (Block block : e.getBlocks()) { - Location fromLocation = block.getLocation(); - Location toLocation = block.getLocation(); - toLocation.add(getDirection(e.getDirection())); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } else { - e.setCancelled(true); - } - } - } - } - } else { - if (e.getBlocks().isEmpty()) { - Location fromLocation = e.getBlock().getLocation(); - Location toLocation = e.getBlock().getLocation(); - toLocation.add(e.getDirection().getDirection()); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } else { - for (Block block : e.getBlocks()) { - Location fromLocation = block.getLocation(); - Location toLocation = block.getLocation(); - toLocation.add(e.getDirection().getDirection()); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } else { - e.setCancelled(true); - } - } - } - } - } - } - - public Vector getDirection(BlockFace blockFace) { - Vector direction = new Vector(blockFace.getModX(), blockFace.getModY(), blockFace.getModZ()); - if (blockFace.getModX() != 0 || blockFace.getModY() != 0 || blockFace.getModZ() != 0) { - direction.normalize(); - } - - return direction; - } - - @EventHandler - public void onIgniteEvent(BlockIgniteEvent e) { - Player player = e.getPlayer(); - if (player != null) { - if (e.getIgnitingBlock() != null) { - Plot plot = PlotManager.getBorderedPlot(e.getIgnitingBlock().getLocation()); - if (plot != null) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - return; - } - e.setCancelled(!plot.hasPermissionToPlot(player)); - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.IGNITE)) { - if (!Flag.World.IGNITE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - } - - @EventHandler - public void onEntityExplode(ExplosionPrimeEvent e) { - Plot plot = PlotManager.getBorderedPlot(e.getEntity().getLocation()); - if (plot != null) { - e.setCancelled(true); - } else { - if (!Flag.World.EXPLOSION_PRIME.isAllowed()) { - e.setCancelled(true); - } - } - } - -// @EventHandler -// public void onPlotEnter(PlayerMoveEvent e) { -// Player player = e.getPlayer(); -// Plot plot = PlotManager.getPlot(e.getTo()); -// if (plot != null && e.getPlayer().isInsideVehicle()) { -// if (!plot.hasPermissionToPlot(player)) { -// e.getPlayer().getVehicle().eject(); -// player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantRideOnPlot); -// } -// } -// } - - @EventHandler - public void onTreeGrow(StructureGrowEvent e) { - for (BlockState block : e.getBlocks()) { - Location fromLocation = e.getLocation(); - Location toLocation = block.getLocation(); - Plot fromPlot = PlotManager.getPlot(fromLocation); - Plot toPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } - } - - @EventHandler - public void onDragonEggMove(BlockFromToEvent e) { - Material block = e.getBlock().getType(); - if (block == Material.DRAGON_EGG || block == Material.LAVA || block == Material.WATER) { - Location fromLocation = e.getBlock().getLocation(); - Location toLocation = e.getToBlock().getLocation(); - Plot fromPlot = PlotManager.getPlot(fromLocation); - Plot toPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } - } - - @EventHandler - public void onProjectileLaunch(ProjectileLaunchEvent e) { - Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); - if (plot != null) { - if (!(e.getEntity().getShooter() instanceof Player && plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player)e.getEntity().getShooter()).getUniqueId()))) { - Player player = (Player) e.getEntity().getShooter(); - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.getEntity().remove(); - } - } else { - e.getEntity().remove(); - } - } - } - } - - @EventHandler - public void onProjectileHit(ProjectileHitEvent e) { - Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); - if (plot != null) { - if (e.getEntity().getShooter() instanceof Player) { - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId()))) { - Player player = (Player) e.getEntity().getShooter(); - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.getEntity().remove(); - } - } else { - e.getEntity().remove(); - } - } - } - } - } - - @EventHandler - public void onFireSpread(BlockSpreadEvent e) { - Location fromLocation = e.getSource().getLocation(); - Location toLocation = e.getBlock().getLocation(); - Plot fromPlot = PlotManager.getPlot(fromLocation); - Plot toPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } - - @EventHandler - public void onArmorStandChange(PlayerArmorStandManipulateEvent e) { - Plot plot = PlotManager.getPlot(e.getPlayer().getLocation()); - Player player = e.getPlayer(); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ARMOR_STAND_MANIPULATION)) { - if (!Flag.World.ARMOR_STAND_MANIPULATION.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - - @EventHandler - public void onItemFrameDamage(HangingBreakByEntityEvent e) { - if (e.getRemover() instanceof Player) { - Player player = (Player) e.getRemover(); - Plot plot = PlotManager.getPlot(player.getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_DESTROY)) { - if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - @EventHandler - public void onItemFrameRotate(PlayerInteractEntityEvent e) { - if (e.getRightClicked().getType().equals(EntityType.ITEM_FRAME)) { - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(player.getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_ROTATE)) { - if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - - @EventHandler - public void onEntityDamage(EntityDamageByEntityEvent e) { - if (e.getDamager() instanceof Player) { - Player player = (Player) e.getDamager(); - Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { - if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - @EventHandler - public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { - if (e.getDamager() instanceof Projectile) { - if (((Projectile) e.getDamager()).getShooter() instanceof Player) { - Player player = ((Player) ((Projectile) e.getDamager()).getShooter()); - Plot plot = PlotManager.getBorderedPlot(e.getDamager().getLocation()); - if (plot != null) { - if (!plot.hasPermissionToPlot(player)) { - e.getDamager().remove(); - e.setCancelled(true); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { - if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/VirtualListener.java b/src/main/java/me/plytki/virtualrealty/listeners/VirtualListener.java deleted file mode 100644 index e612009..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/VirtualListener.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.plytki.virtualrealty.listeners; - -import me.plytki.virtualrealty.VirtualRealty; -import org.bukkit.event.Listener; - -public class VirtualListener implements Listener { - - private final VirtualRealty plugin; - - public VirtualListener(VirtualRealty plugin) { - this.plugin = plugin; - } - - public void registerEvents() { - this.plugin.getServer().getPluginManager().registerEvents(this, this.plugin); - } - - protected VirtualRealty getPlugin() { - return this.plugin; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/plot/BorderListener.java b/src/main/java/me/plytki/virtualrealty/listeners/plot/BorderListener.java deleted file mode 100644 index 4c034b9..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/plot/BorderListener.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.plytki.virtualrealty.listeners.plot; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Permission; -import me.plytki.virtualrealty.listeners.VirtualListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -public class BorderListener extends VirtualListener { - - public BorderListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onBorderBreak(BlockBreakEvent e) { - Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); - if (plot != null) { - if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { - if (plot.getBorderBlocks().contains(e.getBlock())) { - e.setCancelled(true); - e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - - @EventHandler - public void onBorderPlace(BlockPlaceEvent e) { - Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); - if (plot != null) { - if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { - if (plot.getBorderBlocks().contains(e.getBlock())) { - e.setCancelled(true); - e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/plot/PlotListener.java b/src/main/java/me/plytki/virtualrealty/listeners/plot/PlotListener.java deleted file mode 100644 index 4979ac1..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/plot/PlotListener.java +++ /dev/null @@ -1,100 +0,0 @@ -package me.plytki.virtualrealty.listeners.plot; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.listeners.VirtualListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import net.md_5.bungee.api.ChatMessageType; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.Sound; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerMoveEvent; - -import java.util.AbstractMap; -import java.util.HashMap; - -public class PlotListener extends VirtualListener { - - public HashMap> enteredPlot = new HashMap<>(); - - public PlotListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onPlotMove(PlayerMoveEvent e) { - if (e.isCancelled()) return; - Player player = e.getPlayer(); - Location to = e.getTo(); - Plot plot = PlotManager.getPlot(to); - if (plot != null) { - OfflinePlayer offlinePlayer; - String enterPlotString = VirtualRealty.getMessages().enteredAvailablePlot; - if (plot.getOwnedBy() != null) { - offlinePlayer = Bukkit.getOfflinePlayer(plot.getOwnedBy()); - enterPlotString = VirtualRealty.getMessages().enteredOwnedPlot.replaceAll("%owner%", offlinePlayer.getName()).replaceAll("%plot_id%", plot.getID() + ""); - } - if (!enteredPlot.containsKey(player)) { - enteredPlot.put(player, new AbstractMap.SimpleEntry<>(plot, true)); - Plot newPlot = enteredPlot.get(player).getKey(); - if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { - if (newPlot.getOwnedBy() != null && newPlot.getOwnedBy().equals(player.getUniqueId())) { - if (newPlot.getSelectedGameMode() != VirtualRealty.getInstance().getServer().getDefaultGameMode() || newPlot.getSelectedGameMode() != VirtualRealty.getPluginConfiguration().getGameMode()) { - newPlot.setSelectedGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); - } - player.setGameMode(newPlot.getSelectedGameMode()); - } else if (newPlot.getMembers().contains(player.getUniqueId())) { - player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); - } - } - if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { - if (VirtualRealty.getPluginConfiguration().plotSound) { - player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, 0.4f, 0.8f); - } - } - if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(enterPlotString)); - } - } else { - if (!enteredPlot.get(player).getValue()) { - enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(plot, true)); - if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { - player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); - } - } - } - } else { - if (enteredPlot.containsKey(player)) { - if (enteredPlot.get(player).getValue()) { - OfflinePlayer offlinePlayer; - String leavePlotString = VirtualRealty.getMessages().leftAvailablePlot; - if (enteredPlot.get(player).getKey().getOwnedBy() != null) { - offlinePlayer = Bukkit.getOfflinePlayer(enteredPlot.get(player).getKey().getOwnedBy()); - leavePlotString = VirtualRealty.getMessages().leftOwnedPlot.replaceAll("%owner%", offlinePlayer.getName()).replaceAll("%plot_id%", enteredPlot.get(player).getKey().getID() + ""); - if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { - if (enteredPlot.get(player).getKey().hasPlotMembership(player)) { - player.setGameMode(Bukkit.getServer().getDefaultGameMode()); - } - } - } - if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { - if (VirtualRealty.getPluginConfiguration().plotSound) { - player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_CLOSE, 0.3f, 1f); - } - if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(leavePlotString)); - } - } - enteredPlot.remove(player); - return; - } - enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(enteredPlot.get(player).getKey(), false)); - } - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/listeners/world/WorldListener.java b/src/main/java/me/plytki/virtualrealty/listeners/world/WorldListener.java deleted file mode 100644 index 4a45a15..0000000 --- a/src/main/java/me/plytki/virtualrealty/listeners/world/WorldListener.java +++ /dev/null @@ -1,49 +0,0 @@ -package me.plytki.virtualrealty.listeners.world; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Permission; -import me.plytki.virtualrealty.listeners.VirtualListener; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -public class WorldListener extends VirtualListener { - - public WorldListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onBlockBreak(BlockBreakEvent e) { - if (e.isCancelled()) return; - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); - if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { - if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { - if (plot == null) { - e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - - @EventHandler - public void onBlockPlace(BlockPlaceEvent e) { - if (e.isCancelled()) return; - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); - if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { - if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { - if (plot == null) { - e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java b/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java deleted file mode 100644 index 2ba6ba5..0000000 --- a/src/main/java/me/plytki/virtualrealty/managers/PlotManager.java +++ /dev/null @@ -1,186 +0,0 @@ -package me.plytki.virtualrealty.managers; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.HighlightType; -import me.plytki.virtualrealty.enums.PlotSize; -import me.plytki.virtualrealty.objects.Cuboid; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.objects.math.BlockVector2; -import me.plytki.virtualrealty.objects.math.BlockVector3; -import me.plytki.virtualrealty.sql.SQL; -import org.bukkit.Location; -import org.bukkit.Material; -import org.dynmap.markers.AreaMarker; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; - -public class PlotManager { - - private static final String markerString = "

Plot #%s

Owned By: Available"; - private static final String markerOwnedString = "

Plot #%s

Owned By: %s
Owned Until: %s"; - - public static Set areaMarkers = new HashSet<>(); - public static Set plots = new LinkedHashSet<>(); - - public static void loadPlots() { - plots.clear(); - try { - ResultSet rs = SQL.getStatement().executeQuery("SELECT * FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "`"); - while (rs.next()) { - plots.add(new Plot(rs)); - } - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public static Plot createPlot(Location creationLocation, PlotSize plotSize) { - Plot plot = new Plot(creationLocation, plotSize.getFloorMaterial(), plotSize.getBorderMaterial(), plotSize); - plots.add(plot); - plot.insert(); - return plot; - } - - public static Plot createPlot(Location creationLocation, int length, int width, int height) { - Plot plot = new Plot(creationLocation, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), length, width, height); - plots.add(plot); - plot.insert(); - return plot; - } - - public static Plot getPlot(int ID) { - for (Plot plot : plots) { - if(plot.getID() == ID) { - return plot; - } - } - return null; - } - - public static int getPlotMinID() { - return plots.isEmpty() ? null : plots.stream().findFirst().get().getID(); - } - - public static int getPlotMaxID() { - Plot[] plotArray = PlotManager.plots.toArray(new Plot[PlotManager.plots.size()]); - Plot lastPlot = plotArray[plotArray.length - 1]; - return lastPlot.getID(); - } - - public static List getPlayerPlots(UUID owner) { - List playerPlots = new ArrayList<>(); - for (Plot plot : plots) { - if (plot.getOwnedBy() != null) { - if (plot.getOwnedBy().equals(owner)) { - playerPlots.add(plot); - } - } - } - return playerPlots; - } - - public static Plot getPlot(Location location) { - BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - for (Plot plot : plots) { - Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); - if(region.contains(newVector)) { - return plot; - } - } - return null; - } - - public static boolean isLocationInPlot(Location location, Plot plot) { - BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); - return region.contains(newVector); - } - - public static Plot getBorderedPlot(Location location) { - BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - for (Plot plot : plots) { - Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), location.getWorld()); - if(region.contains(newVector)) { - return plot; - } - } - return null; - } - - public static boolean isLocationInBorderedPlot(Location location, Plot plot) { - BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), location.getWorld()); - return region.contains(newVector); - } - - public static boolean isColliding(Cuboid newPlot) { - for (Plot plot : plots) { - Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), plot.getCreatedLocation().getWorld()); - for (BlockVector2 vector2 : region.getWalls()) { - if (vector2.containedWithin(newPlot.getMinimumPoint(), newPlot.getMaximumPoint())) { - return true; - } - } - } - return false; - } - - private static AreaMarker getAreaMarker(String areaMarkerName) { - for (AreaMarker areaMarker : VirtualRealty.markerset.getAreaMarkers()) { - if (areaMarker.getMarkerID().equalsIgnoreCase(areaMarkerName)) { - return areaMarker; - } - } - return null; - } - - public static void resetPlotMarker(Plot plot) { - if (!VirtualRealty.isDynmapPresent) return; - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - String ownedBy; - double opacity; - int color; - if (plot.getOwnedBy() == null) { - ownedBy = "Available"; - color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.getHexColor(); - opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.available.opacity; - } else { - ownedBy = plot.getPlotOwner().getName(); - color = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.getHexColor(); - opacity = VirtualRealty.getPluginConfiguration().dynmapMarkersColor.owned.opacity; - } - if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.OWNED && plot.getOwnedBy() == null) return; - if (VirtualRealty.getPluginConfiguration().dynmapType == HighlightType.AVAILABLE && plot.getOwnedBy() != null) return; - AreaMarker marker = getAreaMarker("virtualrealty.plots." + plot.getID()); - if (marker == null) { - marker = VirtualRealty.markerset.createAreaMarker("virtualrealty.plots." + plot.getID(), - - plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true, - - plot.getCreatedWorld(), new double[]{plot.getXMin(), plot.getXMax()}, new double[]{plot.getZMin(), plot.getZMax()}, true); - - areaMarkers.add(marker); - } else { - marker.setLabel( - - plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true); - - } - marker.setFillStyle(opacity, color); - marker.setLineStyle(2, 0.8, 0x474747); - marker.setMarkerSet(VirtualRealty.markerset); - } - - public static void removeDynMapMarker(Plot plot) { - if (!VirtualRealty.isDynmapPresent || VirtualRealty.dapi == null || VirtualRealty.markerset == null) return; - AreaMarker marker = VirtualRealty.markerset.findAreaMarker("virtualrealty.plots." + plot.getID()); - areaMarkers.remove(marker); - marker.deleteMarker(); - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/objects/Cuboid.java b/src/main/java/me/plytki/virtualrealty/objects/Cuboid.java deleted file mode 100644 index 1273672..0000000 --- a/src/main/java/me/plytki/virtualrealty/objects/Cuboid.java +++ /dev/null @@ -1,187 +0,0 @@ -package me.plytki.virtualrealty.objects; - -import me.plytki.virtualrealty.objects.math.BlockVector2; -import me.plytki.virtualrealty.objects.math.BlockVector3; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -public class Cuboid { - - private int xMin; - private int xMax; - private int yMin; - private int yMax; - private int zMin; - private int zMax; - private double xMinCentered; - private double xMaxCentered; - private double yMinCentered; - private double yMaxCentered; - private double zMinCentered; - private double zMaxCentered; - private World world; - - public Cuboid(Location point1, Location point2) { - this.xMin = Math.min(point1.getBlockX(), point2.getBlockX()); - this.xMax = Math.max(point1.getBlockX(), point2.getBlockX()); - this.yMin = Math.min(point1.getBlockY(), point2.getBlockY()); - this.yMax = Math.max(point1.getBlockY(), point2.getBlockY()); - this.zMin = Math.min(point1.getBlockZ(), point2.getBlockZ()); - this.zMax = Math.max(point1.getBlockZ(), point2.getBlockZ()); - this.world = point1.getWorld(); - this.xMinCentered = this.xMin + 0.5; - this.xMaxCentered = this.xMax + 0.5; - this.yMinCentered = this.yMin + 0.5; - this.yMaxCentered = this.yMax + 0.5; - this.zMinCentered = this.zMin + 0.5; - this.zMaxCentered = this.zMax + 0.5; - } - - public Cuboid(BlockVector3 point1, BlockVector3 point2, World world) { - this.xMin = Math.min(point1.getBlockX(), point2.getBlockX()); - this.xMax = Math.max(point1.getBlockX(), point2.getBlockX()); - this.yMin = Math.min(point1.getBlockY(), point2.getBlockY()); - this.yMax = Math.max(point1.getBlockY(), point2.getBlockY()); - this.zMin = Math.min(point1.getBlockZ(), point2.getBlockZ()); - this.zMax = Math.max(point1.getBlockZ(), point2.getBlockZ()); - this.world = world; - this.xMinCentered = this.xMin + 0.5; - this.xMaxCentered = this.xMax + 0.5; - this.yMinCentered = this.yMin + 0.5; - this.yMaxCentered = this.yMax + 0.5; - this.zMinCentered = this.zMin + 0.5; - this.zMaxCentered = this.zMax + 0.5; - } - - - public List blockList() { - ArrayList bL = new ArrayList<>((xMax - xMin) * (yMax - yMin) * (zMax - zMin)); - for(int x = this.xMin; x <= this.xMax; ++x) { - for(int y = this.yMin; y <= this.yMax; ++y) { - for(int z = this.zMin; z <= this.zMax; ++z) { - Block b = this.world.getBlockAt(x, y, z); - bL.add(b); - } - } - } - return bL; - } - - public Location getCenter() { - return new Location(this.world, (this.xMax - this.xMin) / 2 + this.xMin + 1, (this.yMax - this.yMin) / 2 + this.yMin, (this.zMax - this.zMin) / 2 + this.zMin + 1); - } - - public BlockVector3 getCenterVector() { - return BlockVector3.at((this.xMax - this.xMin) / 2 + this.xMin + 1, (this.yMax - this.yMin) / 2 + this.yMin, (this.zMax - this.zMin) / 2 + this.zMin + 1); - } - - public double getDistance() { - return this.getPoint1().distance(this.getPoint2()); - } - - public double getDistanceSquared() { - return this.getPoint1().distanceSquared(this.getPoint2()); - } - - public int getHeight() { - return this.yMax - this.yMin + 1; - } - - public BlockVector3 getMinimumPoint() { - return BlockVector3.at(this.xMin, this.yMin, this.zMin); - } - - public BlockVector3 getMaximumPoint() { - return BlockVector3.at(this.xMax, this.yMax, this.zMax); - } - - public Location getPoint1() { - return new Location(this.world, this.xMin, this.yMin, this.zMin); - } - - public Location getPoint2() { - return new Location(this.world, this.xMax, this.yMax, this.zMax); - } - - public Location getRandomLocation() { - Random rand = new Random(); - int x = rand.nextInt(Math.abs(this.xMax - this.xMin) + 1) + this.xMin; - int y = rand.nextInt(Math.abs(this.yMax - this.yMin) + 1) + this.yMin; - int z = rand.nextInt(Math.abs(this.zMax - this.zMin) + 1) + this.zMin; - return new Location(this.world, x, y, z); - } - - public boolean contains(BlockVector3 vector3) { - return vector3.getBlockX() >= this.xMin && vector3.getBlockX() <= this.xMax && vector3.getBlockY() >= this.yMin && vector3.getBlockY() <= this.yMax && vector3 - .getBlockZ() >= this.zMin && vector3.getBlockZ() <= this.zMax; - } - - public boolean contains(BlockVector3 vector3, World world) { - return world == this.world && vector3.getBlockX() >= this.xMin && vector3.getBlockX() <= this.xMax && vector3.getBlockY() >= this.yMin && vector3.getBlockY() <= this.yMax && vector3 - .getBlockZ() >= this.zMin && vector3.getBlockZ() <= this.zMax; - } - - public int getTotalBlockSize() { - return this.getHeight() * this.getXWidth() * this.getZWidth(); - } - - public int getXWidth() { - return this.xMax - this.xMin + 1; - } - - public int getZWidth() { - return this.zMax - this.zMin + 1; - } - - public boolean isIn(Location loc) { - return loc.getWorld() == this.world && loc.getBlockX() >= this.xMin && loc.getBlockX() <= this.xMax && loc.getBlockY() >= this.yMin && loc.getBlockY() <= this.yMax && loc - .getBlockZ() >= this.zMin && loc.getBlockZ() <= this.zMax; - } - - public boolean isIn(Player player) { - return this.isIn(player.getLocation()); - } - - public boolean isInWithMarge(Location loc, double marge) { - return loc.getWorld() == this.world && loc.getX() >= this.xMinCentered - marge && loc.getX() <= this.xMaxCentered + marge && loc.getY() >= this.yMinCentered - marge && loc - .getY() <= this.yMaxCentered + marge && loc.getZ() >= this.zMinCentered - marge && loc.getZ() <= this.zMaxCentered + marge; - } - - public boolean isColliding(Cuboid region) { - List flatRegion1 = new ArrayList<>(this.getFlatRegion()); - List flatRegion2 = new ArrayList<>(region.getFlatRegion()); - for (BlockVector2 vector1 : flatRegion1) { - for (BlockVector2 vector2 : flatRegion2) - if (vector1.getBlockX() == vector2.getBlockX() && vector1.getBlockZ() == vector2.getBlockZ()) return true; - } - return false; - } - - public List getFlatRegion() { - List blocksVector = new ArrayList<>(); - for (Block block : blockList()) { - blocksVector.add(BlockVector2.at(block.getLocation().getBlockX(), block.getLocation().getBlockZ())); - } - return blocksVector; - } - - public List getWalls() { - List walls = new ArrayList<>(); - for (int z = zMin; z <= zMax; z++) { - walls.add(BlockVector2.at(xMin, z)); - walls.add(BlockVector2.at(xMax, z)); - } - for (int x = xMin; x < xMax; x++) { - walls.add(BlockVector2.at(x, zMin)); - walls.add(BlockVector2.at(x, zMax)); - } - return walls; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/objects/Plot.java b/src/main/java/me/plytki/virtualrealty/objects/Plot.java deleted file mode 100644 index 2b1434e..0000000 --- a/src/main/java/me/plytki/virtualrealty/objects/Plot.java +++ /dev/null @@ -1,796 +0,0 @@ -package me.plytki.virtualrealty.objects; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Direction; -import me.plytki.virtualrealty.enums.Permission; -import me.plytki.virtualrealty.enums.PlotSize; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.math.BlockVector3; -import me.plytki.virtualrealty.sql.SQL; -import me.plytki.virtualrealty.utils.SchematicUtil; -import org.apache.commons.io.FileUtils; -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.time.Instant; -import java.time.LocalDateTime; -import java.util.*; - -public class Plot { - - private int ID; - private UUID ownedBy; - private Set members; - private String assignedBy; - private LocalDateTime ownedUntilDate; - private PlotSize plotSize; - private int length; - private int width; - private int height; - private Material floorMaterial; - private byte floorData; - private Material borderMaterial; - private byte borderData; - private Location createdLocation; - private Direction createdDirection; - private BlockVector3 bottomLeftCorner; - private BlockVector3 topRightCorner; - private BlockVector3 borderBottomLeftCorner; - private BlockVector3 borderTopRightCorner; - private GameMode selectedGameMode; - private String createdWorld; - private Instant modified; - - @Override - public String toString() { - return "{ ID: " + ID + ", ownedBy: " + ownedBy + "}"; - } - - public Plot(Location location, Material floorMaterial, Material borderMaterial, PlotSize plotSize) { - this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; - this.ownedBy = null; - this.members = new HashSet<>(); - this.assignedBy = null; - this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); - this.floorMaterial = floorMaterial; - this.floorData = 0; - this.borderMaterial = borderMaterial; - this.borderData = 0; - this.plotSize = plotSize; - this.length = plotSize.getLength(); - this.width = plotSize.getWidth(); - this.height = plotSize.getHeight(); - this.createdLocation = location; - this.createdDirection = Direction.byYaw(location.getYaw()); - this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); - this.createdWorld = location.getWorld().getName(); - this.modified = Instant.now(); - initialize(); - initializeCorners(); - if (VirtualRealty.markerset != null) { - PlotManager.resetPlotMarker(this); - } - } - - public Plot(Location location, Material floorMaterial, Material borderMaterial, int length, int width, int height) { - this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; - this.ownedBy = null; - this.members = new HashSet<>(); - this.assignedBy = null; - this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); - this.floorMaterial = floorMaterial; - this.floorData = 0; - this.borderMaterial = borderMaterial; - this.borderData = 0; - this.plotSize = PlotSize.CUSTOM; - this.length = length; - this.width = width; - this.height = height; - this.createdLocation = location; - this.createdDirection = Direction.byYaw(location.getYaw()); - this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); - this.createdWorld = location.getWorld().getName(); - this.modified = Instant.now(); - initialize(); - initializeCorners(); - if (VirtualRealty.markerset != null) { - PlotManager.resetPlotMarker(this); - } - } - - - public Plot(ResultSet rs) { - try { - this.ID = rs.getInt("ID"); - this.ownedBy = rs.getString("ownedBy").isEmpty() ? null : UUID.fromString(rs.getString("ownedBy")); - this.members = new HashSet<>(); - String membersString = rs.getString("members"); - if (membersString != null && !membersString.isEmpty()) { - String[] membersArray = membersString.substring(0, membersString.length() - 1).split(";"); - for (String s : membersArray) { - members.add(UUID.fromString(s)); - } - } - this.assignedBy = rs.getString("assignedBy").equalsIgnoreCase("null") ? null : rs.getString("assignedBy"); - this.ownedUntilDate = rs.getTimestamp("ownedUntilDate").toLocalDateTime(); - this.floorMaterial = Material.getMaterial(rs.getString("floorMaterial").split(":")[0]); - this.floorData = rs.getString("floorMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("floorMaterial").split(":")[1]); - if (rs.getString("borderMaterial") != null) { - this.borderMaterial = Material.getMaterial(rs.getString("borderMaterial").split(":")[0]); - this.borderData = rs.getString("borderMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("borderMaterial").split(":")[1]); - } - this.plotSize = PlotSize.valueOf(rs.getString("plotSize")); - this.length = rs.getInt("length"); - this.width = rs.getInt("width"); - this.height = rs.getInt("height"); - ArrayList location = new ArrayList<>(Arrays.asList(rs.getString("createdLocation").subSequence(0, rs.getString("createdLocation").length() - 1).toString().split(";"))); - Location createLocation = new Location(Bukkit.getWorld(location.get(0)), Double.parseDouble(location.get(1)), Double.parseDouble(location.get(2)), Double.parseDouble(location.get(3)), Float.parseFloat(location.get(4)), Float.parseFloat(location.get(5))); - this.createdLocation = rs.getString("createdLocation").isEmpty() ? null : createLocation; - this.createdDirection = Direction.byYaw(createdLocation.getYaw()); - this.selectedGameMode = GameMode.CREATIVE; - this.createdWorld = location.get(0); - if (floorMaterial == null) { - floorMaterial = plotSize.getFloorMaterial(); - floorData = plotSize.getFloorData(); - } - if (borderMaterial == null) { - borderMaterial = plotSize.getBorderMaterial(); - borderData = plotSize.getBorderData(); - } - initializeCorners(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public boolean hasPermissionToPlot(Player player) { - if (player.hasPermission(Permission.PLOT_BUILD.getPermission())) return true; - if (members.contains(player.getUniqueId())) return true; - return ownedBy != null && ownedBy.equals(player.getUniqueId()); - } - - public boolean hasPlotMembership(Player player) { - if (members.contains(player.getUniqueId())) return true; - return ownedBy != null && ownedBy.equals(player.getUniqueId()); - } - - public boolean isOwnershipExpired() { - return ownedUntilDate.isBefore(LocalDateTime.now()); - } - - public int getXMin() { - return Math.min(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); - } - - public int getXMax() { - return Math.max(this.getBorderBottomLeftCorner().getBlockX(), this.borderTopRightCorner.getBlockX()); - } - - public int getZMin() { - return Math.min(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); - } - - public int getZMax() { - return Math.max(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); - } - - public int getID() { - return ID; - } - - public void setID(int ID) { - this.ID = ID; - } - - public UUID getOwnedBy() { - return ownedBy; - } - - public void setOwnedBy(UUID ownedBy) { - this.ownedBy = ownedBy; - members.remove(ownedBy); - updateMarker(); - modified(); - } - - public String getAssignedBy() { - return assignedBy; - } - - public void setAssignedBy(String assignedBy) { - this.assignedBy = assignedBy; - modified(); - } - - public LocalDateTime getOwnedUntilDate() { - return ownedUntilDate; - } - - public void setOwnedUntilDate(LocalDateTime ownedUntilDate) { - this.ownedUntilDate = ownedUntilDate; - updateMarker(); - modified(); - } - - public PlotSize getPlotSize() { - return plotSize; - } - - public void setPlotSize(PlotSize plotSize) { - this.plotSize = plotSize; - } - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public Material getFloorMaterial() { - return floorMaterial; - } - - public void setFloorMaterial(Material floorMaterial, byte data) { - this.floorMaterial = floorMaterial; - this.floorData = data; - initializeFloor(); - modified(); - } - - public Location getCreatedLocation() { - return createdLocation; - } - - public void setBorderMaterial(Material borderMaterial, byte data) { - this.borderMaterial = borderMaterial; - this.borderData = data; - modified(); - } - - public Material getBorderMaterial() { - return borderMaterial; - } - - public void setCreatedLocation(Location createdLocation) { - this.createdLocation = createdLocation; - } - - public BlockVector3 getBottomLeftCorner() { - return bottomLeftCorner; - } - - public void setBottomLeftCorner(BlockVector3 bottomLeftCorner) { - this.bottomLeftCorner = bottomLeftCorner; - } - - public BlockVector3 getTopRightCorner() { - return topRightCorner; - } - - public void setTopRightCorner(BlockVector3 topRightCorner) { - this.topRightCorner = topRightCorner; - } - - public BlockVector3 getBorderBottomLeftCorner() { - return borderBottomLeftCorner; - } - - public void setBorderBottomLeftCorner(BlockVector3 borderBottomLeftCorner) { - this.borderBottomLeftCorner = borderBottomLeftCorner; - } - - public BlockVector3 getBorderTopRightCorner() { - return borderTopRightCorner; - } - - public void setBorderTopRightCorner(BlockVector3 borderTopRightCorner) { - this.borderTopRightCorner = borderTopRightCorner; - } - - public BlockVector3 getBorderedCenter() { - return new Cuboid(borderBottomLeftCorner, borderTopRightCorner, createdLocation.getWorld()).getCenterVector(); - } - - public BlockVector3 getCenter() { - return new Cuboid(bottomLeftCorner, topRightCorner, createdLocation.getWorld()).getCenterVector(); - } - - public GameMode getSelectedGameMode() { - return selectedGameMode; - } - - public String getCreatedWorld() { - return createdWorld; - } - - public OfflinePlayer getPlotOwner() { - return ownedBy == null ? null : Bukkit.getOfflinePlayer(ownedBy); - } - - public void setSelectedGameMode(GameMode selectedGameMode) { - this.selectedGameMode = selectedGameMode; - } - - public void addMember(UUID uuid) { - members.add(uuid); - modified(); - } - - public void removeMember(UUID uuid) { - members.remove(uuid); - } - - public Set getMembers() { - return members; - } - - public Set getMembersPlayer() { - Set offlinePlayers = new HashSet<>(); - for (UUID member : members) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(member); - offlinePlayers.add(offlinePlayer); - } - return offlinePlayers; - } - - private void setFloorBlock(Block floorBlock) { - if (VirtualRealty.isLegacy) { - try { - Method m = Block.class.getDeclaredMethod("setType", Material.class); - m.setAccessible(true); - m.invoke(floorBlock, this.floorMaterial); - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(floorBlock, this.floorData); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - floorBlock.setType(floorMaterial); - } - modified(); - } - - private void initializeFloor() { - Location location = createdLocation; - Direction direction = Direction.byYaw(location.getYaw()); - switch(direction) { - case SOUTH: { - for (int x = location.getBlockX() - width + 1; x < location.getBlockX() + 1; x++) { - for (int z = location.getBlockZ(); z < location.getBlockZ() + length; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - case WEST: { - for (int x = location.getBlockX() - length + 1; x < location.getBlockX() + 1; x++) { - for (int z = location.getBlockZ() - width + 1; z < location.getBlockZ() + 1; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - case NORTH: { - for (int x = location.getBlockX(); x < location.getBlockX() + width; x++) { - for (int z = location.getBlockZ() - length + 1; z < location.getBlockZ() + 1; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - case EAST: { - for (int x = location.getBlockX(); x < location.getBlockX() + length; x++) { - for (int z = location.getBlockZ(); z < location.getBlockZ() + width; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - } - - public void initializeCorners() { - Location location = createdLocation; - Direction direction = Direction.byYaw(location.getYaw()); - Location location1; - Location location2; - Location border1; - Location border2; - switch(direction) { - case SOUTH: { - location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); - location2 = new Location(location.getWorld(), location.getBlockX() - width + 1, location.getBlockY() + height, location.getBlockZ() + length - 1); - border1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); - border2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); - break; - } - case WEST: { - location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); - location2 = new Location(location.getWorld(), location.getBlockX() - length + 1, location.getBlockY() + height, location.getBlockZ() - width + 1); - border1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); - border2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); - break; - } - case NORTH: { - location1 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() - 10, location.getBlockZ()); - location2 = new Location(location.getWorld(), location.getBlockX() + width - 1, location.getBlockY() + height, location.getBlockZ() - length + 1); - border1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); - border2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); - break; - } - case EAST: { - location1 = new Location(location.getWorld(), location.getBlockX() + length - 1, location.getBlockY() - 10, location.getBlockZ()); - location2 = new Location(location.getWorld(), location.getBlockX(), location.getBlockY() + height, location.getBlockZ() + width - 1); - border1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); - border2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - this.bottomLeftCorner = BlockVector3.at(location1.getBlockX(), location1.getBlockY(), location1.getBlockZ()); - this.topRightCorner = BlockVector3.at(location2.getBlockX(), location2.getBlockY(), location2.getBlockZ()); - this.borderBottomLeftCorner = BlockVector3.at(border1.getBlockX(), border1.getBlockY(), border1.getBlockZ()); - this.borderTopRightCorner = BlockVector3.at(border2.getBlockX(), border2.getBlockY(), border2.getBlockZ()); - } - - public void initialize() { - prepareBlocks(createdLocation); - } - - public Set getBorderBlocks() { - Set blocks = new HashSet<>(); - Location location = this.getCreatedLocation(); - Direction direction = Direction.byYaw(location.getYaw()); - int maxX; - int maxZ; - int minX; - int minZ; - switch(direction) { - case SOUTH: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + length + 1; - minX = location.getBlockX() - width + 1; - minZ = location.getBlockZ() - 1; - break; - } - case WEST: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX() - length + 1; - minZ = location.getBlockZ() - width; - break; - } - case NORTH: { - maxX = location.getBlockX() + width + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - length; - break; - } - case EAST: { - maxX = location.getBlockX() + length + 1; - maxZ = location.getBlockZ() + width + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - 1; - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - for (int x = minX - 1; x < maxX; x++) { - for (int z = minZ; z < maxZ; z++) { - if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { - blocks.add(location.getWorld().getBlockAt(x, location.getBlockY() + 1, z)); - } - } - } - return blocks; - } - - public Set getFloorBlocks() { - Set blocks = new HashSet<>(); - Location location = this.getCreatedLocation(); - Direction direction = Direction.byYaw(location.getYaw()); - int maxX; - int maxZ; - int minX; - int minZ; - switch(direction) { - case SOUTH: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + length + 1; - minX = location.getBlockX() - width + 1; - minZ = location.getBlockZ() - 1; - break; - } - case WEST: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX() - length + 1; - minZ = location.getBlockZ() - width; - break; - } - case NORTH: { - maxX = location.getBlockX() + width + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - length; - break; - } - case EAST: { - maxX = location.getBlockX() + length + 1; - maxZ = location.getBlockZ() + width + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - 1; - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - for (int x = minX - 1; x < maxX; x++) { - for (int z = minZ; z < maxZ; z++) { - blocks.add(location.getWorld().getBlockAt(x, location.getBlockY(), z)); - } - } - return blocks; - } - - public void setBorder(Material material, byte data) { - borderMaterial = material; - borderData = data; - for (Block borderBlock : getBorderBlocks()) { - if (VirtualRealty.isLegacy) { - borderBlock.setType(material); - try { - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(borderBlock, data); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - } else { - borderBlock.setType(material); - } - } - modified(); - } - - public void prepareBlocks(Location location) { - Direction direction = Direction.byYaw(location.getYaw()); - Location location1; - Location location2; - switch (direction) { - case SOUTH: { - location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); - location2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); - SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - break; - } - case WEST: { - location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); - location2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); - SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - break; - } - case NORTH: { - location1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); - location2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); - SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - break; - } - case EAST: { - location1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); - location2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); - SchematicUtil.save(ID, SchematicUtil.getStructure(location1.getBlock(), location2.getBlock())); - break; - } - } - for (Block floorBlock : getFloorBlocks()) { - for (int y = location.getBlockY() + height; y > location.getBlockY() - 1; y--) { - Block airBlock = location.getWorld().getBlockAt(floorBlock.getX(), y, floorBlock.getZ()); - airBlock.setType(Material.AIR); - } - floorBlock.setType(floorMaterial); - if (VirtualRealty.isLegacy) { - try { - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(floorBlock, plotSize.getFloorData()); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - } - } - int maxX = 0; - int maxZ = 0; - int minX = 0; - int minZ = 0; - switch(direction) { - case SOUTH: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + length + 1; - minX = location.getBlockX() - width + 1; - minZ = location.getBlockZ() - 1; - break; - } - case WEST: { - maxX = location.getBlockX() + 1 + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX() - length + 1; - minZ = location.getBlockZ() - width; - break; - } - case NORTH: { - maxX = location.getBlockX() + width + 1; - maxZ = location.getBlockZ() + 1 + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - length; - break; - } - case EAST: { - maxX = location.getBlockX() + length + 1; - maxZ = location.getBlockZ() + width + 1; - minX = location.getBlockX(); - minZ = location.getBlockZ() - 1; - break; - } - } - for (int x = minX - 1; x < maxX; x++) { - for (int z = minZ; z < maxZ; z++) { - if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { - Block borderBlock = location.getWorld().getBlockAt(x, location.getBlockY() + 1, z); - if (VirtualRealty.isLegacy) { - borderBlock.setType(plotSize.getBorderMaterial()); - try { - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(borderBlock, plotSize.getBorderData()); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - } else { - borderBlock.setType(plotSize.getBorderMaterial()); - } - } - } - } - } - - public void unloadPlot() { - switch (createdDirection) { - case SOUTH: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - width, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); - break; - } - case WEST: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - length, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - width)); - break; - } - case NORTH: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - length)); - break; - } - case EAST: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); - break; - } - } - } - - public String getMembersString() { - StringBuilder stringBuilder = new StringBuilder(); - for (UUID member : members) { - stringBuilder.append(member.toString()).append(";"); - } - return stringBuilder.toString(); - } - - public void insert() { - StringBuilder builder = new StringBuilder(); - builder.append(this.createdLocation.getWorld().getName() + ";"); - builder.append(this.createdLocation.getX() + ";"); - builder.append(this.createdLocation.getY() + ";"); - builder.append(this.createdLocation.getZ() + ";"); - builder.append(this.createdLocation.getYaw() + ";"); - builder.append(this.createdLocation.getPitch() + ";"); - try { - SQL.getStatement().execute("INSERT INTO `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + - "` (`ID`, `ownedBy`, `members`, `assignedBy`, `ownedUntilDate`," + - " `floorMaterial`, `borderMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`, `created`, `modified`) " + - "VALUES ('" + this.ID + "', '" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "','" + getMembersString() + "', '" + this.assignedBy + "', " + - "'" + Timestamp.valueOf(this.ownedUntilDate) + "', '" + this.floorMaterial + ":" + this.floorData + "', '" + this.borderMaterial + ":" + this.borderData + "'," + - " '" + this.plotSize + "', '" + this.length + "', '" + this.width + "', '" + this.height + "', '" + builder + "', '" + Timestamp.from(Instant.now()) + "', '" + Timestamp.from(Instant.now()) + "')"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void update() { - try { - SQL.getStatement().execute("UPDATE `" + - VirtualRealty.getPluginConfiguration().mysql.plotsTableName + - "` SET `ownedBy`='" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "'," + - " `members`='" + getMembersString() + "', `assignedBy`='" + this.assignedBy + "'," + - " `ownedUntilDate`='" + Timestamp.valueOf(this.ownedUntilDate) + "'," + - " `floorMaterial`='" + this.floorMaterial + ":" + this.floorData + "'," + - " `borderMaterial`='" + this.borderMaterial + ":" + this.borderData + "'," + - " `plotSize`='" + this.plotSize + "'," + - " `length`='" + this.length + "'," + - " `width`='" + this.width + "'," + - " `height`='" + this.height + "'," + - " `modified`='" + (this.modified != null ? Timestamp.from(this.modified) : Timestamp.from(Instant.now())) + "'" + - " WHERE `ID`='" + this.ID + "'"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void remove() { - this.unloadPlot(); - PlotManager.removeDynMapMarker(this); - try { - SQL.getStatement().execute("DELETE FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` WHERE `ID` = '" + ID + "';"); - } catch (SQLException e) { - e.printStackTrace(); - } - int id = ID; - File file = new File(VirtualRealty.plotsSchemaFolder, "plot" + id + ".region"); - if (file.exists()) - FileUtils.deleteQuietly(file); - PlotManager.plots.remove(this); - } - - public Direction getCreatedDirection() { - return createdDirection; - } - - public void setCreatedDirection(Direction createdDirection) { - this.createdDirection = createdDirection; - } - - public void updateMarker() { - PlotManager.resetPlotMarker(this); - } - - public void modified() { - this.modified = Instant.now(); - } - -} \ No newline at end of file diff --git a/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector2.java b/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector2.java deleted file mode 100644 index 7101190..0000000 --- a/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector2.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.plytki.virtualrealty.objects.math; - -import java.util.Vector; - -public class BlockVector2 extends Vector { - - private int x; - private int z; - - public BlockVector2(int x, int z) { - this.x = x; - this.z = z; - } - - public static BlockVector2 at(int x, int z) { - return new BlockVector2(x, z); - } - - public int getBlockX() { - return x; - } - - public void setX(int x) { - this.x = x; - } - - public int getBlockZ() { - return z; - } - - public void setZ(int z) { - this.z = z; - } - - public boolean containedWithin(BlockVector2 min, BlockVector2 max) { - return this.x >= min.x && this.x <= max.x && this.z >= min.z && this.z <= max.z; - } - - @Override - public String toString() { - return "(" + x + ", " + z + ")"; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector3.java b/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector3.java deleted file mode 100644 index 1194dd5..0000000 --- a/src/main/java/me/plytki/virtualrealty/objects/math/BlockVector3.java +++ /dev/null @@ -1,59 +0,0 @@ -package me.plytki.virtualrealty.objects.math; - -import org.bukkit.Location; - -public class BlockVector3 extends BlockVector2 { - - private int x; - private int y; - private int z; - - private BlockVector3(int x, int y, int z) { - super(x, z); - this.x = x; - this.y = y; - this.z = z; - } - - public static BlockVector3 at(int x, int y, int z) { - return new BlockVector3(x, y, z); - } - - public static BlockVector3 locationToVector(Location location) { - return new BlockVector3(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } - - public int getBlockX() { - return x; - } - - public void setX(int x) { - this.x = x; - } - - public int getBlockY() { - return y; - } - - public void setY(int y) { - this.y = y; - } - - public int getBlockZ() { - return z; - } - - public void setZ(int z) { - this.z = z; - } - - @Override - public String toString() { - return "(" + x + ", " + y + ", " + z + ")"; - } - - public String toSimpleString() { - return x + ", " + y + ", " + z; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/registry/VirtualPlaceholders.java b/src/main/java/me/plytki/virtualrealty/registry/VirtualPlaceholders.java deleted file mode 100644 index 3d86be8..0000000 --- a/src/main/java/me/plytki/virtualrealty/registry/VirtualPlaceholders.java +++ /dev/null @@ -1,123 +0,0 @@ -package me.plytki.virtualrealty.registry; - -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import org.bukkit.entity.Player; - -public class VirtualPlaceholders extends PlaceholderExpansion { - - private final VirtualRealty plugin; - - /** - * Since we register the expansion inside our own plugin, we - * can simply use this method here to get an instance of our - * plugin. - * - * @param plugin - * The instance of our plugin. - */ - public VirtualPlaceholders(VirtualRealty plugin){ - this.plugin = plugin; - } - - /** - * Because this is an internal class, - * you must override this method to let PlaceholderAPI know to not unregister your expansion class when - * PlaceholderAPI is reloaded - * - * @return true to persist through reloads - */ - @Override - public boolean persist(){ - return true; - } - - /** - * Because this is a internal class, this check is not needed - * and we can simply return {@code true} - * - * @return Always true since it's an internal class. - */ - @Override - public boolean canRegister(){ - return true; - } - - /** - * The name of the person who created this expansion should go here. - *
For convienience do we return the author from the plugin.yml - * - * @return The name of the author as a String. - */ - @Override - public String getAuthor(){ - return plugin.getDescription().getAuthors().toString(); - } - - /** - * The placeholder identifier should go here. - *
This is what tells PlaceholderAPI to call our onRequest - * method to obtain a value if a placeholder starts with our - * identifier. - *
The identifier has to be lowercase and can't contain _ or % - * - * @return The identifier in {@code %_%} as String. - */ - @Override - public String getIdentifier(){ - return "virtualrealty"; - } - - /** - * This is the version of the expansion. - *
You don't have to use numbers, since it is set as a String. - * - * For convienience do we return the version from the plugin.yml - * - * @return The version as a String. - */ - @Override - public String getVersion(){ - return plugin.getDescription().getVersion(); - } - - /** - * This is the method called when a placeholder with our identifier - * is found and needs a value. - *
We specify the value identifier in this method. - *
Since version 2.9.1 can you use OfflinePlayers in your requests. - * - * @param player - * A {@link org.bukkit.entity.Player Player}. - * @param identifier - * A String containing the identifier/value. - * - * @return possibly-null String of the requested identifier. - */ - @Override - public String onPlaceholderRequest(Player player, String identifier){ - if(player == null) - return ""; - - Plot plot = PlotManager.getBorderedPlot(player.getLocation()); - if (identifier.equals("plot_id")) { - if (plot == null) return ""; - return String.valueOf(plot.getID()); - } - if (identifier.equals("plot_owner")) { - if (plot == null) return ""; - if (plot.getOwnedBy() == null) return ""; - return String.valueOf(plot.getPlotOwner().getName()); - } - if (identifier.equals("is_plot_owner")) { - if (plot == null) return ""; - if (plot.getOwnedBy() == null) return "false"; - if (plot.getOwnedBy().equals(player.getUniqueId())) return "true"; - return "false"; - } - return null; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/sql/SQL.java b/src/main/java/me/plytki/virtualrealty/sql/SQL.java deleted file mode 100644 index 2a34081..0000000 --- a/src/main/java/me/plytki/virtualrealty/sql/SQL.java +++ /dev/null @@ -1,125 +0,0 @@ -package me.plytki.virtualrealty.sql; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.configs.PluginConfiguration; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; - -public class SQL { - - private static Connection connection; - private static Statement statement; - public static final long MYSQL_TIMEOUT_MS = 28800000; - private static long lastQuery = System.currentTimeMillis(); - - public static void connect() { - try { - switch (VirtualRealty.getPluginConfiguration().dataModel) { - case H2: { - Class.forName("me.plytki.virtualrealty.utils.h2.Driver"); - connection = DriverManager.getConnection("jdbc:h2:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data"); - break; - } - case SQLITE: { - Class.forName("org.sqlite.JDBC"); - File dataDir = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data"); - if (!dataDir.exists()) { - dataDir.mkdirs(); - } - connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.db"); - break; - } - case MYSQL: { - Class.forName("com.mysql.jdbc.Driver"); - connection = DriverManager.getConnection("jdbc:mysql://" + VirtualRealty.getPluginConfiguration().mysql.hostname + ":" + VirtualRealty.getPluginConfiguration().mysql.port + "/" + VirtualRealty.getPluginConfiguration().mysql.database + "?useSSL=" + VirtualRealty.getPluginConfiguration().mysql.useSSL + "&autoReconnect=true", VirtualRealty.getPluginConfiguration().mysql.user, VirtualRealty.getPluginConfiguration().mysql.password); - break; - } - } - createStatement(); - } catch (SQLException | ClassNotFoundException ex) { - ex.printStackTrace(); - } - } - - public static void createStatement() { - try { - statement = connection.createStatement(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public static void closeConnection() { - try { - if (statement != null && !statement.isClosed()) { - statement.close(); - } - if (connection != null) - connection.close(); - VirtualRealty.debug("Database connection closed"); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public static void createTables() { - try { - statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); - updateTables(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - public static void updateTables() { - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `borderMaterial` VARCHAR(32) AFTER `floorMaterial`;"); - } catch (SQLException ignored) { - - } - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `members` TEXT AFTER `ownedBy`;"); - } catch (SQLException ignored) { - - } - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `created` DATETIME AFTER `createdLocation`;"); - } catch (SQLException ignored) { - - } - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `modified` DATETIME AFTER `created`;"); - } catch (SQLException ignored) { - - } - } - - public static Statement getStatement() { - try { - if (System.currentTimeMillis() - lastQuery > MYSQL_TIMEOUT_MS) { - connection.close(); - statement.close(); - connect(); - } else if(connection.isClosed()) { - connect(); - } - lastQuery = System.currentTimeMillis(); - } catch (SQLException e) { - e.printStackTrace(); - } - return statement; - } - - - public static void setConnection(Connection connection) { - SQL.connection = connection; - } - - public static void setStatement(Statement statement) { - SQL.statement = statement; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/ConfigurationFactory.java b/src/main/java/me/plytki/virtualrealty/utils/ConfigurationFactory.java deleted file mode 100644 index 675de8a..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/ConfigurationFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import eu.okaeri.configs.ConfigManager; -import eu.okaeri.configs.serdes.commons.SerdesCommons; -import eu.okaeri.configs.validator.okaeri.OkaeriValidator; -import eu.okaeri.configs.yaml.bukkit.YamlBukkitConfigurer; -import me.plytki.virtualrealty.configs.MessagesConfiguration; -import me.plytki.virtualrealty.configs.PluginConfiguration; -import me.plytki.virtualrealty.configs.SizesConfiguration; - -import java.io.File; - -public class ConfigurationFactory { - - public ConfigurationFactory() { - - } - - public PluginConfiguration createPluginConfiguration(File pluginConfigurationFile) { - return ConfigManager.create(PluginConfiguration.class, (it) -> { - it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); - it.withBindFile(pluginConfigurationFile); - it.saveDefaults(); - it.load(true); - }); - } - - public SizesConfiguration createSizesConfiguration(File sizesConfigurationFile) { - return ConfigManager.create(SizesConfiguration.class, (it) -> { - it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); - it.withBindFile(sizesConfigurationFile); - it.saveDefaults(); - it.load(true); - }); - } - - public MessagesConfiguration createMessagesConfiguration(File messagesConfigurationFile) { - return ConfigManager.create(MessagesConfiguration.class, (it) -> { - it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); - it.withBindFile(messagesConfigurationFile); - it.saveDefaults(); - it.load(true); - }); - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/Permissions.java b/src/main/java/me/plytki/virtualrealty/utils/Permissions.java deleted file mode 100644 index 833e82e..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/Permissions.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import me.plytki.virtualrealty.VirtualRealty; -import org.bukkit.command.CommandSender; -import org.bukkit.permissions.Permission; - -public class Permissions { - - public static boolean hasPermission(CommandSender sender, Permission basePermission, String permission) { - Permission finalPermission = new Permission(basePermission.getName() + "." + permission); - if (!sender.hasPermission(finalPermission)) { - sender.sendMessage(VirtualRealty.PREFIX + "§cInsufficient permissions! §8(§7" + finalPermission.getName() + "§8)"); - return false; - } - return true; - } - - public static boolean hasPermission(CommandSender sender, String permission) { - Permission finalPermission = new Permission(permission); - if (!sender.hasPermission(finalPermission)) { - sender.sendMessage(VirtualRealty.PREFIX + "§cInsufficient permissions! §8(§7" + finalPermission.getName() + "§8)"); - return false; - } - return true; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/PlotUtil.java b/src/main/java/me/plytki/virtualrealty/utils/PlotUtil.java deleted file mode 100644 index 3fd3a69..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/PlotUtil.java +++ /dev/null @@ -1,41 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import me.plytki.virtualrealty.enums.Direction; -import me.plytki.virtualrealty.objects.Cuboid; -import me.plytki.virtualrealty.objects.math.BlockVector3; -import org.bukkit.Location; - -public class PlotUtil { - - public static Cuboid getPlotRegion(Location location, Direction direction, int length, int width, int height) { - Location location1; - Location location2; - switch(direction) { - case SOUTH: { - location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); - location2 = new Location(location.getWorld(), location.getBlockX() - width, location.getBlockY() + height, location.getBlockZ() + length); - break; - } - case WEST: { - location1 = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); - location2 = new Location(location.getWorld(), location.getBlockX() - length, location.getBlockY() + height, location.getBlockZ() - width); - break; - } - case NORTH: { - location1 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); - location2 = new Location(location.getWorld(), location.getBlockX() + width, location.getBlockY() + height, location.getBlockZ() - length); - break; - } - case EAST: { - location1 = new Location(location.getWorld(), location.getBlockX() + length, location.getBlockY() - 10, location.getBlockZ() - 1); - location2 = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + height, location.getBlockZ() + width); - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - return new Cuboid(BlockVector3.at(location1.getBlockX(), location1.getBlockY(), location1.getBlockZ()), - BlockVector3.at(location2.getBlockX(), location2.getBlockY(), location2.getBlockZ()), location.getWorld()); - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/ProtectionUtil.java b/src/main/java/me/plytki/virtualrealty/utils/ProtectionUtil.java deleted file mode 100644 index ea2208c..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/ProtectionUtil.java +++ /dev/null @@ -1,40 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.enums.Flag; -import me.plytki.virtualrealty.enums.Permission; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.time.LocalDateTime; - -public class ProtectionUtil { - - public static boolean canBuild(Player player, Location location) { - Plot plot = PlotManager.getBorderedPlot(location); - if (plot != null) { - if (plot.getOwnedBy() != null) { - if (!plot.getOwnedBy().equals(player.getUniqueId())) { - return false; - } else { - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - return false; - } - } - } else { - return false; - } - } - return true; - } - - public static boolean hasPermissionToWorld(Player player, Flag.World flag) { - if (player.hasPermission(Permission.WORLD_BUILD.getPermission())) return true; - if (player.hasPermission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".world." + flag.name().toLowerCase())) return true; - if (player.isOp()) return true; - return false; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/Reflections.java b/src/main/java/me/plytki/virtualrealty/utils/Reflections.java deleted file mode 100644 index 87a8916..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/Reflections.java +++ /dev/null @@ -1,271 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Entity; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public final class Reflections { - - public static final String SERVER_VERSION = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; - public static final boolean USE_PRE_13_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 13; - public static final boolean USE_PRE_12_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 12; - public static final boolean USE_PRE_9_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 9; - - private static final Map> CLASS_CACHE = new HashMap<>(); - private static final Map FIELD_CACHE = new HashMap<>(); - private static final Map> FIELD_ACCESSOR_CACHE = new HashMap<>(); - private static final Map METHOD_CACHE = new HashMap<>(); - private static final Class INVALID_CLASS = InvalidMarker.class; - private static final Method INVALID_METHOD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredMethod("invalidMethodMaker")); - private static final Field INVALID_FIELD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredField("invalidFieldMarker")); - private static final FieldAccessor INVALID_FIELD_ACCESSOR = getField(INVALID_CLASS, Void.class, 0); - - public static Class getClassOmitCache(String className) { - CLASS_CACHE.remove(className); - return getClass(className); - } - - public static Class getClass(String className) { - Class c = CLASS_CACHE.get(className); - - if (c != null) { - return c != INVALID_CLASS ? c : null; - } - - try { - c = Class.forName(className); - CLASS_CACHE.put(className, c); - } - catch (Exception ex) { - System.err.println("Could not retrieve class"); - - CLASS_CACHE.put(className, INVALID_CLASS); - } - return c; - } - - public static Class getNMSClass(String name) { - return getClass("net.minecraft.server." + SERVER_VERSION + "." + name); - } - - public static Class getCraftBukkitClass(String name) { - return getClass("org.bukkit.craftbukkit." + SERVER_VERSION + "." + name); - } - - public static Class getBukkitClass(String name) { - return getClass("org.bukkit." + name); - } - - public static Object getHandle(Entity entity) { - try { - return getMethod(entity.getClass(), "getHandle").invoke(entity); - } - catch (Exception ex) { - System.err.println("Could not get entity handle"); - return null; - } - } - - public static Object getHandle(World world) { - try { - return getMethod(world.getClass(), "getHandle").invoke(world); - } - catch (Exception ex) { - System.err.println("Could not get world handle"); - - return null; - } - } - - private static String constructFieldCacheKey(Class cl, String fieldName) { - return cl.getName() + "." + fieldName; - } - - public static Field getField(Class cl, String fieldName) { - String cacheKey = constructFieldCacheKey(cl, fieldName); - - Field field = FIELD_CACHE.get(cacheKey); - - if (field != null) { - return field != INVALID_FIELD ? field : null; - } - - try { - field = cl.getDeclaredField(fieldName); - FIELD_CACHE.put(cacheKey, field); - } - catch (Exception ex) { - System.err.println("Could not retrieve field"); - - FIELD_CACHE.put(cacheKey, INVALID_FIELD); - } - - return field; - } - - public static FieldAccessor getField(Class target, Class fieldType, int index) { - return getField(target, null, fieldType, index); - } - - @SuppressWarnings("unchecked") - private static FieldAccessor getField(Class target, String name, Class fieldType, int index) { - final String cacheKey = target.getName() + "." + (name != null ? name : "NONE") + "." + fieldType.getName() + "." + index; - - FieldAccessor output = (FieldAccessor) FIELD_ACCESSOR_CACHE.get(cacheKey); - - if (output != null) { - if (output == INVALID_FIELD_ACCESSOR) { - throw new IllegalArgumentException("Cannot find field with type " + fieldType); - } - - return output; - } - - for (final Field field : target.getDeclaredFields()) { - if ((name == null || field.getName().equals(name)) && fieldType.isAssignableFrom(field.getType()) && index-- <= 0) { - field.setAccessible(true); - - output = new FieldAccessor() { - - @Override - public T get(Object target) { - try { - return (T) field.get(target); - } catch (IllegalAccessException e) { - throw new RuntimeException("Cannot access reflection.", e); - } - } - - @Override - public void set(Object target, Object value) { - try { - field.set(target, value); - } catch (IllegalAccessException e) { - throw new RuntimeException("Cannot access reflection.", e); - } - } - - @Override - public boolean hasField(Object target) { - return field.getDeclaringClass().isAssignableFrom(target.getClass()); - } - }; - - break; - } - } - - if (output == null && target.getSuperclass() != null) { - output = getField(target.getSuperclass(), name, fieldType, index); - } - - FIELD_ACCESSOR_CACHE.put(cacheKey, output != null ? output : INVALID_FIELD_ACCESSOR); - - if (output == null) { - throw new IllegalArgumentException("Cannot find field with type " + fieldType); - } - - return output; - } - - public static Field getPrivateField(Class cl, String fieldName) { - String cacheKey = constructFieldCacheKey(cl, fieldName); - - Field c = FIELD_CACHE.get(cacheKey); - if (c != null) { - return c != INVALID_FIELD ? c : null; - } - - try { - c = cl.getDeclaredField(fieldName); - c.setAccessible(true); - FIELD_CACHE.put(cacheKey, c); - } - catch (Exception ex) { - System.err.println("Could not retrieve field"); - - FIELD_CACHE.put(cacheKey, INVALID_FIELD); - } - - return c; - } - - public static Method getMethod(Class cl, String method, Class... args) { - String cacheKey = cl.getName() + "." + method + "." + (args == null ? "NONE" : Arrays.toString(args)); - - Method output = METHOD_CACHE.get(cacheKey); - if (output != null) { - return output != INVALID_METHOD ? output : null; - } - - for (Method m : cl.getMethods()) { - if (m.getName().equals(method) && (args == null || classListEqual(args, m.getParameterTypes()))) { - output = m; - break; - } - } - - METHOD_CACHE.put(cacheKey, output == null ? INVALID_METHOD : output); - return output; - } - - public static Method getMethod(Class cl, String method) { - return getMethod(cl, method, null); - } - - public static Constructor getConstructor(Class clazz, Class... arguments) { - for (Constructor constructor : clazz.getDeclaredConstructors()) { - if (Arrays.equals(constructor.getParameterTypes(), arguments)) { - return constructor; - } - } - - return null; - } - - public static boolean classListEqual(Class[] l1, Class[] l2) { - if (l1.length != l2.length) { - return false; - } - - for (int i = 0; i < l1.length; i++) { - if (l1[i] != l2[i]) { - return false; - } - } - - return true; - } - - public interface ConstructorInvoker { - Object invoke(Object... arguments); - } - - public interface MethodInvoker { - Object invoke(Object target, Object... arguments); - } - - public interface FieldAccessor { - T get(Object target); - - void set(Object target, Object value); - - boolean hasField(Object target); - } - - private static class InvalidMarker { - public Void invalidFieldMarker; - public void invalidMethodMaker() {} - } - - private Reflections() {} - -} - diff --git a/src/main/java/me/plytki/virtualrealty/utils/SafeUtil.java b/src/main/java/me/plytki/virtualrealty/utils/SafeUtil.java deleted file mode 100644 index 61d809c..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/SafeUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.plytki.virtualrealty.utils; - -public class SafeUtil { - - private static void reportUnsafe(Throwable th) { - try { - throw new Exception(th.getMessage()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static T safeInit(SafeInitializer initializer) { - try { - return initializer.initialize(); - } catch (Exception e) { - reportUnsafe(e); - return null; - } - } - - @FunctionalInterface - public interface SafeInitializer { - T initialize() throws Exception; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java b/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java deleted file mode 100644 index b99ba70..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/SchematicUtil.java +++ /dev/null @@ -1,154 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.managers.PlotManager; -import me.plytki.virtualrealty.objects.Plot; -import me.plytki.virtualrealty.utils.data.Data; -import me.plytki.virtualrealty.utils.multiversion.VMaterial; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; - -import java.io.*; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.zip.Deflater; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.InflaterInputStream; - -public class SchematicUtil { - - public static String[] getStructure(Block block, Block block2) { - long time = System.currentTimeMillis(); - int minX = Math.min(block.getX(), block2.getX()); - int minZ = Math.min(block.getZ(), block2.getZ()); - int minY = Math.min(block.getY(), block2.getY()); - int maxX = Math.max(block.getX(), block2.getX()); - int maxZ = Math.max(block.getZ(), block2.getZ()); - int maxY = Math.max(block.getY(), block2.getY()); - List blocks = new ArrayList<>(); - for (int x = minX; x <= maxX; ++x) { - for (int y = minY; y <= maxY; ++y) { - for (int z = minZ; z <= maxZ; ++z) { - Block b = block.getWorld().getBlockAt(x, y, z); - if (b.getType() != Material.AIR) { - if (VirtualRealty.isLegacy) { - blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getType().getId() + ";" + b.getData()); - } else { - blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getBlockData().getAsString().substring(10)); - } - } - } - } - } - VirtualRealty.debug("Getted and serialized blocks in: " + (System.currentTimeMillis() - time) + " ms"); - return blocks.toArray(new String[0]); - } - - public static void paste(int plotID, Location l) { - long time = System.currentTimeMillis(); - String[] blocks = load(plotID); - if (blocks == null) return; - Plot plot = PlotManager.getPlot(plotID); - Location location = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderBottomLeftCorner().getBlockX(), plot.getBorderBottomLeftCorner().getBlockY(), plot.getBorderBottomLeftCorner().getBlockZ()); - Location location2 = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderTopRightCorner().getBlockX(), plot.getBorderTopRightCorner().getBlockY(), plot.getBorderTopRightCorner().getBlockZ()); - Block pos1Block = location.getBlock(); - Block pos2Block = location2.getBlock(); - int minX = Math.min(pos1Block.getX(), pos2Block.getX()); - int minZ = Math.min(pos1Block.getZ(), pos2Block.getZ()); - int minY = Math.min(pos1Block.getY(), pos2Block.getY()); - int maxX = Math.max(pos1Block.getX(), pos2Block.getX()); - int maxZ = Math.max(pos1Block.getZ(), pos2Block.getZ()); - int maxY = Math.max(pos1Block.getY(), pos2Block.getY()); - for (int x = minX; x <= maxX; ++x) { - for (int y = minY; y <= maxY; ++y) { - for (int z = minZ; z <= maxZ; ++z) { - Block b = location.getWorld().getBlockAt(x, y, z); - b.setType(Material.AIR); - } - } - } - if (blocks[0].isEmpty()) return; - for (String block : blocks) { - String[] cords = block.split(";"); - int x = Integer.parseInt(cords[0]); - int y = Integer.parseInt(cords[1]); - int z = Integer.parseInt(cords[2]); - Location displaced = l.clone(); - displaced.add(x, y, z); - Block b = displaced.getBlock(); - if (VirtualRealty.isLegacy) { - try { - Method m = Block.class.getDeclaredMethod("setType", Material.class); - m.setAccessible(true); - m.invoke(b, VMaterial.getMaterial(Integer.parseInt(cords[3]))); - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(b, (byte) Integer.parseInt(cords[4])); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - BlockData blockData = Bukkit.createBlockData("minecraft:" + cords[3]); - b.setBlockData(blockData); - } - b.getState().update(true); - } - VirtualRealty.debug("Pasted in: " + (System.currentTimeMillis() - time) + " ms"); - } - - public static void save(int plotID, String[] blocks) { - long time = System.currentTimeMillis(); - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); - - StringBuilder stringBuilder = new StringBuilder(); - for (String s : blocks) { - stringBuilder.append(s).append("|"); - } - String plotString = stringBuilder.toString(); - if (plotString.isEmpty()) - plotString = "clear|"; - try { - new Data().compressData(plotString.substring(0, plotString.length() - 1).getBytes(StandardCharsets.UTF_8), f); - } catch (IOException e) { - e.printStackTrace(); - } - VirtualRealty.debug("Saved in: " + (System.currentTimeMillis() - time) + " ms"); - } - - public static String[] load(int plotID) { - long time = System.currentTimeMillis(); - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); - if (f.exists()) { - String loaded = null; - try { - loaded = new String(new Data().decompressData(f)); - } catch (IOException e) { - e.printStackTrace(); - } - if (loaded.equalsIgnoreCase("clear")) return new String[]{""}; - VirtualRealty.debug("Loaded in: " + (System.currentTimeMillis() - time) + " ms"); - return loaded.split("\\|"); - } - return null; - } - - public static List oldLoad(int plotID) { - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".schem"); - List loaded = new ArrayList<>(); - try { - FileInputStream streamIn = new FileInputStream(f); - ObjectInputStream objectinputstream = new ObjectInputStream(streamIn); - loaded = (List)objectinputstream.readObject(); - objectinputstream.close(); - } catch (Exception e) { - e.printStackTrace(); - } - return loaded; - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/UUIDUtils.java b/src/main/java/me/plytki/virtualrealty/utils/UUIDUtils.java deleted file mode 100644 index ce40e3c..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/UUIDUtils.java +++ /dev/null @@ -1,16 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import java.util.UUID; - -public class UUIDUtils { - - public static boolean isValidUUID(String uuidString) { - try { - UUID.fromString(uuidString); - return true; - } catch (Exception e) { - return false; - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/UpdateChecker.java b/src/main/java/me/plytki/virtualrealty/utils/UpdateChecker.java deleted file mode 100644 index 34bd2e0..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/UpdateChecker.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.plytki.virtualrealty.utils; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import me.plytki.virtualrealty.VirtualRealty; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; - -public class UpdateChecker { - - private static final String VERSION_URL = "https://api.spiget.org/v2/resources/95599/versions/latest"; - private static final String DESCRIPTION_URL = "https://api.spiget.org/v2/resources/95599/updates/latest"; - - public static String[] getUpdate() { - try { - JsonObject latestVersionObj = getURLResults(VERSION_URL); - String newVersion = latestVersionObj.get("name").getAsString(); - JsonObject updateDesc = getURLResults(DESCRIPTION_URL); - String updateName = updateDesc.get("title").getAsString(); - return new String[] { newVersion, updateName }; - } catch (IOException ex) { - VirtualRealty.getInstance().getLogger().severe("Failed to get plugin update information, is Spiget down?"); - return null; - } - } - - private static JsonObject getURLResults(String urlStr) throws IOException { - URL url = new URL(urlStr); - HttpURLConnection connection = (HttpURLConnection)url.openConnection(); - connection.addRequestProperty("User-Agent", "AdvancedTeleportPA"); - return new JsonParser().parse(new InputStreamReader(connection.getInputStream())).getAsJsonObject(); - } - -} - - diff --git a/src/main/java/me/plytki/virtualrealty/utils/data/Data.java b/src/main/java/me/plytki/virtualrealty/utils/data/Data.java deleted file mode 100644 index 0ff5e38..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/data/Data.java +++ /dev/null @@ -1,31 +0,0 @@ -package me.plytki.virtualrealty.utils.data; - -import java.io.*; -import java.util.zip.*; - -public class Data { - - public void compressData(byte[] data, File file) throws IOException { - try (OutputStream outputStream = new FileOutputStream(file)) { - Deflater d = new Deflater(); - DeflaterOutputStream dout = new DeflaterOutputStream(outputStream, d); - dout.write(data); - dout.close(); - } - } - - public byte[] decompressData(File file) throws IOException { - try (InputStream inputStream = new FileInputStream(file)) { - InflaterInputStream newInput = new InflaterInputStream(inputStream); - ByteArrayOutputStream bout = new ByteArrayOutputStream(512); - int b; - while ((b = newInput.read()) != -1) { - bout.write(b); - } - newInput.close(); - bout.close(); - return bout.toByteArray(); - } - } - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java b/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java deleted file mode 100644 index c3c88bb..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/multiversion/Chat.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.plytki.virtualrealty.utils.multiversion; - -import me.plytki.virtualrealty.VirtualRealty; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class Chat { - - private final BaseComponent text; - - public Chat(BaseComponent text) { - this.text = text; - } - - public Chat(String text) { - this.text = new TextComponent(text); - } - - public void sendTo(CommandSender sender) { - if (sender instanceof Player) { - Player player = (Player) sender; - if (VirtualRealty.isLegacy) { - try { - Method m = Player.class.getDeclaredMethod("sendMessage", BaseComponent.class); - m.setAccessible(true); - m.invoke(player, text); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } else { - player.spigot().sendMessage(text); - } - } else { - sender.sendMessage(text.toLegacyText()); - } - } - - -} diff --git a/src/main/java/me/plytki/virtualrealty/utils/multiversion/VMaterial.java b/src/main/java/me/plytki/virtualrealty/utils/multiversion/VMaterial.java deleted file mode 100644 index 3e651a4..0000000 --- a/src/main/java/me/plytki/virtualrealty/utils/multiversion/VMaterial.java +++ /dev/null @@ -1,60 +0,0 @@ -package me.plytki.virtualrealty.utils.multiversion; - -import me.plytki.virtualrealty.VirtualRealty; -import me.plytki.virtualrealty.exceptions.MaterialMatchException; -import org.bukkit.Material; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class VMaterial { - - public static Material getMaterial(int materialID) throws MaterialMatchException { - if (VirtualRealty.isLegacy) { - try { - Method m = Material.class.getDeclaredMethod("getMaterial", int.class); - m.setAccessible(true); - return (Material) m.invoke(Material.class, materialID); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } else { - int counter = 1; - for (Material material : Material.values()) { - if (counter == materialID) { - return material; - } - counter++; - } - } - throw new MaterialMatchException("Couldn't parse material: " + materialID); - } - - public static Material catchMaterial(String material) throws MaterialMatchException { - try { - Method m = Material.class.getDeclaredMethod("getMaterial", String.class); - m.setAccessible(true); - Material mat = (Material) m.invoke(Material.class, material); - if (mat == null) { - throw new MaterialMatchException("Couldn't parse material: \"" + material + "\""); - } - return mat; - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } - - public static Material getMaterial(String material) { - try { - Method m = Material.class.getDeclaredMethod("getMaterial", String.class); - m.setAccessible(true); - return (Material) m.invoke(Material.class, material); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } - - -} From f8fc35456708392d68d29b10549c8b20c661f46d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 27 Jan 2022 15:28:19 +0100 Subject: [PATCH 08/23] v1.8.0 --- virtualrealty.iml | 1 + 1 file changed, 1 insertion(+) diff --git a/virtualrealty.iml b/virtualrealty.iml index 84ca1fd..fa730ca 100644 --- a/virtualrealty.iml +++ b/virtualrealty.iml @@ -18,6 +18,7 @@ + From fb772e34b02ae03ab156ad9518b136d03647b38a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 3 Mar 2022 20:16:36 +0100 Subject: [PATCH 09/23] Update --- pom.xml | 4 ++-- virtualrealty.iml | 4 +--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 5153902..8a010ef 100644 --- a/pom.xml +++ b/pom.xml @@ -114,11 +114,11 @@ dynmap-repo - http://repo.mikeprimm.com/ + https://repo.mikeprimm.com/ placeholderapi - http://repo.extendedclip.com/content/repositories/placeholderapi/ + https://repo.extendedclip.com/content/repositories/placeholderapi/ diff --git a/virtualrealty.iml b/virtualrealty.iml index fa730ca..d44b105 100644 --- a/virtualrealty.iml +++ b/virtualrealty.iml @@ -18,7 +18,6 @@ - @@ -38,7 +37,6 @@ - - + \ No newline at end of file From eed37a0d0ea8d797eb0ffe19dcb163b0d82d0033 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 3 Mar 2022 20:27:25 +0100 Subject: [PATCH 10/23] Update --- pom.xml | 86 +- .../modnmetl/virtualrealty/VirtualRealty.java | 557 ++++++------- .../commands/CommandManager.java | 352 +++++++++ .../virtualrealty/commands/PlotCommand.java | 369 --------- .../virtualrealty/commands/SubCommand.java | 54 ++ .../commands/VirtualRealtyCommand.java | 734 ------------------ .../commands/plot/PlotCommand.java | 66 ++ .../plot/subcommand/AddSubCommand.java | 90 +++ .../plot/subcommand/GmSubCommand.java | 92 +++ .../plot/subcommand/InfoSubCommand.java | 57 ++ .../plot/subcommand/KickSubCommand.java | 88 +++ .../plot/subcommand/ListSubCommand.java | 100 +++ .../plot/subcommand/TpSubCommand.java | 65 ++ .../commands/vrplot/VirtualRealtyCommand.java | 72 ++ .../vrplot/subcommand/AssignSubCommand.java | 86 ++ .../vrplot/subcommand/CreateSubCommand.java | 219 ++++++ .../vrplot/subcommand/InfoSubCommand.java | 111 +++ .../vrplot/subcommand/ListSubCommand.java | 64 ++ .../vrplot/subcommand/ReloadSubCommand.java | 49 ++ .../vrplot/subcommand/RemoveSubCommand.java | 53 ++ .../vrplot/subcommand/SetSubCommand.java | 242 ++++++ .../vrplot/subcommand/TpSubCommand.java | 60 ++ .../vrplot/subcommand/UnassignSubCommand.java | 55 ++ .../configs/MessagesConfiguration.java | 114 ++- .../configs/PermissionsConfiguration.java | 51 ++ .../configs/PluginConfiguration.java | 126 ++- .../configs/SizesConfiguration.java | 54 +- .../modnmetl/virtualrealty/enums/Flag.java | 33 - .../virtualrealty/enums/PlotSize.java | 47 +- .../virtualrealty/enums/ServerVersion.java | 8 + .../virtualrealty/enums/items/VItem.java | 8 + .../enums/materials/InteractMaterial.java | 144 ++++ .../enums/materials/SwitchMaterial.java | 30 + .../permissions/ManagementPermission.java | 37 + .../enums/permissions/RegionPermission.java | 41 + .../exceptions/FailedCommandExecution.java | 9 + ...istener.java => PlotEntranceListener.java} | 46 +- .../listeners/ProtectionListener.java | 472 ----------- .../listeners/VirtualListener.java | 3 - .../player/PlayerActionListener.java | 30 + .../listeners/plot/BorderListener.java | 44 -- .../protection/BorderProtectionListener.java | 39 + .../protection/PlotProtectionListener.java | 609 +++++++++++++++ .../protection/WorldProtectionListener.java | 207 +++++ .../listeners/world/WorldListener.java | 49 -- .../virtualrealty/managers/PlotManager.java | 70 +- .../managers/PlotMemberManager.java | 23 + .../modnmetl/virtualrealty/objects/Plot.java | 652 ++++++---------- .../virtualrealty/objects/PlotMember.java | 140 ++++ .../objects/math/BlockVector3.java | 8 +- .../objects/{ => region}/Cuboid.java | 5 +- .../objects/region/GridStructure.java | 208 +++++ .../registry/VirtualPlaceholders.java | 3 +- .../modnmetl/virtualrealty/sql/Database.java | 117 +++ .../com/modnmetl/virtualrealty/sql/SQL.java | 120 --- .../utils/ConfigurationFactory.java | 46 -- .../virtualrealty/utils/EnumUtils.java | 18 + .../virtualrealty/utils/PermissionUtil.java | 18 + .../virtualrealty/utils/ProtectionUtil.java | 40 - .../virtualrealty/utils/Reflections.java | 271 ------- .../utils/{PlotUtil.java => RegionUtil.java} | 6 +- .../virtualrealty/utils/SafeUtil.java | 27 - .../virtualrealty/utils/SchematicUtil.java | 150 ---- .../virtualrealty/utils/WorldUtil.java | 34 + .../configuration/ConfigurationFactory.java | 91 +++ .../data/{Data.java => DataCompressor.java} | 5 +- .../virtualrealty/utils/data/ItemBuilder.java | 244 ++++++ .../utils/data/OldSchematicUtil.java | 90 +++ .../utils/data/SchematicUtil.java | 163 ++++ .../virtualrealty/utils/data/SkullUtil.java | 46 ++ .../utils/data/VirtualBlock.java | 47 ++ .../utils/loader/CustomClassLoader.java | 12 + .../utils/multiversion/Chat.java | 2 +- .../utils/multiversion/VMaterial.java | 2 +- src/main/resources/plugin.yml | 3 +- virtualrealty.iml | 27 +- 76 files changed, 5232 insertions(+), 3378 deletions(-) create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/SubCommand.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/AddSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/GmSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/InfoSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/KickSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/ListSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/AssignSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ListSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ReloadSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/RemoveSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/SetSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/UnassignSubCommand.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/configs/PermissionsConfiguration.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/Flag.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/ServerVersion.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/items/VItem.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/materials/InteractMaterial.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/materials/SwitchMaterial.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/permissions/ManagementPermission.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/permissions/RegionPermission.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandExecution.java rename src/main/java/com/modnmetl/virtualrealty/listeners/{plot/PlotListener.java => PlotEntranceListener.java} (69%) delete mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/player/PlayerActionListener.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/protection/BorderProtectionListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/protection/PlotProtectionListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/protection/WorldProtectionListener.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/managers/PlotMemberManager.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/PlotMember.java rename src/main/java/com/modnmetl/virtualrealty/objects/{ => region}/Cuboid.java (98%) create mode 100644 src/main/java/com/modnmetl/virtualrealty/objects/region/GridStructure.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/sql/Database.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/sql/SQL.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/EnumUtils.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/PermissionUtil.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java rename src/main/java/com/modnmetl/virtualrealty/utils/{PlotUtil.java => RegionUtil.java} (91%) delete mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/WorldUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/configuration/ConfigurationFactory.java rename src/main/java/com/modnmetl/virtualrealty/utils/data/{Data.java => DataCompressor.java} (92%) create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/data/ItemBuilder.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/data/OldSchematicUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/data/SchematicUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/data/SkullUtil.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/data/VirtualBlock.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/loader/CustomClassLoader.java diff --git a/pom.xml b/pom.xml index 8a010ef..1416b96 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.modnmetl virtualrealty - 1.8.0 + 2.0.0 jar A plot creation and management plugin for Minecraft @@ -16,15 +16,6 @@ UTF-8 - - - build - - ../target - - - - @@ -39,31 +30,15 @@ org.apache.maven.plugins maven-shade-plugin 3.2.4 - - - package - - shade - - - false - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.1 org.bstats - com.modnmetl.virtualrealty.utils + com.modnmetl.virtualrealty.utils.bstats org.apache.commons.io - com.modnmetl.virtualrealty.utils + com.modnmetl.virtualrealty.utils.apache @@ -79,6 +54,7 @@ *:* META-INF/** + LICENSE @@ -104,10 +80,6 @@ sonatype https://oss.sonatype.org/content/groups/public/ - - panda-repository - https://repo.panda-lang.org/ - okaeri-repo https://storehouse.okaeri.eu/repository/maven-public/ @@ -120,13 +92,18 @@ placeholderapi https://repo.extendedclip.com/content/repositories/placeholderapi/ + + codemc-repo + https://repo.codemc.org/repository/maven-public/ + default + org.jetbrains annotations - 21.0.1 + 22.0.0 provided @@ -141,32 +118,29 @@ 1.13.2-R0.1-SNAPSHOT provided - - - - - - org.bstats bstats-bukkit - 2.2.1 + 3.0.0 compile eu.okaeri okaeri-configs-yaml-bukkit - 3.1.0 + 4.0.0-beta9 + compile eu.okaeri - okaeri-configs-serdes-commons - 3.1.0 + okaeri-configs-serdes-bukkit + 4.0.0-beta9 + compile eu.okaeri okaeri-configs-validator-okaeri - 3.1.0 + 4.0.0-beta9 + compile commons-io @@ -174,12 +148,6 @@ 2.11.0 compile - - org.apache.commons - commons-lang3 - 3.12.0 - compile - org.dynmap dynmap-api @@ -198,6 +166,24 @@ ${project.version} provided + + org.projectlombok + lombok + 1.18.22 + provided + + + de.tr7zw + item-nbt-api-plugin + 2.9.1 + compile + + + com.zaxxer + HikariCP + 5.0.1 + compile + diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java index c6a6618..db5b2e8 100644 --- a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -1,33 +1,36 @@ package com.modnmetl.virtualrealty; -import com.modnmetl.virtualrealty.commands.PlotCommand; -import com.modnmetl.virtualrealty.commands.VirtualRealtyCommand; -import com.modnmetl.virtualrealty.configs.MessagesConfiguration; -import com.modnmetl.virtualrealty.configs.PluginConfiguration; -import com.modnmetl.virtualrealty.configs.SizesConfiguration; -import com.modnmetl.virtualrealty.enums.Flag; +import com.modnmetl.virtualrealty.commands.CommandManager; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.commands.plot.PlotCommand; +import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; +import com.modnmetl.virtualrealty.configs.*; import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.enums.ServerVersion; import com.modnmetl.virtualrealty.exceptions.MaterialMatchException; -import com.modnmetl.virtualrealty.listeners.plot.BorderListener; -import com.modnmetl.virtualrealty.listeners.plot.PlotListener; -import com.modnmetl.virtualrealty.listeners.world.WorldListener; +import com.modnmetl.virtualrealty.listeners.player.PlayerActionListener; +import com.modnmetl.virtualrealty.listeners.protection.BorderProtectionListener; +import com.modnmetl.virtualrealty.listeners.PlotEntranceListener; +import com.modnmetl.virtualrealty.listeners.protection.PlotProtectionListener; +import com.modnmetl.virtualrealty.listeners.protection.WorldProtectionListener; import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.managers.PlotMemberManager; import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.premiumloader.PremiumLoader; import com.modnmetl.virtualrealty.registry.VirtualPlaceholders; -import com.modnmetl.virtualrealty.sql.SQL; -import com.modnmetl.virtualrealty.utils.ConfigurationFactory; -import com.modnmetl.virtualrealty.utils.SchematicUtil; +import com.modnmetl.virtualrealty.sql.Database; +import com.modnmetl.virtualrealty.utils.configuration.ConfigurationFactory; +import com.modnmetl.virtualrealty.utils.loader.CustomClassLoader; import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; -import com.modnmetl.virtualrealty.listeners.ProtectionListener; import com.modnmetl.virtualrealty.utils.UpdateChecker; +import com.zaxxer.hikari.HikariDataSource; +import de.tr7zw.nbtapi.utils.VersionChecker; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.LineIterator; import org.bstats.bukkit.Metrics; import org.bstats.charts.AdvancedPie; import org.bstats.charts.SimplePie; import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.command.CommandExecutor; import org.bukkit.permissions.Permission; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; @@ -37,26 +40,35 @@ import org.dynmap.markers.MarkerIcon; import org.dynmap.markers.MarkerSet; +import javax.sql.DataSource; import java.io.*; -import java.nio.charset.StandardCharsets; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.Statement; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.sql.SQLException; import java.util.*; -import java.util.concurrent.Callable; +import java.util.logging.Level; public final class VirtualRealty extends JavaPlugin { - public final Locale locale = Locale.getDefault(); - public final List availableLocales = new ArrayList<>(Arrays.asList(new Locale("en", "GB"), new Locale("es", "ES"), new Locale("pl", "PL"))); + public Locale locale = Locale.getDefault(); //CORE private static VirtualRealty instance; + private static ClassLoader loader; public static final String PREFIX = "§a§lVR §8§l» §7"; - public static ArrayList tasks = new ArrayList<>(); - private static final ArrayList preVersions = new ArrayList<>(); - public static boolean isLegacy = false; + public static LinkedList tasks = new LinkedList<>(); + private static final LinkedList preVersions = new LinkedList<>(); + public static boolean legacyVersion = false; + public static ServerVersion currentServerVersion = ServerVersion.MODERN; public static final Permission GLOBAL_PERMISSION = new Permission("virtualrealty"); + private static Object premium; + public static boolean upToDate; + public static String latestVersion; //FILES public static File plotsFolder; @@ -64,9 +76,14 @@ public final class VirtualRealty extends JavaPlugin { public PluginConfiguration pluginConfiguration; public SizesConfiguration sizesConfiguration; public MessagesConfiguration messagesConfiguration; + public PermissionsConfiguration permissionsConfiguration; private final File pluginConfigurationFile = new File(this.getDataFolder(), "config.yml"); private final File sizesConfigurationFile = new File(this.getDataFolder(), "sizes.yml"); + private final File permissionsConfigurationFile = new File(this.getDataFolder(), "permissions.yml"); private final File languagesDirectory = new File(this.getDataFolder(), "messages"); + private final File databaseFolder = new File(this.getDataFolder().getAbsolutePath(), File.separator + "data" + File.separator); + private final File databaseFile = new File(databaseFolder, "data.db"); + private File loaderFile; //DYNMAP API public static boolean isDynmapPresent = false; @@ -77,153 +94,158 @@ public final class VirtualRealty extends JavaPlugin { @Override public void onEnable() { instance = this; + loader = getClassLoader(); + VersionChecker.hideOk = true; if (checkLegacyVersions()) { - isLegacy = true; + legacyVersion = true; + currentServerVersion = ServerVersion.LEGACY; + } + databaseFolder.mkdirs(); + plotsFolder = new File(getInstance().getDataFolder().getAbsolutePath(), "plots"); + plotsFolder.mkdirs(); + plotsSchemaFolder = new File(plotsFolder.getAbsolutePath(), "primary-terrain"); + plotsSchemaFolder.mkdirs(); + reloadConfigs(); + this.locale = new Locale(pluginConfiguration.locale.split("_")[0], pluginConfiguration.locale.split("_")[1]); + configureMessages(); + if (ServerVersion.valueOf(pluginConfiguration.initServerVersion) == ServerVersion.LEGACY && currentServerVersion == ServerVersion.MODERN) { + this.getLogger().severe(" » ------------------------------------------------------------------------------------------------ « "); + this.getLogger().severe(" You cannot migrate existing legacy plots (1.8-1.12) to a non-legacy server version (1.13 and higher)"); + this.getLogger().severe(" » ------------------------------------------------------------------------------------------------ « "); + this.getPluginLoader().disablePlugin(this); + return; + } + if (ServerVersion.valueOf(pluginConfiguration.initServerVersion) == ServerVersion.MODERN && currentServerVersion == ServerVersion.LEGACY) { + this.getLogger().severe(" » ------------------------------------------------------------------------------------------------ « "); + this.getLogger().severe(" You cannot migrate existing non-legacy plots (1.13 and higher) to a legacy server version (1.8-1.12)"); + this.getLogger().severe(" » ------------------------------------------------------------------------------------------------ « "); + this.getPluginLoader().disablePlugin(this); + return; } String[] updateCheck = UpdateChecker.getUpdate(); if (updateCheck != null) { if (!updateCheck[0].equals(this.getDescription().getVersion())) { + upToDate = false; + latestVersion = updateCheck[0]; this.getLogger().info("A newer version is available!"); this.getLogger().info("The current version you use: " + this.getDescription().getVersion()); this.getLogger().info("Latest version available: " + updateCheck[0]); this.getLogger().info("Download link: https://www.spigotmc.org/resources/virtual-realty.95599/"); } else { + upToDate = true; + latestVersion = this.getDescription().getVersion(); this.getLogger().info("Plugin is up to date!"); } } - try { - checkConfig(); - checkSizesConfig(); - } catch (IOException e) { - e.printStackTrace(); - } - plotsFolder = new File(getInstance().getDataFolder().getAbsolutePath(), "plots"); - plotsFolder.mkdirs(); - plotsSchemaFolder = new File(plotsFolder.getAbsolutePath(), "primary-terrain"); - plotsSchemaFolder.mkdirs(); - spawnLocales(); - reformatConfig(); - reloadConfigs(); - if (!pluginConfiguration.licenseKey.isEmpty()) { - //LOAD premium + if (!pluginConfiguration.license.key.isEmpty() && !pluginConfiguration.license.email.isEmpty()) { + try { + runLoader(new URL("http://license.mineproxy.com/virtualrealty/premium"), pluginConfiguration.license.key, pluginConfiguration.license.email, this.getDescription().getVersion()); + } catch (IOException | InstantiationException | IllegalAccessException | ClassNotFoundException e) { + getLogger().log(Level.WARNING, "Loading of premium features failed."); + } } registerMetrics(); loadSizesConfiguration(); - connectToDatabase(); + try { + connectToDatabase(); + } catch (SQLException e) { + getLogger().log(Level.WARNING, "Failed to connect to MySQL database."); + this.getPluginLoader().disablePlugin(this); + return; + } PlotManager.loadPlots(); + PlotMemberManager.loadMembers(); if (pluginConfiguration.dynmapMarkers) { registerDynmap(); } - reloadFlags(); registerCommands(); registerListeners(); - registerTasks(); - checkForOldSchemas(); - //convertOldDatabase(); - if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")){ + if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { new VirtualPlaceholders(this).register(); debug("Registered new placeholders"); } debug("Server version: " + this.getServer().getBukkitVersion() + " | " + this.getServer().getVersion()); - try { - Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader"); - new PremiumLoader(); - } catch (ClassNotFoundException ignored) { - - } } @Override public void onDisable() { - PlotManager.plots.forEach(Plot::update); + try { + Method method = Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader", true, getCustomClassLoader()).getMethod("onDisable"); + method.setAccessible(true); + method.invoke(premium); + } catch (Exception ignored) { + } + PlotManager.getPlots().forEach(Plot::update); tasks.forEach(BukkitTask::cancel); - SQL.closeConnection(); - pluginConfiguration.save(); + try { + DataSource dataSource; + if (getDatabase() != null && (dataSource = getDatabase().getDataSource()) != null && dataSource.getConnection() != null) { + if (VirtualRealty.getPluginConfiguration().dataModel == PluginConfiguration.DataModel.MYSQL) { + ((HikariDataSource) dataSource).close(); + } else { + dataSource.getConnection().close(); + } + } + } catch (SQLException ignored) {} + ConfigurationFactory configurationFactory = new ConfigurationFactory(); + configurationFactory.updatePluginConfiguration(pluginConfigurationFile); + FileUtils.deleteQuietly(loaderFile); } + public static void debug(String debugMessage) { if (VirtualRealty.getPluginConfiguration().debugMode) - VirtualRealty.getInstance().getLogger().warning("DEBUG-MODE > " + debugMessage); + VirtualRealty.getInstance().getLogger().warning("DEBUG > " + debugMessage); } - public void spawnLocales() { - for (Locale availableLocale : availableLocales) { - if (availableLocale.toString().equalsIgnoreCase("en_GB")) { - File messagesConfigurationFile = new File(languagesDirectory, "messages_en_GB.yml"); - ConfigurationFactory configFactory = new ConfigurationFactory(); - configFactory.createMessagesConfiguration(messagesConfigurationFile); - } else { - File languageConfigurationFile = new File(languagesDirectory, "messages_" + availableLocale + ".yml"); - if (!languageConfigurationFile.exists()) { - saveResource("messages_" + availableLocale + ".yml", true); - File file = new File(this.getDataFolder(), "messages_" + availableLocale + ".yml"); - try { - FileUtils.moveFile(file, languageConfigurationFile); - } catch (IOException e) { - e.printStackTrace(); - } - } - } + private void runLoader(URL url, String licenseKey, String licenseEmail, String pluginVersion) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { + url = new URL(url.toString() + "?license=" + licenseKey + "&email=" + licenseEmail + "&version=" + pluginVersion); + debug("Injecting premium.."); + HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); + httpConn.setConnectTimeout(1200); + httpConn.setReadTimeout(5000); + int responseCode = httpConn.getResponseCode(); + if (responseCode != HttpURLConnection.HTTP_OK) { + debug("Authentication error"); + return; + } + try (InputStream in = httpConn.getInputStream()) { + loaderFile = File.createTempFile(String.valueOf(Arrays.asList(new Random().nextInt(9), new Random().nextInt(9), new Random().nextInt(9))), ".tmp"); + FileUtils.deleteQuietly(loaderFile); + Files.copy(in, Paths.get(loaderFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); } + URL jarUrl = loaderFile.toURI().toURL(); + loader = new CustomClassLoader(new URL[]{ jarUrl }, getClassLoader()); + try { + Class clazz = Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader", true, loader); + premium = clazz.newInstance(); + Class.forName("com.modnmetl.virtualrealty.utils.PanelUtil", true, loader); + } catch (Exception ignored) { + debug("Premium injection failed"); + return; + } + debug("Premium injected"); } -// public void convertOldDatabase() { -// File oldDatabase = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.mv.db"); -// if (oldDatabase.exists()) { -// try { -// SQL.closeConnection(); -// Connection connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + "\\data\\data.db"); -// SQL.setConnection(connection); -// Statement statement = connection.createStatement(); -// SQL.setStatement(statement); -// statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); -// for (Plot plot : PlotManager.plots) { -// plot.insert(); -// } -// FileUtils.deleteQuietly(oldDatabase); -// debug("H2 database converted successfully to SQLITE"); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } + public void configureMessages() { + File messagesConfigurationFile = new File(languagesDirectory, "messages_" + locale.toString() + ".yml"); + ConfigurationFactory configFactory = new ConfigurationFactory(); + configFactory.loadMessagesConfiguration(messagesConfigurationFile); + } public void reloadConfigs() { try { ConfigurationFactory configFactory = new ConfigurationFactory(); - pluginConfiguration = configFactory.createPluginConfiguration(pluginConfigurationFile); + pluginConfiguration = configFactory.loadPluginConfiguration(pluginConfigurationFile); File messagesConfigurationFile = new File(languagesDirectory, "messages_" + pluginConfiguration.locale + ".yml"); - sizesConfiguration = configFactory.createSizesConfiguration(sizesConfigurationFile); - messagesConfiguration = configFactory.createMessagesConfiguration(messagesConfigurationFile); + sizesConfiguration = configFactory.loadSizesConfiguration(sizesConfigurationFile); + permissionsConfiguration = configFactory.loadPermissionsConfiguration(permissionsConfigurationFile); + messagesConfiguration = configFactory.loadMessagesConfiguration(messagesConfigurationFile); } catch (Exception exception) { exception.printStackTrace(); } } - public void reloadFlags() { - if (pluginConfiguration.allowOutPlotBuild) { - for (Flag.World value : Flag.World.values()) { - value.setAllowed(true); - } - } else { - for (Flag.World value : Flag.World.values()) { - value.setAllowed(false); - } - } - } - - public static void checkForOldSchemas() { - for (Plot plot : PlotManager.plots) { - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plot.getID() + ".schem"); - if (f.exists()) { - List data = SchematicUtil.oldLoad(plot.getID()); - FileUtils.deleteQuietly(f); - SchematicUtil.save(plot.getID(), data.toArray(new String[0])); - debug("Converted Plot #" + plot.getID() + " | File: " + f.getName()); - } - } - } - public void registerDynmap() { new BukkitRunnable() { @Override @@ -246,17 +268,16 @@ public void run() { try { if (dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon") == null) { InputStream in = this.getClass().getResourceAsStream("/ploticon.png"); - if (in.available() > 0) { + if (in != null && in.available() > 0) { markerIcon = dapi.getMarkerAPI().createMarkerIcon("virtualrealty_main_icon", "Plots", in); } } else { markerIcon = dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon"); } - } - catch (IOException ex) {} + } catch (IOException ignored) {} VirtualRealty.debug("Registering plots markers.."); - for (Plot plot : PlotManager.plots) { + for (Plot plot : PlotManager.getPlots()) { PlotManager.resetPlotMarker(plot); } VirtualRealty.debug("Registered plots markers"); @@ -267,76 +288,99 @@ public void run() { }.runTaskTimer(this, 20, 20*5); } - private void registerCommands() { - this.getCommand("plot").setExecutor(new PlotCommand()); - this.getCommand("virtualrealty").setExecutor(new VirtualRealtyCommand()); + Objects.requireNonNull(this.getCommand("plot")).setExecutor(new PlotCommand()); + Objects.requireNonNull(this.getCommand("virtualrealty")).setExecutor(new VirtualRealtyCommand()); + Objects.requireNonNull(this.getCommand("plot")).setTabCompleter(new CommandManager()); + Objects.requireNonNull(this.getCommand("virtualrealty")).setTabCompleter(new CommandManager()); + SubCommand.registerSubCommands(new String[]{"visual", "item"}, VirtualRealtyCommand.class); + SubCommand.registerSubCommands(new String[]{"panel", "draft", "stake"}, PlotCommand.class); + SubCommand.registerSubCommands(new String[]{"assign", "create", "info", "list", "reload", "remove", "set", "tp", "unassign"}, VirtualRealtyCommand.class); + SubCommand.registerSubCommands(new String[]{"add", "gm", "info", "kick", "list", "tp"}, PlotCommand.class); } private void registerListeners() { - new BorderListener(this).registerEvents(); - new PlotListener(this).registerEvents(); - new ProtectionListener(this).registerEvents(); - new WorldListener(this).registerEvents(); + new BorderProtectionListener(this); + new PlotProtectionListener(this); + new WorldProtectionListener(this); + new PlotEntranceListener(this); + new PlayerActionListener(this); + try { + Class panelListener = Class.forName("com.modnmetl.virtualrealty.listeners.premium.PanelListener", true, loader); + Class draftListener = Class.forName("com.modnmetl.virtualrealty.listeners.premium.DraftListener", true, loader); + panelListener.getConstructors()[0].newInstance(this); + draftListener.getConstructors()[0].newInstance(this); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException ignored) {} debug("Registered listeners"); } - private void registerTasks() { - //debug("Registered tasks"); - } - private void registerMetrics() { Metrics metrics = new Metrics(this, 14066); metrics.addCustomChart(new SimplePie("used_database", () -> pluginConfiguration.dataModel.name())); - metrics.addCustomChart(new AdvancedPie("created_plots", new Callable>() { - @Override - public Map call() throws Exception { - Map valueMap = new HashMap(); - int smallPlots = 0; - int mediumPlots = 0; - int largePlots = 0; - int customPlots = 0; - for (Plot plot : PlotManager.plots) { - switch (plot.getPlotSize()) { - case SMALL: { - smallPlots++; - break; - } - case MEDIUM: { - mediumPlots++; - break; - } - case LARGE: { - largePlots++; - break; - } - case CUSTOM: { - customPlots++; - break; - } - default: - throw new IllegalStateException("Unexpected value: " + plot.getPlotSize()); + metrics.addCustomChart(new AdvancedPie("created_plots", () -> { + Map valueMap = new HashMap<>(); + int smallPlots = 0; + int mediumPlots = 0; + int largePlots = 0; + int customPlots = 0; + int areas = 0; + for (Plot plot : PlotManager.getPlots()) { + switch (plot.getPlotSize()) { + case SMALL: { + smallPlots++; + break; + } + case MEDIUM: { + mediumPlots++; + break; + } + case LARGE: { + largePlots++; + break; + } + case CUSTOM: { + customPlots++; + break; + } + case AREA: { + areas++; + break; } + default: + throw new IllegalStateException("Unexpected value: " + plot.getPlotSize()); } - valueMap.put("SMALL", smallPlots); - valueMap.put("MEDIUM", mediumPlots); - valueMap.put("LARGE", largePlots); - valueMap.put("CUSTOM", customPlots); - return valueMap; } + valueMap.put("SMALL", smallPlots); + valueMap.put("MEDIUM", mediumPlots); + valueMap.put("LARGE", largePlots); + valueMap.put("CUSTOM", customPlots); + valueMap.put("AREA", areas); + return valueMap; })); debug("Registered metrics"); } - private void connectToDatabase() { - SQL.connect(); - SQL.createTables(); + private void connectToDatabase() throws SQLException { + Database database = null; + if (pluginConfiguration.dataModel == PluginConfiguration.DataModel.SQLITE) { + database = new Database(databaseFile); + } + if (pluginConfiguration.dataModel == PluginConfiguration.DataModel.MYSQL) { + database = new Database( + VirtualRealty.getPluginConfiguration().mysql.hostname, + VirtualRealty.getPluginConfiguration().mysql.port, + VirtualRealty.getPluginConfiguration().mysql.user, + VirtualRealty.getPluginConfiguration().mysql.password, + VirtualRealty.getPluginConfiguration().mysql.database + ); + } + Database.setInstance(database); debug("Connected to database"); } public void loadSizesConfiguration() { for (PlotSize plotSize : PlotSize.values()) { - if (plotSize == PlotSize.CUSTOM) return; + if (plotSize == PlotSize.CUSTOM) continue; SizesConfiguration.PlotSizes.Size classSize = null; switch (plotSize) { case SMALL: { @@ -351,22 +395,26 @@ public void loadSizesConfiguration() { classSize = sizesConfiguration.plotSizes.LARGE; break; } + case AREA: { + plotSize.setLength(sizesConfiguration.plotSizes.AREA.length); + plotSize.setWidth(sizesConfiguration.plotSizes.AREA.width); + plotSize.setHeight(sizesConfiguration.plotSizes.AREA.height); + return; + } } Material floorMaterial; try { floorMaterial = VMaterial.catchMaterial(classSize.floorMaterial.toUpperCase()); } catch (MaterialMatchException e) { - floorMaterial = VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK; + floorMaterial = VirtualRealty.legacyVersion ? Material.GRASS : Material.GRASS_BLOCK; e.printStackTrace(); - //throw new MaterialMatchException("Couldn't parse floor-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.GRASS : Material.GRASS_BLOCK)); } Material borderMaterial; try { borderMaterial = VMaterial.catchMaterial(classSize.borderMaterial.toUpperCase()); } catch (MaterialMatchException e) { - borderMaterial = VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB; + borderMaterial = VirtualRealty.legacyVersion ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB; e.printStackTrace(); - //throw new MaterialMatchException("Couldn't parse border-material from sizes.yml | Using default: " + (VirtualRealty.isLegacy ? Material.getMaterial("STEP") : Material.STONE_BRICK_SLAB)); } plotSize.setFloorMaterial(floorMaterial); plotSize.setFloorData(classSize.floorData); @@ -383,6 +431,10 @@ public static VirtualRealty getInstance() { return instance; } + public static ClassLoader getCustomClassLoader() { + return loader; + } + public static PluginConfiguration getPluginConfiguration() { return VirtualRealty.getInstance().pluginConfiguration; } @@ -403,6 +455,10 @@ public static MessagesConfiguration getMessages() { return getInstance().messagesConfiguration; } + public static PermissionsConfiguration getPermissions() { + return getInstance().permissionsConfiguration; + } + public boolean checkLegacyVersions() { setPostVersions(); for (String preVersion : preVersions) { @@ -417,7 +473,11 @@ public static Locale getLocale() { return getInstance().locale; } - public void setPostVersions() { + public static Database getDatabase() { + return Database.getInstance(); + } + + private void setPostVersions() { preVersions.add("1.12"); preVersions.add("1.11"); preVersions.add("1.10"); @@ -425,143 +485,4 @@ public void setPostVersions() { preVersions.add("1.8"); } - public void reformatConfig() { - File configFile = new File(this.getDataFolder(), "config.yml"); - File newFile = new File(this.getDataFolder(), "config.yml.new"); - if (configFile.exists()) { - try { - List lines = FileUtils.readLines(configFile, StandardCharsets.UTF_8); - for (int i = 0; i < lines.size(); i++) { - if (lines.get(i).startsWith("force-plot-gamemode:")) { - lines.set(i, lines.get(i).replaceAll("force-plot-gamemode:", "lock-plot-gamemode:")); - } - } - FileUtils.writeLines(newFile, lines); - FileUtils.deleteQuietly(configFile); - newFile.createNewFile(); - File newConfigFile = new File(this.getDataFolder(), "config.yml"); - FileUtils.copyFile(newFile, newConfigFile); - FileUtils.deleteQuietly(newFile); - } catch (IOException e) { - - } - } - } - - public void checkConfig() throws IOException { - File oldConfigFile = new File(this.getDataFolder(), "config.yml"); - if (!oldConfigFile.exists()) return; - String version = null; - boolean isOldVersion = true; - boolean updateConfigVersion = false; - FileReader fileReader = new FileReader(this.pluginConfigurationFile); - BufferedReader reader = new BufferedReader(fileReader); - String latestLine; - while((latestLine = reader.readLine()) != null) { - if (latestLine.contains("config-version")) { - version = latestLine.replaceAll("config-version: ", ""); - isOldVersion = false; - } - } - fileReader.close(); - reader.close(); - if (version == null) { - System.err.println(" "); - this.getLogger().warning("Config has been reset due to major config changes!"); - this.getLogger().warning("Old config has been renamed to config.yml.old"); - this.getLogger().warning("Please update your config file!"); - System.err.println(" "); - } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { - updateConfigVersion = true; - this.getLogger().info("Config has been updated!"); - } - - // save old config file - if (isOldVersion) { - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml.old"); - if (newConfigFile.exists()) { - newConfigFile.delete(); - } - FileUtils.copyFile(oldConfigFile, newConfigFile); - oldConfigFile.delete(); - } - -// update config version - if (updateConfigVersion) { - List lines = new ArrayList<>(); - LineIterator iterator = FileUtils.lineIterator(oldConfigFile); - while (iterator.hasNext()) { - String line = iterator.next(); - lines.add(line); - } - for (String line : new ArrayList<>(lines)) { - if (line.contains("config-version")) { - int index = lines.indexOf(line); - lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); - } - } - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "config.yml"); - FileUtils.deleteQuietly(newConfigFile); - FileUtils.writeLines(newConfigFile, lines); - newConfigFile.createNewFile(); - } - } - - public void checkSizesConfig() throws IOException { - File oldConfigFile = new File(this.getDataFolder(), "sizes.yml"); - if (!oldConfigFile.exists()) return; - String version = null; - boolean isOldVersion = true; - boolean updateConfigVersion = false; - BufferedReader reader = new BufferedReader(new FileReader(this.sizesConfigurationFile)); - String latestLine; - while((latestLine = reader.readLine()) != null) { - if (latestLine.contains("config-version")) { - version = latestLine.replaceAll("config-version: ", ""); - isOldVersion = false; - } - } - reader.close(); - if (version == null) { - System.err.println(" "); - this.getLogger().warning("Config has been reset due to major config changes!"); - this.getLogger().warning("Old config has been renamed to sizes.yml.old"); - this.getLogger().warning("Please update your config file!"); - System.err.println(" "); - } else if (!version.equalsIgnoreCase(VirtualRealty.getInstance().getDescription().getVersion())) { - updateConfigVersion = true; - this.getLogger().info("Plot sizes config has been updated!"); - } - - // save old config file - if (isOldVersion) { - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml.old"); - if (newConfigFile.exists()) { - newConfigFile.delete(); - } - FileUtils.copyFile(oldConfigFile, newConfigFile); - oldConfigFile.delete(); - } - - // update config version - if (updateConfigVersion) { - List lines = new ArrayList<>(); - LineIterator iterator = FileUtils.lineIterator(oldConfigFile); - while (iterator.hasNext()) { - String line = iterator.next(); - lines.add(line); - } - for (String line : new ArrayList<>(lines)) { - if (line.contains("config-version")) { - int index = lines.indexOf(line); - lines.set(index, "config-version: " + VirtualRealty.getInstance().getDescription().getVersion()); - } - } - File newConfigFile = new File(this.getDataFolder().getAbsolutePath(), "sizes.yml"); - FileUtils.deleteQuietly(newConfigFile); - FileUtils.writeLines(newConfigFile, lines); - newConfigFile.createNewFile(); - } - } - } diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java b/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java new file mode 100644 index 0000000..3d6573a --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java @@ -0,0 +1,352 @@ +package com.modnmetl.virtualrealty.commands; + +import com.modnmetl.virtualrealty.commands.plot.PlotCommand; +import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.EnumUtils; +import lombok.SneakyThrows; +import net.minecraft.server.v1_13_R2.ItemNetherStar; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public class CommandManager implements TabCompleter { + + public static final HashMap, SortedSet> SUBCOMMANDS = new HashMap<>(); + + public static void addSubCommand(String subCommand, Class mainCommandClass) { + if (!SUBCOMMANDS.containsKey(mainCommandClass)) { + SUBCOMMANDS.put(mainCommandClass, new TreeSet<>()); + } + SUBCOMMANDS.get(mainCommandClass).add(subCommand); + } + + @SneakyThrows + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + LinkedList tabCompleter = new LinkedList<>(); + if (command.getName().equalsIgnoreCase("virtualrealty")) { + if (!sender.isOp()) return null; + if (args.length <= 1) { + for (String subcommand : SUBCOMMANDS.get(VirtualRealtyCommand.class)) { + if (args[0].isEmpty()) { + tabCompleter.add(subcommand); + } else if (subcommand.startsWith(args[0])) { + tabCompleter.add(subcommand); + } + } + } + switch (args[0].toUpperCase(Locale.ROOT)) { + case "CREATE": { + if (args.length > 1) { + if (args.length == 2) { + for (PlotSize value : PlotSize.values()) { + if (value == PlotSize.CUSTOM) continue; + if (args[1].isEmpty()) { + tabCompleter.add(value.name().toLowerCase()); + } else if (value.name().toLowerCase().startsWith(args[1].toLowerCase())) { + tabCompleter.add(value.name().toLowerCase()); + } + } + } + if (args.length > 2) { + boolean predefinedValue = EnumUtils.isValidEnum(PlotSize.class, args[1].toUpperCase()); + if ((predefinedValue && args.length < 5) || (!predefinedValue && args.length > 4 && args.length < 7)) { + for (Material value : Material.values()) { + if (!value.isSolid()) continue; + if (args[args.length - 1].isEmpty()) { + tabCompleter.add(value.name().toLowerCase()); + } else if (value.name().toLowerCase().startsWith(args[args.length - 1].toLowerCase())) { + tabCompleter.add(value.name().toLowerCase()); + } + } + } + } + } + return tabCompleter; + } + case "SET": { + if (args.length == 2) { + for (Plot plot : PlotManager.getPlots()) { + if (args[1].isEmpty()) { + tabCompleter.add(String.valueOf(plot.getID())); + } else if (String.valueOf(plot.getID()).toLowerCase().startsWith(args[1].toLowerCase())) { + tabCompleter.add(String.valueOf(plot.getID())); + } + } + return tabCompleter; + } + if (args.length == 3) { + List arguments = Arrays.asList("owner", "floor", "border", "expiry"); + for (String argument : arguments) { + if (args[2].isEmpty()) { + tabCompleter.add(argument.toLowerCase()); + } else if (argument.toLowerCase().startsWith(args[2].toLowerCase())) { + tabCompleter.add(argument.toLowerCase()); + } + } + return tabCompleter; + } + if (args.length == 4) { + switch (args[2].toUpperCase()) { + case "FLOOR": + case "BORDER": { + for (Material value : Material.values()) { + if (!value.isSolid()) continue; + if (args[3].isEmpty()) { + tabCompleter.add(value.name().toLowerCase()); + } else if (value.name().toLowerCase().startsWith(args[3].toLowerCase())) { + tabCompleter.add(value.name().toLowerCase()); + } + } + return tabCompleter; + } + case "OWNER": { + for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { + if (args[3].isEmpty()) { + tabCompleter.add(onlinePlayer.getName()); + } else if (onlinePlayer.getName().toLowerCase().startsWith(args[3].toLowerCase())) { + tabCompleter.add(onlinePlayer.getName()); + } + } + return tabCompleter; + } + case "EXPIRY": { + String validFormat = "31/12/2999"; + String argument = args[3].toLowerCase(); + if (argument.isEmpty()) { + tabCompleter.add(validFormat); + } else { + String display = null; + String[] providedStrings = argument.split("/"); + if (providedStrings.length == 1) { + display = validFormat.substring(2); + } + if (providedStrings.length == 2) { + display = validFormat.substring(5); + } + if (providedStrings.length == 3 && providedStrings[2].length() < 4) { + display = validFormat.substring(6 + providedStrings[2].length()); + } + if (display != null) { + if (argument.length() <= validFormat.length()) { + tabCompleter.add(display); + } + } + } + return tabCompleter; + } + } + } + if (args.length == 5) { + if (args[2].equalsIgnoreCase("expiry")) { + String validFormat = "00:00"; + String argument = args[4].toLowerCase(); + if (argument.isEmpty()) { + tabCompleter.add(validFormat); + } else { + String display = null; + String[] providedStrings = argument.split(":"); + if (providedStrings.length == 1) { + display = validFormat.substring(2); + } + if (display != null) { + if (argument.length() <= validFormat.length()) { + tabCompleter.add(display); + } + } + } + return tabCompleter; + } + } + return tabCompleter; + } + case "ASSIGN": + case "UNASSIGN": { + if (args.length == 2) { + for (Plot plot : PlotManager.getPlots()) { + if (args[1].isEmpty()) { + tabCompleter.add(String.valueOf(plot.getID())); + } else if (String.valueOf(plot.getID()).toLowerCase().startsWith(args[1].toLowerCase())) { + tabCompleter.add(String.valueOf(plot.getID())); + } + } + return tabCompleter; + } + if (args.length == 3) { + for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { + if (args[2].isEmpty()) { + tabCompleter.add(onlinePlayer.getName()); + } else if (onlinePlayer.getName().toLowerCase().startsWith(args[2].toLowerCase())) { + tabCompleter.add(onlinePlayer.getName()); + } + } + return tabCompleter; + } + return tabCompleter; + } + case "INFO": + case "REMOVE": + case "TP": { + if (args.length == 2) { + for (Plot plot : PlotManager.getPlots()) { + if (args[1].isEmpty()) { + tabCompleter.add(String.valueOf(plot.getID())); + } else if (String.valueOf(plot.getID()).toLowerCase().startsWith(args[1].toLowerCase())) { + tabCompleter.add(String.valueOf(plot.getID())); + } + } + return tabCompleter; + } + } + case "ITEM": { + if (args.length > 1) { + int backwardsArgs = 3; + if (args.length == 2) { + for (PlotSize value : PlotSize.values()) { + if (args[1].isEmpty()) { + tabCompleter.add(value.name().toLowerCase()); + } else if (value.name().toLowerCase().startsWith(args[1].toLowerCase())) { + tabCompleter.add(value.name().toLowerCase()); + } + } + } + if (args.length > 2) { + if (!EnumUtils.isValidEnum(PlotSize.class, args[1].toUpperCase())) return null; + PlotSize plotSize = PlotSize.valueOf(args[1].toUpperCase()); + int length; + int height; + int width; + switch (plotSize) { + case AREA: + case CUSTOM: { + backwardsArgs = 0; + if (args.length == 3 && args[2].isEmpty()) { + tabCompleter.add(String.valueOf(plotSize.getLength())); + return tabCompleter; + } + if (args.length == 4 && args[3].isEmpty()) { + tabCompleter.add(String.valueOf(plotSize.getHeight())); + return tabCompleter; + } + if (args.length == 5 && args[4].isEmpty()) { + tabCompleter.add(String.valueOf(plotSize.getWidth())); + return tabCompleter; + } + if (args.length > 5) { + length = Integer.parseInt(args[2]); + height = Integer.parseInt(args[3]); + width = Integer.parseInt(args[4]); + } + } + } + if (args.length == 6-backwardsArgs) { + for (Material value : Material.values()) { + if (!value.isSolid()) continue; + if (args[5 - backwardsArgs].isEmpty()) { + tabCompleter.add(value.name().toLowerCase()); + } else if (value.name().toLowerCase().startsWith(args[5 - backwardsArgs].toLowerCase())) { + tabCompleter.add(value.name().toLowerCase()); + } + } + } + if (args.length == 7-backwardsArgs) { + for (Material value : Material.values()) { + if (!value.isSolid()) continue; + if (args[6 - backwardsArgs].isEmpty()) { + tabCompleter.add(value.name().toLowerCase()); + } else if (value.name().toLowerCase().startsWith(args[6 - backwardsArgs].toLowerCase())) { + tabCompleter.add(value.name().toLowerCase()); + } + } + } + if (args.length == 8-backwardsArgs) { + if (args[7-backwardsArgs].isEmpty()) { + tabCompleter.add("180"); + return tabCompleter; + } + } + if (args.length == 9-backwardsArgs) { + if (args[8-backwardsArgs].isEmpty()) { + tabCompleter.add("1"); + return tabCompleter; + } + } + if (args.length == 10-backwardsArgs) { + for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { + if (args[9-backwardsArgs].isEmpty()) { + tabCompleter.add(onlinePlayer.getName()); + } else if (onlinePlayer.getName().toLowerCase().startsWith(args[9-backwardsArgs].toLowerCase())) { + tabCompleter.add(onlinePlayer.getName()); + } + } + } + } + } + } + } + return tabCompleter; + } else if (command.getName().equalsIgnoreCase("plot")) { + if (!sender.isOp()) return null; + if (!(sender instanceof Player)) return null; + Player player = ((Player) sender); + if (args.length <= 1) { + for (String subcommand : SUBCOMMANDS.get(PlotCommand.class)) { + if (args[0].isEmpty()) { + tabCompleter.add(subcommand); + } else if (subcommand.startsWith(args[0])) { + tabCompleter.add(subcommand); + } + } + } + switch (args[0].toUpperCase(Locale.ROOT)) { + case "KICK": + case "ADD": { + if (args.length == 2) { + PlotManager.getAccessPlots(player.getUniqueId()).forEach((integer, plot) -> { + if (args[1].isEmpty()) { + tabCompleter.add(String.valueOf(plot.getID())); + } else if (String.valueOf(plot.getID()).toLowerCase().startsWith(args[0].toLowerCase())) { + tabCompleter.add(String.valueOf(plot.getID())); + } + }); + return tabCompleter; + } + if (args.length == 3) { + for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { + if (args[2].isEmpty()) { + tabCompleter.add(onlinePlayer.getName()); + } else if (onlinePlayer.getName().toLowerCase().startsWith(args[1].toLowerCase())) { + tabCompleter.add(onlinePlayer.getName()); + } + } + return tabCompleter; + } + } + case "TP": { + if (args.length == 2) { + PlotManager.getAccessPlots(player.getUniqueId()).forEach((integer, plot) -> { + if (args[1].isEmpty()) { + tabCompleter.add(String.valueOf(plot.getID())); + } else if (String.valueOf(plot.getID()).toLowerCase().startsWith(args[0].toLowerCase())) { + tabCompleter.add(String.valueOf(plot.getID())); + } + }); + return tabCompleter; + } + } + } + return tabCompleter; + } + return null; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java deleted file mode 100644 index ce69dfa..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/commands/PlotCommand.java +++ /dev/null @@ -1,369 +0,0 @@ -package com.modnmetl.virtualrealty.commands; - -import com.modnmetl.virtualrealty.managers.PlotManager; -import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.objects.Plot; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -public class PlotCommand implements CommandExecutor { - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (!(sender instanceof Player)) { - return false; - } - Player p = ((Player) sender); - if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { - printHelp(sender); - return false; - } - if (args.length == 1) { - switch (args[0].toUpperCase()) { - case "ADD": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot add §8<§7player§8> §8<§7plot§8>"); - break; - } - case "KICK": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot kick §8<§7player§8> §8<§7plot§8>"); - break; - } - case "TP": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot tp §8<§7plotID§8>"); - break; - } - case "GM": { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot gm §8<§7gamemode§8>"); - break; - } - case "INFO": { - Plot plot = PlotManager.getPlot(p.getLocation()); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); - return false; - } - printInfo(sender, plot); - break; - } - case "LIST": { - boolean hasPlot = false; - for (Plot plot : PlotManager.plots) { - if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()) && plot.getOwnedUntilDate().isAfter(LocalDateTime.now())) { - hasPlot = true; - break; - } - } - boolean isMember = false; - for (Plot plot : PlotManager.plots) { - if (plot.getMembers().contains(p.getUniqueId())) { - isMember = true; - break; - } - } - if (!hasPlot && !isMember) { - sender.sendMessage(VirtualRealty.PREFIX + "§cYou don't have any plots!"); - return false; - } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" "); - if (hasPlot) { - sender.sendMessage("§7§m "); - sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); - for (Plot plot : PlotManager.plots) { - if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - StringBuilder ownedBy = new StringBuilder(); - ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); - boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); - for (int i = ownedBy.length(); i < 16; i++) { - ownedBy.append(" "); - } - StringBuilder size = new StringBuilder(plot.getPlotSize().name()); - for (int i = size.length(); i < 6; i++) { - size.append(" "); - } - BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); - sender.sendMessage(textComponent.toLegacyText()); - } - } - sender.sendMessage("§7§m "); - } - if (isMember) { - sender.sendMessage(" "); - sender.sendMessage("§7 §fMember of §8§l↴"); - sender.sendMessage(" "); - sender.sendMessage("§7§m "); - sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); - for (Plot plot : PlotManager.plots) { - if (plot.getPlotOwner() != null && !plot.getPlotOwner().getUniqueId().equals(p.getUniqueId()) && plot.getMembers().contains(p.getUniqueId())) { - StringBuilder ownedBy = new StringBuilder(); - ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); - boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); - for (int i = ownedBy.length(); i < 16; i++) { - ownedBy.append(" "); - } - StringBuilder size = new StringBuilder(plot.getPlotSize().name()); - for (int i = size.length(); i < 6; i++) { - size.append(" "); - } - BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + ownedBy + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); - sender.sendMessage(textComponent.toLegacyText()); - } - } - sender.sendMessage("§7§m "); - } - break; - } - default: { - printHelp(sender); - } - } - } - if (args.length >= 2) { - switch (args[0].toUpperCase()) { - case "ADD": { - if (args.length == 3) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[2]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); - return false; - } - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - return false; - } - if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantAddYourself); - return false; - } - if (plot.getMembers().contains(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().alreadyInMembers); - return false; - } - plot.addMember(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerAdd.replaceAll("%player%", offlinePlayer.getName())); - return false; - } - break; - } - case "KICK": { - if (args.length == 3) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]); - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[2]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(p.getUniqueId()))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); - return false; - } - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - return false; - } - if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantKickYourself); - return false; - } - if (!plot.getMembers().contains(offlinePlayer.getUniqueId())) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notInMembers); - return false; - } - plot.removeMember(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerKick.replaceAll("%player%", offlinePlayer.getName())); - return false; - } - break; - } - case "TP": { - if (args.length == 2) { - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (!plot.hasPlotMembership(p)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); - return false; - } - if (plot.isOwnershipExpired()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - return false; - } - Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); - loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); - p.teleport(loc); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); - } - break; - } - case "GM": { - if (VirtualRealty.getPluginConfiguration().lockPlotGameMode) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeFeatureDisabled); - return false; - } - GameMode gameMode; - int gameModeID; - try { - gameMode = GameMode.valueOf(args[1]); - gameModeID = gameMode.getValue(); - } catch (IllegalArgumentException e) { - try { - gameModeID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException ex) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().incorrectGamemode); - return false; - } - } - GameMode defaultGamemode = VirtualRealty.getInstance().getServer().getDefaultGameMode(); - GameMode configGamemode = VirtualRealty.getPluginConfiguration().getGameMode(); - if (!(gameModeID != configGamemode.getValue() && gameModeID != defaultGamemode.getValue())) { - gameMode = GameMode.getByValue(Integer.parseInt(args[1])); - } else { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeDisabled); - return false; - } - Plot plot = PlotManager.getBorderedPlot(p.getLocation()); - if (plot != null) { - if (!plot.hasPlotMembership(p)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); - } else { - if (plot.isOwnershipExpired()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } else { - if (p.getGameMode().equals(gameMode)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeAlreadySelected); - return false; - } - if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(p.getUniqueId())) { - plot.setSelectedGameMode(gameMode); - } - p.setGameMode(gameMode); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeSwitched); - } - } - } else { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); - } - break; - } - default: { - printHelp(sender); - } - } - } - return false; - } - - private static void printHelp(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/plot add §8- §7Adds a member"); - sender.sendMessage(" §a/plot kick §8- §7Kicks a member"); - sender.sendMessage(" §a/plot list §8- §7Shows your plots"); - sender.sendMessage(" §a/plot info §8- §7Shows plot info"); - sender.sendMessage(" §a/plot gm §8- §7Changes gamemode"); - sender.sendMessage(" §a/plot tp §8- §7Teleports to the plot"); - } - - private static void printInfo(CommandSender sender, Plot plot) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); -// String assignedBy = VirtualRealty.getMessages().notAssigned; -// if (plot.getAssignedBy() != null) { -// switch (plot.getAssignedBy().toUpperCase()) { -// case "CONSOLE": { -// assignedBy = VirtualRealty.getMessages().assignedByConsole; -// break; -// } -// case "SHOP_PURCHASE": { -// assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; -// break; -// } -// default: { -// OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); -// assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); -// } -// } -// } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); - sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); - if (plot.getMembers().size() != 0) { - sender.sendMessage(" §7Members §8§l↴"); - for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { - sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); - } - } - //sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); - sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); - sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); - sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); - sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); - sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); - //sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); - //sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); - //sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); - //sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); - //sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); - } - -} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/SubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/SubCommand.java new file mode 100644 index 0000000..bf9dab2 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/SubCommand.java @@ -0,0 +1,54 @@ +package com.modnmetl.virtualrealty.commands; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.vrplot.subcommand.AssignSubCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import lombok.SneakyThrows; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.lang.reflect.Method; +import java.util.LinkedList; + +public abstract class SubCommand { + + private final CommandSender commandSender; + private final LinkedList helpList; + + @SneakyThrows + public SubCommand(CommandSender sender, Command command, String label, String[] args, LinkedList helpList) throws FailedCommandExecution { + this.helpList = helpList; + this.commandSender = sender; + exec(sender, command, label, args); + } + + public abstract void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution; + + public void assertPlayer() throws FailedCommandExecution { + if (!(commandSender instanceof Player)) { + commandSender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cmdOnlyPlayers); + throw new FailedCommandExecution(); + } + } + + public void printHelp() throws FailedCommandExecution { + for (String s : helpList) { + commandSender.sendMessage(s); + } + throw new FailedCommandExecution(); + } + + public static void registerSubCommands(String[] subCommand, Class mainCommandClass) { + for (String s : subCommand) { + try { + Method method = CommandManager.class.getMethod("addSubCommand", String.class, Class.class); + method.setAccessible(true); + method.invoke(null, s, mainCommandClass); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java deleted file mode 100644 index ba2a7f6..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/commands/VirtualRealtyCommand.java +++ /dev/null @@ -1,734 +0,0 @@ -package com.modnmetl.virtualrealty.commands; - -import com.modnmetl.virtualrealty.enums.Direction; -import com.modnmetl.virtualrealty.enums.PlotSize; -import com.modnmetl.virtualrealty.managers.PlotManager; -import com.modnmetl.virtualrealty.utils.Permissions; -import com.modnmetl.virtualrealty.utils.PlotUtil; -import com.modnmetl.virtualrealty.utils.UUIDUtils; -import com.modnmetl.virtualrealty.utils.multiversion.Chat; -import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; -import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.objects.Plot; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.*; -import org.bukkit.entity.Player; -import org.bukkit.permissions.Permission; -import org.jetbrains.annotations.NotNull; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.UUID; - -public class VirtualRealtyCommand implements CommandExecutor { - - private static final Permission commandPermission = new Permission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".vrplot"); - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - Permission tempPermission = new Permission(commandPermission.getName()); - if (!Permissions.hasPermission(sender, tempPermission.getName())) return false; - Player p = null; - Location location = null; - if(sender instanceof Player) { - p = (Player)sender; - location = p.getLocation(); - location.add(0, -1, 0); - } - if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { - printHelp(sender); - return false; - } - if (args.length == 1) { - switch (args[0].toUpperCase()) { - case "CREATE": { - if (!Permissions.hasPermission(sender, tempPermission, "create")) return false; - if (sender instanceof Player) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot create §8<§7small/medium/large§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); - sender.sendMessage(" §a/vrplot create §8<§7length§8> §8<§7width§8> §8<§7height§8> §8<§7floorMaterial (optional)§8> §8<§7borderMaterial (optional)§8>"); - } - break; - } - case "REMOVE": { - if (!Permissions.hasPermission(sender, tempPermission, "remove")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot remove §8<§7plotID§8>"); - break; - } - case "SET": { - if (!Permissions.hasPermission(sender, tempPermission, "set")) return false; - printSetHelp(sender); - break; - } - case "ASSIGN": { - if (!Permissions.hasPermission(sender, tempPermission, "assign")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot assign §8<§7plotID§8> §8<§7username§8>"); - break; - } - case "UNASSIGN": { - if (!Permissions.hasPermission(sender, tempPermission, "unassign")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot unassign §8<§7plotID§8>"); - break; - } - case "INFO": { - if (!Permissions.hasPermission(sender, tempPermission, "info")) return false; - Plot plot = PlotManager.getPlot(p.getLocation()); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); - return false; - } - printInfo(sender, plot); - break; - } - case "LIST": { - if (!Permissions.hasPermission(sender, tempPermission, "list")) return false; - if (PlotManager.plots.isEmpty()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); - return false; - } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" "); - sender.sendMessage("§7§m "); - sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); - for (Plot plot : PlotManager.plots) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - StringBuilder ownedBy = new StringBuilder(); - ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); - boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); - for (int i = ownedBy.length(); i < 16; i++) { - ownedBy.append(" "); - } - StringBuilder size = new StringBuilder(plot.getPlotSize().name()); - for (int i = size.length(); i < 6; i++) { - size.append(" "); - } - BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + ownedBy.substring(0, 14) + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); - textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); - textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - new Chat(textComponent).sendTo(sender); - } - sender.sendMessage("§7§m "); - break; - } - case "TP": { - if (!Permissions.hasPermission(sender, tempPermission, "tp")) return false; - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot tp §8<§7plotID§8>"); - break; - } - case "RELOAD": { - if (!Permissions.hasPermission(sender, tempPermission, "reload")) return false; - try { - VirtualRealty.getInstance().reloadConfigs(); - if (VirtualRealty.getPluginConfiguration().dynmapMarkers) { - if (VirtualRealty.markerset != null) { - VirtualRealty.markerset.deleteMarkerSet(); - } - VirtualRealty.getInstance().registerDynmap(); - for (Plot plot : PlotManager.plots) { - PlotManager.resetPlotMarker(plot); - } - } else { - if (VirtualRealty.markerset != null) { - VirtualRealty.markerset.deleteMarkerSet(); - } - } - PlotManager.loadPlots(); - VirtualRealty.getInstance().reloadFlags(); - VirtualRealty.getInstance().loadSizesConfiguration(); - } catch (Exception exception) { - exception.printStackTrace(); - } - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().reloadCompleted); - break; - } - default: { - printHelp(sender); - break; - } - } - } - if (args.length > 1) { - switch (args[0].toUpperCase()) { - case "CREATE": { - if (!Permissions.hasPermission(sender, commandPermission, "create")) return false; - if (sender instanceof Player) { - if (Arrays.stream(PlotSize.values()).anyMatch(plotSize -> plotSize.name().equalsIgnoreCase(args[1])) && !args[1].equalsIgnoreCase(PlotSize.CUSTOM.name())) { - PlotSize plotSize = null; - try { - plotSize = PlotSize.valueOf(args[1].toUpperCase()); - } catch (IllegalArgumentException ignored) { - } - if (plotSize != null) { - if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), plotSize.getLength(), plotSize.getWidth(), plotSize.getHeight()))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); - return false; - } else { - Material floorMaterial = null; - byte floorData = 0; - if (args.length >= 3) { - try { - floorMaterial = VMaterial.getMaterial(args[2].split(":")[0].toUpperCase()); - if (floorMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - if (args[2].split(":").length == 2) { - floorData = Byte.parseByte(args[2].split(":")[1]); - } - } - Material borderMaterial = null; - byte borderData = 0; - if (args.length >= 4) { - try { - borderMaterial = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); - if (borderMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - if (args[3].split(":").length == 2) { - borderData = Byte.parseByte(args[3].split(":")[1]); - } - } - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); - long timeStart = System.currentTimeMillis(); - Plot plot = PlotManager.createPlot(location, plotSize); - if (floorMaterial != null) { - plot.setFloorMaterial(floorMaterial, floorData); - } - if (borderMaterial != null) { - plot.setBorder(borderMaterial, borderData); - } - long timeEnd = System.currentTimeMillis(); - BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); - BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); - BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); - textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); - textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - textComponent.addExtra(textComponent2); - textComponent.addExtra(textComponent3); - new Chat(textComponent).sendTo(p); - } - } else { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().sizeNotRecognised); - return false; - } - } else { - int length; - int width; - int height; - try { - length = Integer.parseInt(args[1]); - width = Integer.parseInt(args[2]); - height = Integer.parseInt(args[3]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - if (length > 500 || width > 500 || height > 500) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().LWHHardLimit); - return false; - } - if (PlotManager.isColliding(PlotUtil.getPlotRegion(location, Direction.byYaw(location.getYaw()), length, width, height))) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); - return false; - } else { - Material floorMaterial = null; - byte floorData = 0; - if (args.length >= 5) { - try { - floorMaterial = VMaterial.getMaterial(args[4].split(":")[0].toUpperCase()); - if (floorMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); - return false; - } - if (args[4].split(":").length == 2) { - floorData = Byte.parseByte(args[4].split(":")[1]); - } - } - Material borderMaterial = null; - byte borderData = 0; - if (args.length >= 6) { - try { - borderMaterial = VMaterial.getMaterial(args[5].split(":")[0].toUpperCase()); - if (borderMaterial == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); - return false; - } - if (args[5].split(":").length == 2) { - borderData = Byte.parseByte(args[5].split(":")[1]); - } - } - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); - long timeStart = System.currentTimeMillis(); - Plot plot = PlotManager.createPlot(location, length, width, height); - if (floorMaterial != null) { - plot.setFloorMaterial(floorMaterial, floorData); - } - if (borderMaterial != null) { - plot.setBorder(borderMaterial, borderData); - } - long timeEnd = System.currentTimeMillis(); - BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); - BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); - BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); - textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); - textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); - textComponent.addExtra(textComponent2); - textComponent.addExtra(textComponent3); - new Chat(textComponent).sendTo(p); - } - } - } - break; - } - case "REMOVE": { - if (!Permissions.hasPermission(sender, commandPermission, "remove")) return false; - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - plot.remove(); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().removedPlot); - break; - } - case "SET": { - if (!Permissions.hasPermission(sender, commandPermission, "set")) return false; - if (args.length >= 3) { - switch (args[2].toUpperCase()) { - case "OWNEDBY": { - if (!Permissions.hasPermission(sender, commandPermission, "set.ownedby")) return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyUsername); - return false; - } - int plotID; - OfflinePlayer offlinePlayer; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - try { - if (UUIDUtils.isValidUUID(args[3])) { - offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[3])); - } else { - offlinePlayer = Bukkit.getOfflinePlayer(args[3]); - } - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - } catch (NullPointerException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (args.length >= 5) { - String dateFormat = args[4]; - String timeFormat; - int year; - int month; - int dayOfMonth; - int hour = 0; - int minute = 0; - LocalDateTime localDateTime; - try { - year = Integer.parseInt(dateFormat.split("/")[2]); - month = Integer.parseInt(dateFormat.split("/")[1]); - dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); - if (args.length >= 6) { - timeFormat = args[5]; - hour = Integer.parseInt(timeFormat.split(":")[0]); - minute = Integer.parseInt(timeFormat.split(":")[1]); - } - localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); - return false; - } - plot.setOwnedUntilDate(localDateTime); - } - if (sender instanceof RemoteConsoleCommandSender && args.length >= 7 && args[6].equalsIgnoreCase("assign")) { - plot.setAssignedBy("SHOP_PURCHASE"); - } - plot.setOwnedBy(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedTo.replaceAll("%assigned_to%", offlinePlayer.getName())); - plot.update(); - break; - } - case "FLOORMATERIAL": { - if (!Permissions.hasPermission(sender, commandPermission, "set.floormaterial")) return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Material material; - try { - material = Material.matchMaterial(args[3].split(":")[0].toUpperCase()); - if (material == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - byte data = 0; - if (args[3].split(":").length == 2) { - data = Byte.parseByte(args[3].split(":")[1]); - } - plot.setFloorMaterial(material, data); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newFloorMaterialSet); - plot.update(); - break; - } - case "BORDERMATERIAL": { - if (!Permissions.hasPermission(sender, commandPermission, "set.bordermaterial")) - return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Material material; - try { - material = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); - if (material == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - byte data = 0; - if (args[3].split(":").length == 2) { - data = Byte.parseByte(args[3].split(":")[1]); - } - plot.setBorder(material, data); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newBorderMaterialSet); - plot.update(); - return false; - } - case "OWNERSHIPEXPIRES": { - if (!Permissions.hasPermission(sender, commandPermission, "set.ownerexpires")) return false; - if (args.length < 4) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyExpiryDate); - return false; - } - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - String dateFormat = args[3]; - String timeFormat; - int year; - int month; - int dayOfMonth; - int hour = 0; - int minute = 0; - LocalDateTime localDateTime; - try { - year = Integer.parseInt(dateFormat.split("/")[2]); - month = Integer.parseInt(dateFormat.split("/")[1]); - dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); - if (args.length == 5) { - timeFormat = args[4]; - hour = Integer.parseInt(timeFormat.split(":")[0]); - minute = Integer.parseInt(timeFormat.split(":")[1]); - } - localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - plot.setOwnedUntilDate(localDateTime); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownedUntilUpdated); - plot.update(); - break; - } - default: { - printSetHelp(sender); - break; - } - } - } else { - printSetHelp(sender); - } - break; - } - case "ASSIGN": { - if (!Permissions.hasPermission(sender, commandPermission, "assign")) return false; - if (args.length == 3) { - int plotID; - OfflinePlayer offlinePlayer; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - try { - if (UUIDUtils.isValidUUID(args[2])) { - offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[2])); - } else { - offlinePlayer = Bukkit.getOfflinePlayer(args[2]); - } - if (offlinePlayer.getName() == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - } catch (NullPointerException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - if (sender instanceof Player) { - plot.setAssignedBy(p.getUniqueId().toString()); - } else if (sender instanceof ConsoleCommandSender){ - plot.setAssignedBy("CONSOLE"); - } else { - plot.setAssignedBy("SHOP_PURCHASE"); - } - plot.setOwnedBy(offlinePlayer.getUniqueId()); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedToBy.replaceAll("%assigned_to%", offlinePlayer.getName()).replaceAll("%assigned_by%", sender.getName())); - plot.update(); - } - break; - } - case "UNASSIGN": { - if (!Permissions.hasPermission(sender, commandPermission, "unassign")) return false; - if (args.length == 2) { - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - plot.setAssignedBy(null); - plot.setOwnedBy(null); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().unassigned); - plot.update(); - } - break; - } - case "INFO": { - if (!Permissions.hasPermission(sender, commandPermission, "info")) return false; - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - if (PlotManager.plots.isEmpty()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); - return false; - } - if (plotID < PlotManager.getPlotMinID()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().minPlotID.replaceAll("%min_id%", String.valueOf(PlotManager.getPlotMinID()))); - return false; - } - if (plotID > PlotManager.getPlotMaxID()) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().maxPlotID.replaceAll("%max_id%", String.valueOf(PlotManager.getPlotMaxID()))); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - printInfo(sender, plot); - break; - } - case "TP": { - if (!Permissions.hasPermission(sender, commandPermission, "tp")) return false; - if (!(sender instanceof Player)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cmdOnlyPlayers); - return false; - } - if (args.length == 2) { - int plotID; - try { - plotID = Integer.parseInt(args[1]); - } catch (IllegalArgumentException e) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); - return false; - } - Plot plot = PlotManager.getPlot(plotID); - if (plot == null) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); - return false; - } - Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); - loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); - p.teleport(loc); - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); - } - break; - } - default: { - printHelp(sender); - break; - } - } - } - return false; - } - - private static void printInfo(CommandSender sender, Plot plot) { - LocalDateTime localDateTime = plot.getOwnedUntilDate(); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); - String assignedBy = VirtualRealty.getMessages().notAssigned; - if (plot.getAssignedBy() != null) { - switch (plot.getAssignedBy().toUpperCase()) { - case "CONSOLE": { - assignedBy = VirtualRealty.getMessages().assignedByConsole; - break; - } - case "SHOP_PURCHASE": { - assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; - break; - } - default: { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); - assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); - } - } - } - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); - sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); - if (plot.getMembers().size() != 0) { - sender.sendMessage(" §7Members §8§l↴"); - for (OfflinePlayer offlinePlayer : plot.getMembersPlayer()) { - sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); - } - } - sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); - sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); - sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); - sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); - sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); - sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); - sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); - sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); - sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); - sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); - sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); - } - - private static void printHelp(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot create §8- §7Creates a plot"); - sender.sendMessage(" §a/vrplot remove §8- §7Removes a plot"); - sender.sendMessage(" §a/vrplot set §8- §7Sets a variable for the plot"); - sender.sendMessage(" §a/vrplot assign §8- §7Assigns a plot to player"); - sender.sendMessage(" §a/vrplot unassign §8- §7Sets assigned to and assigned by to null"); - sender.sendMessage(" §a/vrplot info §8- §7Prints info about plot"); - sender.sendMessage(" §a/vrplot list §8- §7Prints all plots"); - sender.sendMessage(" §a/vrplot tp §8- §7Teleports to the plot"); - sender.sendMessage(" §a/vrplot reload §8- §7Reloads plugin"); - } - - private static void printSetHelp(CommandSender sender) { - sender.sendMessage(" "); - sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownedBy §8<§7username§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7floorMaterial §8<§7material§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7borderMaterial §8<§7material§8>"); - sender.sendMessage(" §a/vrplot set §8<§7plotID§8> §7ownershipExpires §8<§7dd/mm/YYYY§8> §8<§7HH:mm (optional)§8>"); - } - -} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java new file mode 100644 index 0000000..858c8cd --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java @@ -0,0 +1,66 @@ +package com.modnmetl.virtualrealty.commands.plot; + +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +import java.lang.reflect.InvocationTargetException; +import java.util.*; + +public class PlotCommand implements CommandExecutor { + + public static final LinkedList HELP_LIST = new LinkedList<>(); + + static { + HELP_LIST.add(" "); + HELP_LIST.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP_LIST.add(" §a/plot panel §8- §7Opens your plots panel"); + HELP_LIST.add(" §a/plot draft §8- §7Enables draft mode"); + HELP_LIST.add(" §a/plot stake §8- §7Creates a plot when not colliding"); + HELP_LIST.add(" §a/plot info §8- §7Shows plot info"); + HELP_LIST.add(" §a/plot gm §8- §7Changes gamemode"); + HELP_LIST.add(" §a/plot add §8- §7Adds a member"); + HELP_LIST.add(" §a/plot kick §8- §7Kicks a member"); + HELP_LIST.add(" §a/plot list §8- §7Shows your plots"); + HELP_LIST.add(" §a/plot tp §8- §7Teleports to the plot"); + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + boolean displayError = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--error")); + args = Arrays.stream(args).filter(s1 -> !s1.equalsIgnoreCase("--error")).toArray(String[]::new); + if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { + printHelp(sender); + return false; + } + if (args[0].equalsIgnoreCase("panel") || args[0].equalsIgnoreCase("draft") || args[0].equalsIgnoreCase("stake")) { + try { + Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader", true, VirtualRealty.getCustomClassLoader()); + } catch (Exception e) { + sender.sendMessage("§aThis function is available with a valid license key"); + sender.sendMessage("§aPlease visit §fhttps://modnmetl.com/ §ato purchase one"); + return false; + } + } + try { + Class clazz = Class.forName("com.modnmetl.virtualrealty.commands.plot.subcommand." + String.valueOf(args[0].toCharArray()[0]).toUpperCase(Locale.ROOT) + args[0].substring(1) + "SubCommand", true, VirtualRealty.getCustomClassLoader()); + clazz.getConstructors()[0].newInstance(sender, command, label, args); + } catch (Exception e) { + if (displayError) { + e.printStackTrace(); + } + if(!(e instanceof InvocationTargetException)) { + printHelp(sender); + } + } + return false; + } + + private static void printHelp(CommandSender sender) { + for (String message : HELP_LIST) { + sender.sendMessage(message); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/AddSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/AddSubCommand.java new file mode 100644 index 0000000..6715647 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/AddSubCommand.java @@ -0,0 +1,90 @@ +package com.modnmetl.virtualrealty.commands.plot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.enums.permissions.ManagementPermission; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.objects.PlotMember; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.time.LocalDateTime; +import java.util.LinkedList; + +public class AddSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/plot add §8<§7plot§8> §8<§7player§8>"); + } + + public AddSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + assertPlayer(); + Player player = ((Player) sender); + if (args.length < 3) { + printHelp(); + return; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[2]); + if (offlinePlayer.getFirstPlayed() == 0) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + if (!plot.hasMembershipAccess(player.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); + return; + } + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plotMember != null) { + if (!plotMember.hasManagementPermission(ManagementPermission.ADD_MEMBER)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noAccess); + return; + } + } else { + if (plot.getPlotOwner().getUniqueId() != player.getUniqueId()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noAccess); + return; + } + } + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantAddYourself); + return; + } + if (plot.getMember(offlinePlayer.getUniqueId()) != null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().alreadyInMembers); + return; + } + plot.addMember(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerAdd.replaceAll("%player%", offlinePlayer.getName())); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/GmSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/GmSubCommand.java new file mode 100644 index 0000000..7e33807 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/GmSubCommand.java @@ -0,0 +1,92 @@ +package com.modnmetl.virtualrealty.commands.plot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.managers.PlotMemberManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.objects.PlotMember; +import org.bukkit.GameMode; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.LinkedList; + +public class GmSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/plot gm §8<§7gamemode§8>"); + } + + public GmSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + assertPlayer(); + Player player = ((Player) sender); + if (args.length < 2) { + printHelp(); + return; + } + if (VirtualRealty.getPluginConfiguration().lockPlotGamemode) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeFeatureDisabled); + return; + } + GameMode gameMode; + int gameModeID; + try { + gameMode = GameMode.valueOf(args[1]); + gameModeID = gameMode.getValue(); + } catch (IllegalArgumentException e) { + try { + gameModeID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException ex) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().incorrectGamemode); + return; + } + } + GameMode defaultGamemode = VirtualRealty.getInstance().getServer().getDefaultGameMode(); + GameMode configGamemode = VirtualRealty.getPluginConfiguration().getDefaultPlotGamemode(); + if (!(gameModeID != configGamemode.getValue() && gameModeID != defaultGamemode.getValue())) { + gameMode = GameMode.getByValue(Integer.parseInt(args[1])); + } else { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeDisabled); + return; + } + Plot plot = PlotManager.getBorderedPlot(player.getLocation()); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); + return; + } + if (!plot.hasMembershipAccess(player.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantSwitchGamemode); + return; + } + if (plot.isOwnershipExpired()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (player.getGameMode().equals(gameMode)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeAlreadySelected); + return; + } + if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(player.getUniqueId())) { + plot.setSelectedGameMode(gameMode); + } else { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + plotMember.setSelectedGameMode(gameMode); + } + player.setGameMode(gameMode); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().gamemodeSwitched); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/InfoSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/InfoSubCommand.java new file mode 100644 index 0000000..641bf9b --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/InfoSubCommand.java @@ -0,0 +1,57 @@ +package com.modnmetl.virtualrealty.commands.plot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedList; + +public class InfoSubCommand extends SubCommand { + + public InfoSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, new LinkedList<>()); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + assertPlayer(); + Player player = ((Player) sender); + Plot plot = PlotManager.getPlot(player.getLocation()); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); + return; + } + printInfo(sender, plot); + } + + private void printInfo(CommandSender sender, Plot plot) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); + sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); + if (plot.getMembers().size() != 0) { + sender.sendMessage(" §7Members §8§l↴"); + for (OfflinePlayer offlinePlayer : plot.getPlayerMembers()) { + sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); + } + } + sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); + sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); + sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); + sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); + sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/KickSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/KickSubCommand.java new file mode 100644 index 0000000..a64b236 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/KickSubCommand.java @@ -0,0 +1,88 @@ +package com.modnmetl.virtualrealty.commands.plot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.enums.permissions.ManagementPermission; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.objects.PlotMember; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedList; + +public class KickSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/plot kick §8<§7plot§8> §8<§7player§8>"); + } + + public KickSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + assertPlayer(); + Player player = ((Player) sender); + if (args.length < 3) { + printHelp(); + return; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[2]); + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + if (!plot.hasMembershipAccess(player.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); + return; + } + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plotMember != null) { + if (!plotMember.hasManagementPermission(ManagementPermission.KICK_MEMBER)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noAccess); + return; + } + } else { + if (plot.getPlotOwner().getUniqueId() != player.getUniqueId()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noAccess); + return; + } + } + if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plot.getOwnedBy().equals(offlinePlayer.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantKickYourself); + return; + } + + plot.removeMember(plotMember); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerKick.replaceAll("%player%", offlinePlayer.getName())); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/ListSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/ListSubCommand.java new file mode 100644 index 0000000..33c20c6 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/ListSubCommand.java @@ -0,0 +1,100 @@ +package com.modnmetl.virtualrealty.commands.plot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedList; + +public class ListSubCommand extends SubCommand { + + public ListSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, new LinkedList<>()); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + assertPlayer(); + Player player = ((Player) sender); + boolean hasPlot = false; + for (Plot plot : PlotManager.getPlots()) { + if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(player.getUniqueId()) && plot.getOwnedUntilDate().isAfter(LocalDateTime.now())) { + hasPlot = true; + break; + } + } + boolean isMember = false; + for (Plot plot : PlotManager.getPlots()) { + if (plot.getMember(player.getUniqueId()) != null) { + isMember = true; + break; + } + } + if (!hasPlot && !isMember) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlayerPlotsFound); + return; + } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" "); + if (hasPlot) { + sender.sendMessage("§7§m "); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + for (Plot plot : PlotManager.getPlots()) { + if (plot.getPlotOwner() != null && plot.getPlotOwner().getUniqueId().equals(player.getUniqueId())) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + StringBuilder ownedBy = new StringBuilder(); + ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); + boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); + for (int i = ownedBy.length(); i < 16; i++) { + ownedBy.append(" "); + } + StringBuilder size = new StringBuilder(plot.getPlotSize().name()); + for (int i = size.length(); i < 6; i++) { + size.append(" "); + } + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + sender.sendMessage(textComponent.toLegacyText()); + } + } + sender.sendMessage("§7§m "); + } + if (isMember) { + sender.sendMessage(" "); + sender.sendMessage("§7 §fMember of §8§l↴"); + sender.sendMessage(" "); + sender.sendMessage("§7§m "); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + for (Plot plot : PlotManager.getPlots()) { + if (plot.getPlotOwner() != null && !plot.getPlotOwner().getUniqueId().equals(player.getUniqueId()) && plot.hasMembershipAccess(player.getUniqueId())) { + StringBuilder ownedBy = new StringBuilder(); + ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); + boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); + for (int i = ownedBy.length(); i < 16; i++) { + ownedBy.append(" "); + } + StringBuilder size = new StringBuilder(plot.getPlotSize().name()); + for (int i = size.length(); i < 6; i++) { + size.append(" "); + } + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + (isOwned ? " " : "") + ownedBy + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + sender.sendMessage(textComponent.toLegacyText()); + } + } + sender.sendMessage("§7§m "); + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java new file mode 100644 index 0000000..13bd0f6 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java @@ -0,0 +1,65 @@ +package com.modnmetl.virtualrealty.commands.plot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.Location; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Objects; + +public class TpSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/plot tp §8<§7plot§8>"); + } + + public TpSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + assertPlayer(); + Player player = ((Player) sender); + if (args.length < 2) { + printHelp(); + return; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + if (!plot.hasMembershipAccess(player.getUniqueId())) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notYourPlot); + return; + } + if (plot.isOwnershipExpired()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); + loc.setY(Objects.requireNonNull(loc.getWorld()).getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); + player.teleport(loc); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java new file mode 100644 index 0000000..c24c26c --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java @@ -0,0 +1,72 @@ +package com.modnmetl.virtualrealty.commands.vrplot; + +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.command.*; +import org.bukkit.permissions.Permission; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.InvocationTargetException; +import java.util.*; + +public class VirtualRealtyCommand implements CommandExecutor { + + public static final Permission COMMAND_PERMISSION = new Permission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".vrplot"); + + public static final LinkedList HELP_LIST = new LinkedList<>(); + + static { + HELP_LIST.add(" "); + HELP_LIST.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP_LIST.add(" §a/vrplot create §8- §7Creates a plot"); + HELP_LIST.add(" §a/vrplot remove §8- §7Removes a plot"); + HELP_LIST.add(" §a/vrplot set §8- §7Sets a variable for the plot"); + HELP_LIST.add(" §a/vrplot assign §8- §7Assigns a plot to player"); + HELP_LIST.add(" §a/vrplot unassign §8- §7Sets assigned to and assigned by to null"); + HELP_LIST.add(" §a/vrplot info §8- §7Prints info about plot"); + HELP_LIST.add(" §a/vrplot list §8- §7Prints all plots"); + HELP_LIST.add(" §a/vrplot item §8- §7Creates plot item"); + HELP_LIST.add(" §a/vrplot visual §8- §7Displays visual grid of the plot"); + HELP_LIST.add(" §a/vrplot tp §8- §7Teleports to the plot"); + HELP_LIST.add(" §a/vrplot reload §8- §7Reloads plugin"); + } + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + boolean displayError = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--error")); + args = Arrays.stream(args).filter(s1 -> !s1.equalsIgnoreCase("--error")).toArray(String[]::new); + if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName())) return false; + if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { + printHelp(sender); + return false; + } + if (args[0].equalsIgnoreCase("visual") || args[0].equalsIgnoreCase("item")) { + try { + Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader", true, VirtualRealty.getCustomClassLoader()); + } catch (Exception e) { + sender.sendMessage("§aThis function is available with a valid license key"); + sender.sendMessage("§aPlease visit §fhttps://modnmetl.com/ §ato purchase one"); + return false; + } + } + try { + Class clazz = Class.forName("com.modnmetl.virtualrealty.commands.vrplot.subcommand." + String.valueOf(args[0].toCharArray()[0]).toUpperCase(Locale.ROOT) + args[0].substring(1) + "SubCommand", true, VirtualRealty.getCustomClassLoader()); + clazz.getConstructors()[0].newInstance(sender, command, label, args); + } catch (Exception e) { + if (displayError) { + e.printStackTrace(); + } + if(!(e instanceof InvocationTargetException)) { + printHelp(sender); + } + } + return false; + } + + private static void printHelp(CommandSender sender) { + for (String message : HELP_LIST) { + sender.sendMessage(message); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/AssignSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/AssignSubCommand.java new file mode 100644 index 0000000..8c73e6b --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/AssignSubCommand.java @@ -0,0 +1,86 @@ +package com.modnmetl.virtualrealty.commands.vrplot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import com.modnmetl.virtualrealty.utils.UUIDUtils; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.UUID; + +import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; + +public class AssignSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/vrplot assign §8<§7plot§8> §8<§7username§8>"); + } + + public AssignSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + if (args.length < 2) { + for (String helpMessage : HELP) { + sender.sendMessage(helpMessage); + } + return; + } + int plotID; + OfflinePlayer offlinePlayer; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + try { + if (UUIDUtils.isValidUUID(args[2])) { + offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[2])); + } else { + offlinePlayer = Bukkit.getOfflinePlayer(args[2]); + } + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return; + } + } catch (NullPointerException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + if (sender instanceof Player) { + plot.setAssignedBy(((Player) sender).getUniqueId().toString()); + } else if (sender instanceof ConsoleCommandSender) { + plot.setAssignedBy("CONSOLE"); + } else { + plot.setAssignedBy("SHOP_PURCHASE"); + } + plot.setOwnedBy(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedToBy.replaceAll("%assigned_to%", offlinePlayer.getName()).replaceAll("%assigned_by%", sender.getName())); + plot.update(); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java new file mode 100644 index 0000000..240afcf --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java @@ -0,0 +1,219 @@ +package com.modnmetl.virtualrealty.commands.vrplot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.enums.Direction; +import com.modnmetl.virtualrealty.enums.PlotSize; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.objects.region.GridStructure; +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import com.modnmetl.virtualrealty.utils.RegionUtil; +import com.modnmetl.virtualrealty.utils.multiversion.Chat; +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; + +import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; + +public class CreateSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/vrplot create §8<§7small/medium/large/area§8> §8<§7floor (optional)§8> §8<§7border (optional)§8>"); + HELP.add(" §a/vrplot create §8<§7length§8> §8<§7height§8> §8<§7width§8> §8<§7floor (optional)§8> §8<§7border (optional)§8>"); + } + + public CreateSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + assertPlayer(); + if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + if (args.length < 2) { + printHelp(); + return; + } + Player player = ((Player) sender); + Location location = player.getLocation(); + location.add(0, -1, 0); + if (Arrays.stream(PlotSize.values()).anyMatch(plotSize -> plotSize.name().equalsIgnoreCase(args[1])) && !args[1].equalsIgnoreCase(PlotSize.CUSTOM.name())) { + PlotSize plotSize = null; + try { + plotSize = PlotSize.valueOf(args[1].toUpperCase()); + } catch (IllegalArgumentException ignored) {} + if (plotSize != null) { + if (PlotManager.isColliding(RegionUtil.getRegion(location, Direction.byYaw(location.getYaw()), plotSize.getLength(), plotSize.getHeight(), plotSize.getWidth()))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); + } else { + boolean natural = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--natural")); + Material floorMaterial = null; + byte floorData = 0; + Material borderMaterial = null; + byte borderData = 0; + if (plotSize != PlotSize.AREA) { + if (args.length >= 3 && !natural) { + try { + floorMaterial = VMaterial.getMaterial(args[2].split(":")[0].toUpperCase()); + if (floorMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return; + } + if (args[2].split(":").length == 2) { + floorData = Byte.parseByte(args[2].split(":")[1]); + } + } + if (args.length >= 4) { + try { + borderMaterial = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); + if (borderMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return; + } + if (args[3].split(":").length == 2) { + borderData = Byte.parseByte(args[3].split(":")[1]); + } + } + } + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); + long timeStart = System.currentTimeMillis(); + Plot plot = PlotManager.createPlot(location, plotSize, plotSize.getLength(), plotSize.getHeight(), plotSize.getWidth(), natural); + if (!natural) { + if (floorMaterial != null) { + plot.setFloorMaterial(floorMaterial, floorData); + } + if (borderMaterial != null) { + plot.setBorderMaterial(borderMaterial, borderData); + } + } + long timeEnd = System.currentTimeMillis(); + BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); + BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); + BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); + textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); + textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); + textComponent.addExtra(textComponent2); + textComponent.addExtra(textComponent3); + new Chat(textComponent).sendTo(player); + new BukkitRunnable() { + @Override + public void run() { + new GridStructure(player, plot.getPlotSize().getLength(), plot.getPlotSize().getHeight(), plot.getPlotSize().getWidth(), plot.getID(), ((Player) sender).getWorld(), 20 * 6, plot.getCreatedLocation()).preview(); + } + }.runTaskLater(VirtualRealty.getInstance(), 20); + } + } else { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().sizeNotRecognised); + } + } else { + int length; + int width; + int height; + try { + length = Integer.parseInt(args[1]); + height = Integer.parseInt(args[2]); + width = Integer.parseInt(args[3]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + if (length > 500 || width > 500 || height > 500) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().LHWHardLimit); + return; + } + if (PlotManager.isColliding(RegionUtil.getRegion(location, Direction.byYaw(location.getYaw()), length, height, width))) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); + } else { + boolean natural = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--natural")); + Material floorMaterial = null; + byte floorData = 0; + if (args.length >= 5 && !natural) { + try { + floorMaterial = VMaterial.getMaterial(args[4].split(":")[0].toUpperCase()); + if (floorMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetFloorMaterial); + return; + } + if (args[4].split(":").length == 2) { + floorData = Byte.parseByte(args[4].split(":")[1]); + } + } + Material borderMaterial = null; + byte borderData = 0; + if (args.length >= 6) { + try { + borderMaterial = VMaterial.getMaterial(args[5].split(":")[0].toUpperCase()); + if (borderMaterial == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetBorderMaterial); + return; + } + if (args[5].split(":").length == 2) { + borderData = Byte.parseByte(args[5].split(":")[1]); + } + } + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notCollidingCreating); + long timeStart = System.currentTimeMillis(); + Plot plot = PlotManager.createPlot(location, PlotSize.CUSTOM, length, height, width, natural); + if (!natural) { + if (floorMaterial != null) { + plot.setFloorMaterial(floorMaterial, floorData); + } + if (borderMaterial != null) { + plot.setBorderMaterial(borderMaterial, borderData); + } + } + long timeEnd = System.currentTimeMillis(); + BaseComponent textComponent = new TextComponent(VirtualRealty.PREFIX + VirtualRealty.getMessages().creationPlotComponent1); + BaseComponent textComponent2 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent2.replaceAll("%plot_id%", String.valueOf(plot.getID()))); + BaseComponent textComponent3 = new TextComponent(VirtualRealty.getMessages().creationPlotComponent3.replaceAll("%creation_time%", String.valueOf(timeEnd - timeStart))); + textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); + textComponent2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); + textComponent.addExtra(textComponent2); + textComponent.addExtra(textComponent3); + new Chat(textComponent).sendTo(player); + new BukkitRunnable() { + @Override + public void run() { + new GridStructure(player, plot.getLength(), plot.getHeight(), plot.getWidth(), plot.getID(), ((Player) sender).getWorld(), 20 * 6, plot.getCreatedLocation()).preview(); + } + }.runTaskLater(VirtualRealty.getInstance(), 20); + } + } + } + + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java new file mode 100644 index 0000000..0fdeced --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java @@ -0,0 +1,111 @@ +package com.modnmetl.virtualrealty.commands.vrplot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.LinkedList; +import java.util.UUID; + +import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; + +public class InfoSubCommand extends SubCommand { + + public InfoSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, new LinkedList<>()); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + if (args.length < 2) { + assertPlayer(); + Plot plot = PlotManager.getPlot(((Player) sender).getLocation()); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().notStandingOnPlot); + return; + } + printInfo(sender, plot); + return; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + if (PlotManager.getPlots().isEmpty()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); + return; + } + if (plotID < PlotManager.getPlotMinID()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().minPlotID.replaceAll("%min_id%", String.valueOf(PlotManager.getPlotMinID()))); + return; + } + if (plotID > PlotManager.getPlotMaxID()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().maxPlotID.replaceAll("%max_id%", String.valueOf(PlotManager.getPlotMaxID()))); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + printInfo(sender, plot); + } + + private void printInfo(CommandSender sender, Plot plot) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); + String assignedBy = VirtualRealty.getMessages().notAssigned; + if (plot.getAssignedBy() != null) { + switch (plot.getAssignedBy().toUpperCase()) { + case "CONSOLE": { + assignedBy = VirtualRealty.getMessages().assignedByConsole; + break; + } + case "SHOP_PURCHASE": { + assignedBy = VirtualRealty.getMessages().assignedByShopPurchase; + break; + } + default: { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(plot.getAssignedBy())); + assignedBy = (offlinePlayer.isOnline() ? "§a" : "§c") + offlinePlayer.getName(); + } + } + } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" §7Plot ID §8§l‣ §f" + plot.getID()); + sender.sendMessage(" §7Owned By §8§l‣ §a" + (plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : "§cAvailable")); + if (plot.getMembers().size() != 0) { + sender.sendMessage(" §7Members §8§l↴"); + for (OfflinePlayer offlinePlayer : plot.getPlayerMembers()) { + sender.sendMessage(" §8§l⁍ §" + (offlinePlayer.isOnline() ? "a" : "c") + offlinePlayer.getName()); + } + } + sender.sendMessage(" §7Assigned By §8§l‣ §a" + assignedBy); + sender.sendMessage(" §7Owned Until §8§l‣ §f" + dateTimeFormatter.format(localDateTime)); + sender.sendMessage(" §7Size §8§l‣ §f" + plot.getPlotSize()); + sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); + sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); + sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); + sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); + sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); + sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); + sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); + sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ListSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ListSubCommand.java new file mode 100644 index 0000000..9d56291 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ListSubCommand.java @@ -0,0 +1,64 @@ +package com.modnmetl.virtualrealty.commands.vrplot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import com.modnmetl.virtualrealty.utils.multiversion.Chat; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedList; + +import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; + +public class ListSubCommand extends SubCommand { + + public ListSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, new LinkedList<>()); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + if (PlotManager.getPlots().isEmpty()) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); + return; + } + sender.sendMessage(" "); + sender.sendMessage(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + sender.sendMessage(" "); + sender.sendMessage("§7§m "); + sender.sendMessage("§7| §a§l§oID§7 | §a§l§oOwned By§7 | §a§l§oOwned Until§7 | §a§l§oSize§7 | §a§l§oPlot Center§7 |"); + for (Plot plot : PlotManager.getPlots()) { + LocalDateTime localDateTime = plot.getOwnedUntilDate(); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + StringBuilder ownedBy = new StringBuilder(); + ownedBy.append((plot.getOwnedBy() != null ? (Bukkit.getOfflinePlayer(plot.getOwnedBy()).isOnline() ? "§a" : "§c") + Bukkit.getOfflinePlayer(plot.getOwnedBy()).getName() : VirtualRealty.getMessages().available)); + boolean isOwned = !ownedBy.toString().equals(VirtualRealty.getMessages().available); + for (int i = ownedBy.length(); i < 16; i++) { + ownedBy.append(" "); + } + StringBuilder size = new StringBuilder(plot.getPlotSize().name()); + for (int i = size.length(); i < 6; i++) { + size.append(" "); + } + BaseComponent textComponent = new TextComponent("§f" + plot.getID() + "§8 §f" + ownedBy.substring(0, 14) + "§8 §f" + (isOwned ? " " : "") + dateTimeFormatter.format(localDateTime) + "§8 §f" + size + "§8 §f" + plot.getCenter().toSimpleString()); + textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(VirtualRealty.getMessages().clickToShowDetailedInfo.replaceAll("%plot_id%", String.valueOf(plot.getID())))})); + textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vrplot info " + plot.getID())); + new Chat(textComponent).sendTo(sender); + } + sender.sendMessage("§7§m "); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ReloadSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ReloadSubCommand.java new file mode 100644 index 0000000..8d673a8 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ReloadSubCommand.java @@ -0,0 +1,49 @@ +package com.modnmetl.virtualrealty.commands.vrplot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.LinkedList; + +import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; + +public class ReloadSubCommand extends SubCommand { + + public ReloadSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, new LinkedList<>()); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + try { + VirtualRealty.getInstance().reloadConfigs(); + if (VirtualRealty.getPluginConfiguration().dynmapMarkers) { + if (VirtualRealty.markerset != null) { + VirtualRealty.markerset.deleteMarkerSet(); + } + VirtualRealty.getInstance().registerDynmap(); + for (Plot plot : PlotManager.getPlots()) { + PlotManager.resetPlotMarker(plot); + } + } else { + if (VirtualRealty.markerset != null) { + VirtualRealty.markerset.deleteMarkerSet(); + } + } + PlotManager.loadPlots(); + VirtualRealty.getInstance().loadSizesConfiguration(); + } catch (Exception exception) { + exception.printStackTrace(); + } + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().reloadComplete); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/RemoveSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/RemoveSubCommand.java new file mode 100644 index 0000000..ea1a07a --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/RemoveSubCommand.java @@ -0,0 +1,53 @@ +package com.modnmetl.virtualrealty.commands.vrplot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.LinkedList; + +public class RemoveSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/vrplot remove §8<§7plot§8>"); + } + + public RemoveSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + if (args.length < 2) { + printHelp(); + return; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + plot.remove(); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().removedPlot); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/SetSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/SetSubCommand.java new file mode 100644 index 0000000..44a7c7a --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/SetSubCommand.java @@ -0,0 +1,242 @@ +package com.modnmetl.virtualrealty.commands.vrplot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import com.modnmetl.virtualrealty.utils.UUIDUtils; +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.RemoteConsoleCommandSender; + +import java.time.LocalDateTime; +import java.util.*; + +public class SetSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/vrplot set §8<§7plot§8> §aowner §8<§7username§8>"); + HELP.add(" §a/vrplot set §8<§7plot§8> §afloor §8<§7material§8>"); + HELP.add(" §a/vrplot set §8<§7plot§8> §aborder §8<§7material§8>"); + HELP.add(" §a/vrplot set §8<§7plot§8> §aexpiry §8<§7dd/mm/YYYY§8> §8<§7HH:mm (optional)§8>"); + } + + public SetSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + if (args.length < 3) { + printHelp(); + return; + } + switch (args[2].toUpperCase()) { + case "OWNER": { + if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase())) return; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyUsername); + return; + } + int plotID; + OfflinePlayer offlinePlayer; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + try { + if (UUIDUtils.isValidUUID(args[3])) { + offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(args[3])); + } else { + offlinePlayer = Bukkit.getOfflinePlayer(args[3]); + } + if (offlinePlayer.getName() == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return; + } + } catch (NullPointerException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().playerNotFoundWithUsername); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + if (args.length >= 5) { + String dateFormat = args[4]; + String timeFormat; + int year; + int month; + int dayOfMonth; + int hour = 0; + int minute = 0; + LocalDateTime localDateTime; + try { + year = Integer.parseInt(dateFormat.split("/")[2]); + month = Integer.parseInt(dateFormat.split("/")[1]); + dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); + if (args.length >= 6) { + timeFormat = args[5]; + hour = Integer.parseInt(timeFormat.split(":")[0]); + minute = Integer.parseInt(timeFormat.split(":")[1]); + } + localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); + return; + } + plot.setOwnedUntilDate(localDateTime); + } + if (sender instanceof RemoteConsoleCommandSender && args.length >= 7 && args[6].equalsIgnoreCase("assign")) { + plot.setAssignedBy("SHOP_PURCHASE"); + } + plot.setOwnedBy(offlinePlayer.getUniqueId()); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().assignedTo.replaceAll("%assigned_to%", offlinePlayer.getName())); + plot.update(); + return; + } + case "FLOOR": { + if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase())) return; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); + return; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + Material material; + try { + material = Material.matchMaterial(args[3].split(":")[0].toUpperCase()); + if (material == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + byte data = 0; + if (args[3].split(":").length == 2) { + data = Byte.parseByte(args[3].split(":")[1]); + } + plot.setFloorMaterial(material, data); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newFloorMaterialSet); + plot.update(); + return; + } + case "BORDER": { + if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase())) return; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); + return; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + Material material; + try { + material = VMaterial.getMaterial(args[3].split(":")[0].toUpperCase()); + if (material == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return; + } + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantGetMaterial); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + byte data = 0; + if (args[3].split(":").length == 2) { + data = Byte.parseByte(args[3].split(":")[1]); + } + plot.setBorderMaterial(material, data); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().newBorderMaterialSet); + plot.update(); + return; + } + case "EXPIRY": { + if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase())) return; + if (args.length < 4) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyExpiryDate); + return; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + String dateFormat = args[3]; + String timeFormat; + int year; + int month; + int dayOfMonth; + int hour = 0; + int minute = 0; + LocalDateTime localDateTime; + try { + year = Integer.parseInt(dateFormat.split("/")[2]); + month = Integer.parseInt(dateFormat.split("/")[1]); + dayOfMonth = Integer.parseInt(dateFormat.split("/")[0]); + if (args.length == 5) { + timeFormat = args[4]; + hour = Integer.parseInt(timeFormat.split(":")[0]); + minute = Integer.parseInt(timeFormat.split(":")[1]); + } + localDateTime = LocalDateTime.of(year, month, dayOfMonth, hour, minute); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().invalidDateProvided); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + plot.setOwnedUntilDate(localDateTime); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownedUntilUpdated); + plot.update(); + return; + } + default: { + for (String helpMessage : HELP) { + sender.sendMessage(helpMessage); + } + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java new file mode 100644 index 0000000..c60d3a7 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java @@ -0,0 +1,60 @@ +package com.modnmetl.virtualrealty.commands.vrplot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import org.bukkit.Location; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.LinkedList; + +import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; + +public class TpSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/vrplot tp §8<§7plot§8>"); + } + + public TpSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + assertPlayer(); + if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + if (args.length < 2) { + printHelp(); + return; + } + Player player = ((Player) sender); + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); + loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); + player.teleport(loc); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/UnassignSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/UnassignSubCommand.java new file mode 100644 index 0000000..30c5d84 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/UnassignSubCommand.java @@ -0,0 +1,55 @@ +package com.modnmetl.virtualrealty.commands.vrplot.subcommand; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.commands.SubCommand; +import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.PermissionUtil; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.LinkedList; + +public class UnassignSubCommand extends SubCommand { + + public static final LinkedList HELP = new LinkedList<>(); + + static { + HELP.add(" "); + HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); + HELP.add(" §a/vrplot unassign §8<§7plot§8>"); + } + + public UnassignSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + super(sender, command, label, args, HELP); + } + + @Override + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + if (args.length < 2) { + printHelp(); + return; + } + int plotID; + try { + plotID = Integer.parseInt(args[1]); + } catch (IllegalArgumentException e) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().useNaturalNumbersOnly); + return; + } + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); + return; + } + plot.setAssignedBy(null); + plot.setOwnedBy(null); + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().unassigned); + plot.update(); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java index cd379df..1a23b3c 100644 --- a/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java +++ b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java @@ -1,69 +1,117 @@ package com.modnmetl.virtualrealty.configs; import eu.okaeri.configs.OkaeriConfig; +import eu.okaeri.configs.annotation.Header; +import eu.okaeri.configs.annotation.NameModifier; +import eu.okaeri.configs.annotation.NameStrategy; +import eu.okaeri.configs.annotation.Names; +import java.util.Arrays; +import java.util.List; + +@Header("-------------------------------------------------------------- #") +@Header(" #") +@Header(" Messages #") +@Header(" #") +@Header("-------------------------------------------------------------- #") +@Names(strategy = NameStrategy.IDENTITY) public class MessagesConfiguration extends OkaeriConfig { + //Core + public String reloadComplete = "§aReload complete!"; + public String cmdOnlyPlayers = "§cCommand only for players!"; + public String noAccess = "§cYou don't have access to this feature!"; + + //Markers + public String available = "§cAvailable"; + public String assignedByConsole = "§eConsole"; + public String assignedByShopPurchase = "§eShop Purchase"; + public String notAssigned = "§cNot assigned"; + public String creationPlotComponent1 = "§aPlot "; + public String creationPlotComponent2 = "§8#§7%plot_id%"; + public String creationPlotComponent3 = " §acreated! §8(§7%creation_time% ms§8)"; + + //Checks + public String insufficientPermissions = "§cInsufficient permissions! §8(§7%permission%§8)"; public String useNaturalNumbersOnly = "§cUse only natural numbers!"; + public String incorrectGamemode = "§cIncorrect gamemode value!"; + public String sizeNotRecognised = "§cSize not recognized!"; + public String LHWHardLimit = "§cL, W and H hard-limit is 500!"; + public String specifyUsername = "§cSpecify username!"; + public String playerNotFoundWithUsername = "§cCouldn't find player with specified username!"; + public String invalidDateProvided = "§cInvalid date format provided!"; + public String specifyMaterialName = "§cSpecify material name!"; + public String specifyExpiryDate = "§cSpecify expiry date!"; + public String minPlotID = "§cMinimum plot ID is %min_id%!"; + public String maxPlotID = "§cMaximum plot ID is %max_id%!"; + + //Permissions + public String cantDoAnyDMG = "§cYou can't do any damage here!"; + public String cantInteract = "§cYou can't interact here!"; + public String cantBuildHere = "§cYou can't build here!"; + public String cantRideOnPlot = "§cYou can't ride on someones plot!"; + + //Plot public String noPlotFound = "§cCouldn't get plot with specified ID!"; public String notYourPlot = "§cIt's not your plot!"; public String ownershipExpired = "§cYour ownership has expired!"; public String teleportedToPlot = "§aYou have been teleported to the plot!"; public String gamemodeFeatureDisabled = "§cGamemode feature is disabled!"; - public String incorrectGamemode = "§cIncorrect gamemode value!"; public String gamemodeDisabled = "§cThis gamemode is disabled!"; public String cantSwitchGamemode = "§cYou can't switch gamemode here!"; - public String notStandingOnPlot = "§cYou aren't standing on any plot!"; - public String assignedByConsole = "§eConsole"; - public String assignedByShopPurchase = "§eShop Purchase"; public String noPlots = "§cThere are no plots!"; - public String available = "§cAvailable"; - public String reloadCompleted = "§aReload completed!"; + public String noPlayerPlotsFound = "§cYou don't own any plot!"; public String cantCreateOnExisting = "§cYou can't create new plot over an existing plot!"; public String cantGetFloorMaterial = "§cCouldn't get floor material with specified name!"; public String cantGetBorderMaterial = "§cCouldn't get border material with specified name!"; public String cantGetMaterial = "§cCouldn't get material with specified name!"; public String notCollidingCreating = "§aNot colliding. Creating plot.."; public String clickToShowDetailedInfo = "§a§oClick to show detailed information about the plot! §8(§7ID: §f%plot_id%§8)"; - public String sizeNotRecognised = "§cSize not recognized!"; - public String LWHHardLimit = "§cL, W and H hard-limit is 500!"; - public String removedPlot = "§aSuccessfully removed plot!"; - public String specifyUsername = "§cSpecify username!"; - public String playerNotFoundWithUsername = "§cCouldn't find player with specified username!"; - public String invalidDateProvided = "§cInvalid date format provided!"; + public String removedPlot = "§aPlot successfully removed!"; public String assignedTo = "§aPlot has been assigned to §f%assigned_to%!"; - public String specifyMaterialName = "§cSpecify material name!"; - public String specifyExpiryDate = "§cSpecify expiry date!"; public String newFloorMaterialSet = "§aNew floor material has been set!"; public String newBorderMaterialSet = "§aNew border material has been set!"; public String ownedUntilUpdated = "§aOwned until date has been updated!"; public String assignedToBy = "§aPlot has been assigned to §f%assigned_to% §aby §f%assigned_by%!"; - public String notAssigned = "§cNot assigned"; public String unassigned = "§aPlot has been unassigned!"; - public String minPlotID = "§cMinimum plot ID is %min_id%!"; - public String maxPlotID = "§cMaximum plot ID is %max_id%!"; - public String cmdOnlyPlayers = "§cCommand only for players!"; - - public String enteredAvailablePlot = "§2You have entered an available plot!"; - public String enteredOwnedPlot = "§7You have entered §2%owner%'s §7plot!"; - public String leftAvailablePlot = "§cYou have left an available plot!"; - public String leftOwnedPlot = "§7You have left §2%owner%'s §7plot!"; - public String cantInteract = "§cYou can't interact here!"; - public String cantBuildHere = "§cYou can't build here!"; - public String cantRideOnPlot = "§cYou can't ride on someones plot!"; - - public String creationPlotComponent1 = "§aPlot "; - public String creationPlotComponent2 = "§8#§7%plot_id%"; - public String creationPlotComponent3 = " §acreated! §8(§7%creation_time% ms§8)"; - public String cantAddYourself = "§cYou can't add yourself to the plot!"; public String cantKickYourself = "§cYou can't kick yourself from the plot!"; public String alreadyInMembers = "§cThis player is already one of the plot members!"; - public String notInMembers = "§cThis player is not one of the plot members!"; - public String cantDoAnyDMG = "§cYou can't do any damage here!"; + public String standingOnPlot = "§cYou are standing on a plot!"; + public String notStandingOnPlot = "§cYou aren't standing on any plot!"; public String playerKick = "§aPlayer §7%player% §ahas been kicked out of your plot!"; public String playerAdd = "§aPlayer §7%player% §ahas been added to your plot!"; public String gamemodeSwitched = "§aYour gamemode has changed!"; public String gamemodeAlreadySelected = "§cThis gamemode is already selected!"; + public String noPlotMembers = "§cThis plot has no members."; + + //Entrance + public String enteredAvailablePlot = "§2You have entered an available plot!"; + public String enteredOwnedPlot = "§7You have entered §2%owner%'s §7plot!"; + public String leftAvailablePlot = "§cYou have left an available plot!"; + public String leftOwnedPlot = "§7You have left §2%owner%'s §7plot!"; + public String enteredProtectedArea = "§6You have entered a protected area!"; + public String leftProtectedArea = "§6You have left a protected area!"; + + //Draft + public String notHoldingPlotClaim = "§cYou currently don't hold any plot claim item in your hand."; + public String cantPlaceDraftItems = "§cYou can't place draft items."; + public String noDraftClaimEnabled = "§cYou don't have plot draft claim enabled."; + public String draftModeDisabled = "§aDraft mode successfully disabled!"; + public String draftModeCancelled = "§cDraft cancelled. Collision with another plot."; + public String draftModeCancelledCollision = "§cDraft cancelled. Collision with another plot."; + public String draftModeDisabledDueToDeath = "§cDraft mode has been disabled due to death."; + public List draftModeEnabled = Arrays.asList( + " ", + " §8§l«§8§m §8[§aDraft Mode§8]§m §8§l»", + " ", + " §8§l» §7Type §a/plot stake §7to place plot.", + " §8§l» §7If you want to leave draft mode type §a/plot draft", + " " + ); + + //Other + public String visualBoundaryDisplayed = "§aThe visual boundary was displayed."; + public String visualBoundaryActive = "§cThe visual boundary is already active for this region."; } diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/PermissionsConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/PermissionsConfiguration.java new file mode 100644 index 0000000..1c432d5 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/configs/PermissionsConfiguration.java @@ -0,0 +1,51 @@ +package com.modnmetl.virtualrealty.configs; + +import com.modnmetl.virtualrealty.enums.permissions.RegionPermission; +import eu.okaeri.configs.OkaeriConfig; +import eu.okaeri.configs.annotation.*; + +import javax.swing.plaf.synth.Region; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +@Header("-------------------------------------------------------------- #") +@Header(" #") +@Header(" Permissions #") +@Header(" #") +@Header("-------------------------------------------------------------- #") +@Names(strategy = NameStrategy.HYPHEN_CASE, modifier = NameModifier.TO_LOWER_CASE) +public class PermissionsConfiguration extends OkaeriConfig { + + @Comment("Available permissions ↓") + @Comment(" - BREAK") + @Comment(" - PLACE") + @Comment(" - CHEST_ACCESS") + @Comment(" - ARMOR_STAND") + @Comment(" - ENTITY_DAMAGE") + @Comment(" - SWITCH") + @Comment(" - ITEM_USE") + @Comment(" ") + @Comment("Set permissions for players who are not members of the plot.") + private final List defaultNonMembers = new LinkedList<>(); + + public List getDefaultNonMemberPlotPerms() { + return defaultNonMembers; + } + + @Comment("Set permissions for players who are members of the plot.") + private final List defaultMembers = Arrays.asList(RegionPermission.values()); + + public List getDefaultMemberPerms() { + return defaultMembers; + } + + @Comment("Set permissions for all players to the world") + public final List worldProtection = Arrays.asList(RegionPermission.values()); + + public List getWorldProtection() { + return worldProtection; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java index 639ff56..8af198f 100644 --- a/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java +++ b/src/main/java/com/modnmetl/virtualrealty/configs/PluginConfiguration.java @@ -1,95 +1,82 @@ package com.modnmetl.virtualrealty.configs; -import com.modnmetl.virtualrealty.enums.HighlightType; +import com.modnmetl.virtualrealty.enums.dynmap.HighlightType; +import com.modnmetl.virtualrealty.enums.ServerVersion; import eu.okaeri.configs.OkaeriConfig; import eu.okaeri.configs.annotation.*; import com.modnmetl.virtualrealty.VirtualRealty; +import lombok.NoArgsConstructor; import org.bukkit.GameMode; -@Header("################################################################") -@Header("# #") -@Header("# Virtual Realty #") -@Header("# #") -@Header("################################################################") -@Names(strategy = NameStrategy.IDENTITY, modifier = NameModifier.TO_LOWER_CASE) +@Header("-------------------------------------------------------------- #") +@Header(" #") +@Header(" Virtual Realty #") +@Header(" #") +@Header("-------------------------------------------------------------- #") +@Names(strategy = NameStrategy.HYPHEN_CASE, modifier = NameModifier.TO_LOWER_CASE) public class PluginConfiguration extends OkaeriConfig { - @Comment(" ") - @Comment("-------------------------") - @Comment("Don't change this value!") - @CustomKey("config-version") - public String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); + @Comment("Changing this value will break your plugin!") + @CustomKey("initial-version") + public String initServerVersion = VirtualRealty.legacyVersion ? ServerVersion.LEGACY.toString() : ServerVersion.MODERN.toString(); - @Comment("-------------------------") - @Comment("Debug mode (Dev only)") - @CustomKey("debug-mode") + @Comment("Debug mode") public boolean debugMode = false; - @CustomKey("LICENSE-KEY") - public String licenseKey = ""; + @Comment("Here you put your license details") + public License license = new License(); + + @Names(strategy = NameStrategy.IDENTITY) + public static class License extends OkaeriConfig { + + public String key = ""; + public String email = ""; + + } @Comment("Set player gamemode to change when they enter their plot") - @CustomKey("enable-plot-gamemode") - public boolean enablePlotGameMode = false; + public boolean enablePlotGamemode = false; @Comment("Set your wanted language (locale)") - public String locale = VirtualRealty.getInstance().availableLocales.contains(VirtualRealty.getLocale()) ? VirtualRealty.getLocale().toString() : "en_GB"; + public String locale = "en_GB"; @Comment("Set which gamemode players change to when they enter their plot") @CustomKey("default-plot-gamemode") - public String plotGameMode = "SURVIVAL"; + public String plotGamemode = "SURVIVAL"; @Comment("Lock gamemode to plot default when player enters their plot (disables '/plot gm' command)") - @CustomKey("lock-plot-gamemode") - public boolean lockPlotGameMode = false; + public boolean lockPlotGamemode = false; - public GameMode getGameMode() { + public GameMode getDefaultPlotGamemode() { try { - return GameMode.valueOf(plotGameMode); + return GameMode.valueOf(plotGamemode); } catch (Exception e) { VirtualRealty.getInstance().getLogger().warning("Couldn't parse plot-gamemode from config.yml\nUsing default: SURVIVAL"); return GameMode.SURVIVAL; } } - @Comment("Allow players to build outside of their plots") - @CustomKey("allow-outplot-build") - public boolean allowOutPlotBuild = true; - @Comment("Enables dynmap plots highlighting") @CustomKey("enable-dynmap-markers") public boolean dynmapMarkers = false; @Comment("Choose which type of plots should be highlighted on Dynmap page | Choose from: { ALL, AVAILABLE, OWNED }") - @CustomKey("dynmap-type") public HighlightType dynmapType = HighlightType.ALL; @CustomKey("dynmap-markers") - public MarkerColor dynmapMarkersColor = new MarkerColor(new MarkerColor.Available("#80eb34", .3), new MarkerColor.Owned("#ffbf00", .45)); + public MarkerColor dynmapMarkersColor = new MarkerColor(); @Names(strategy = NameStrategy.IDENTITY) public static class MarkerColor extends OkaeriConfig { - public Available available; - - public Owned owned; - - public MarkerColor(Available available, Owned owned) { - this.available = available; - this.owned = owned; - } + public Available available = new Available(); + public Owned owned = new MarkerColor.Owned(); @Names(strategy = NameStrategy.IDENTITY) public static class Available extends OkaeriConfig { - public String color; - - public double opacity; - - public Available(String color, double opacity) { - this.color = color; - this.opacity = opacity; - } + public String color = "#80eb34"; + public double opacity = .3; public int getHexColor() { return Integer.decode("0x" + color.replaceAll("#", "")); @@ -100,14 +87,8 @@ public int getHexColor() { @Names(strategy = NameStrategy.IDENTITY) public static class Owned extends OkaeriConfig { - public String color; - - public double opacity; - - public Owned(String color, double opacity) { - this.color = color; - this.opacity = opacity; - } + public String color = "#ffbf00"; + public double opacity = .45; public int getHexColor() { return Integer.decode("0x" + color.replaceAll("#", "")); @@ -135,7 +116,7 @@ public int getHexColor() { @Comment("2. Change data in VR config") @Comment("3. Rename database tables using phpMyAdmin for example") @CustomKey("mysql") - public MySQL mysql = new MySQL("localhost", 3306, "db", "root", "passwd", true, "vr_plots"); + public MySQL mysql = new MySQL(); public enum DataModel { SQLITE, @@ -143,32 +124,17 @@ public enum DataModel { } @Names(strategy = NameStrategy.IDENTITY) + @NoArgsConstructor public static class MySQL extends OkaeriConfig { - @Variable("VR_MYSQL_HOSTNAME") - public String hostname; - @Variable("VR_MYSQL_PORT") - public int port; - @Variable("VR_MYSQL_DATABASE") - public String database; - @Variable("VR_MYSQL_USER") - public String user; - @Variable("VR_MYSQL_PASSWORD") - public String password; - @Variable("VR_MYSQL_USE_SSL") - public boolean useSSL; - @Variable("VR_MYSQL_USERS_TABLE_NAME") - public String plotsTableName; - - public MySQL(String hostname, int port, String database, String user, String password, boolean useSSL, String plotsTableName) { - this.hostname = hostname; - this.port = port; - this.database = database; - this.user = user; - this.password = password; - this.useSSL = useSSL; - this.plotsTableName = plotsTableName; - } + public String hostname = "localhost"; + public int port = 3306; + public String database = "db"; + public String user = "root"; + public String password = "passwd"; + public String plotsTableName = "vr_plots"; + public String plotMembersTableName = "vr_plot_members"; + } } diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java index a09ca11..1df10df 100644 --- a/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java +++ b/src/main/java/com/modnmetl/virtualrealty/configs/SizesConfiguration.java @@ -4,21 +4,15 @@ import eu.okaeri.configs.annotation.*; import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.enums.PlotSize; +import lombok.NoArgsConstructor; -@Header("################################################################") -@Header("# #") -@Header("# Plot Sizes #") -@Header("# #") -@Header("################################################################") +@Header("--------------------------------------------------------------#") +@Header(" #") +@Header(" Plot Sizes #") +@Header(" #") +@Header("--------------------------------------------------------------#") public class SizesConfiguration extends OkaeriConfig { - @Comment(" ") - @Comment("-------------------------") - @Comment("Don't change this value!") - @CustomKey("config-version") - public final String configVersion = VirtualRealty.getInstance().getDescription().getVersion(); - @Comment("-------------------------") - @Comment(" ") @Comment("(<1.13) Legacy Materials: https://helpch.at/docs/1.8/org/bukkit/Material.html") @Comment("(>1.12) Post-Legacy Materials: https://helpch.at/docs/1.13/org/bukkit/Material.html") @@ -28,47 +22,29 @@ public class SizesConfiguration extends OkaeriConfig { public PlotSizes plotSizes = new PlotSizes(); @Names(strategy = NameStrategy.IDENTITY) + @NoArgsConstructor public static class PlotSizes extends OkaeriConfig { - @Variable("VR_SIZE_SMALL") public Size SMALL = new Size(PlotSize.SMALL); - @Variable("VR_SIZE_MEDIUM") public Size MEDIUM = new Size(PlotSize.MEDIUM); - @Variable("VR_SIZE_LARGE") public Size LARGE = new Size(PlotSize.LARGE); + public CustomSize AREA = new CustomSize(); - public PlotSizes() { - } - - public PlotSizes(Size small, Size medium, Size large) { - this.SMALL = small; - this.MEDIUM = medium; - this.LARGE = large; - } + @NoArgsConstructor public static class Size extends OkaeriConfig { - @Variable("VR_SIZE_FLOORMATERIAL") @CustomKey("floor-material") public String floorMaterial; - @Variable("VR_SIZE_FLOORDATA") @CustomKey("floor-data") public byte floorData; - @Variable("VR_SIZE_BORDERMATERIAL") @CustomKey("border-material") public String borderMaterial; - @Variable("VR_SIZE_BORDERDATA") @CustomKey("border-data") public byte borderData; - @Variable("VR_SIZE_LENGTH") public int length; - @Variable("VR_SIZE_WIDTH") - public int width; - @Variable("VR_SIZE_HEIGHT") public int height; - - public Size() { - } + public int width; public Size(PlotSize plotSize) { this.floorMaterial = plotSize.getFloorMaterial().name(); @@ -81,6 +57,16 @@ public Size(PlotSize plotSize) { } } + + @NoArgsConstructor + public static class CustomSize extends OkaeriConfig { + + public int length = PlotSize.AREA.getLength(); + public int height = PlotSize.AREA.getHeight(); + public int width = PlotSize.AREA.getWidth(); + + } + } } diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/Flag.java b/src/main/java/com/modnmetl/virtualrealty/enums/Flag.java deleted file mode 100644 index 54e1a73..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/enums/Flag.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.modnmetl.virtualrealty.enums; - -public class Flag { - - public enum World { - - BLOCK_PLACE(false), - BLOCK_BREAK(false), - INTERACT(false), - IGNITE(false), - EXPLOSION_PRIME(false), - ENTITY_DAMAGE(false), - ARMOR_STAND_MANIPULATION(false), - ITEM_FRAME_DESTROY(false), - ITEM_FRAME_ROTATE(false); - - private boolean allowed; - - World(boolean allowed) { - this.allowed = allowed; - } - - public boolean isAllowed() { - return allowed; - } - - public void setAllowed(boolean allowed) { - this.allowed = allowed; - } - - } - -} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java b/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java index 4abf429..d35eadf 100644 --- a/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java +++ b/src/main/java/com/modnmetl/virtualrealty/enums/PlotSize.java @@ -1,86 +1,65 @@ package com.modnmetl.virtualrealty.enums; import com.modnmetl.virtualrealty.VirtualRealty; +import lombok.Data; +import lombok.Getter; import org.bukkit.Material; +@Getter public enum PlotSize { - SMALL(10, 10, 10, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), - MEDIUM(25, 25, 25, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), - LARGE(50, 50, 50, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0), - CUSTOM(0, 0, 0, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.isLegacy ? (byte)5 : (byte)0); + SMALL(10, 10, 10, Material.matchMaterial(VirtualRealty.legacyVersion ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.legacyVersion ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.legacyVersion ? (byte)5 : (byte)0), + MEDIUM(25, 25, 25, Material.matchMaterial(VirtualRealty.legacyVersion ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.legacyVersion ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.legacyVersion ? (byte)5 : (byte)0), + LARGE(50, 50, 50, Material.matchMaterial(VirtualRealty.legacyVersion ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.legacyVersion ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.legacyVersion ? (byte)5 : (byte)0), + CUSTOM(0, 0, 0, Material.matchMaterial(VirtualRealty.legacyVersion ? "GRASS" : "GRASS_BLOCK"), (byte)0, Material.matchMaterial(VirtualRealty.legacyVersion ? "STEP" : "STONE_BRICK_SLAB"), VirtualRealty.legacyVersion ? (byte)5 : (byte)0), + AREA(0, 0, 0, Material.AIR, (byte)0, Material.AIR, (byte)0); private int length; - private int width; private int height; + private int width; + private Material floorMaterial; private byte floorData; private Material borderMaterial; private byte borderData; - PlotSize(int length, int width, int height, Material floorMaterial, byte floorData, Material borderMaterial, byte borderData) { + PlotSize(int length, int height, int width, Material floorMaterial, byte floorData, Material borderMaterial, byte borderData) { this.length = length; - this.width = width; this.height = height; + this.width = width; this.floorMaterial = floorMaterial; this.floorData = floorData; this.borderMaterial = borderMaterial; this.borderData = borderData; } - public int getLength() { - return length; - } - public void setLength(int length) { this.length = length; } - public int getWidth() { - return width; - } - public void setWidth(int width) { this.width = width; } - public int getHeight() { - return height; - } - public void setHeight(int height) { this.height = height; } - public Material getFloorMaterial() { - return floorMaterial; - } public void setFloorMaterial(Material floorMaterial) { this.floorMaterial = floorMaterial; } - public byte getFloorData() { - return floorData; - } - public void setFloorData(byte floorData) { this.floorData = floorData; } - public Material getBorderMaterial() { - return borderMaterial; - } - public void setBorderMaterial(Material borderMaterial) { this.borderMaterial = borderMaterial; } - public byte getBorderData() { - return borderData; - } - public void setBorderData(byte borderData) { this.borderData = borderData; } + } diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/ServerVersion.java b/src/main/java/com/modnmetl/virtualrealty/enums/ServerVersion.java new file mode 100644 index 0000000..951ab5a --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/ServerVersion.java @@ -0,0 +1,8 @@ +package com.modnmetl.virtualrealty.enums; + +public enum ServerVersion { + + LEGACY, + MODERN + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/items/VItem.java b/src/main/java/com/modnmetl/virtualrealty/enums/items/VItem.java new file mode 100644 index 0000000..5b8a7c9 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/items/VItem.java @@ -0,0 +1,8 @@ +package com.modnmetl.virtualrealty.enums.items; + +public enum VItem { + + CLAIM, + DRAFT + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/materials/InteractMaterial.java b/src/main/java/com/modnmetl/virtualrealty/enums/materials/InteractMaterial.java new file mode 100644 index 0000000..b0a9157 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/materials/InteractMaterial.java @@ -0,0 +1,144 @@ +package com.modnmetl.virtualrealty.enums.materials; + +public enum InteractMaterial { + + WOODEN_DOOR, + IRON_DOOR_BLOCK, + WARPED_FENCE_GATE, + CRIMSON_FENCE_GATE, + WARPED_DOOR, + CRIMSON_DOOR, + + ACACIA_DOOR, + ACACIA_FENCE_GATE, + ACACIA_BUTTON, + ACACIA_TRAPDOOR, + ANVIL, + ARMOR_STAND, + BARREL, + BEACON, + BED_BLOCK, + BELL, + BIRCH_BOAT, + BIRCH_BUTTON, + BIRCH_DOOR, + BIRCH_FENCE_GATE, + BIRCH_TRAPDOOR, + BLACK_BED, + BLACK_SHULKER_BOX, + BLAST_FURNACE, + BLUE_BED, + BLUE_SHULKER_BOX, + BREWING_STAND, + BROWN_BED, + BROWN_SHULKER_BOX, + CAMPFIRE, + CAULDRON, + CHEST, + CHEST_MINECART, + CHIPPED_ANVIL, + COMMAND, + COMMAND_BLOCK, + COMMAND_BLOCK_MINECART, + COMPARATOR, + COMPOSTER, + CRAFTING_TABLE, + CYAN_BED, + CYAN_SHULKER_BOX, + DAMAGED_ANVIL, + DARK_OAK_BOAT, + DARK_OAK_BUTTON, + DARK_OAK_FENCE_GATE, + DARK_OAK_TRAPDOOR, + DARK_OAK_DOOR, + DAYLIGHT_DETECTOR, + DAYLIGHT_DETECTOR_INVERTED, + DIODE, + DIODE_BLOCK_OFF, + DIODE_BLOCK_ON, + DISPENSER, + DOOR, + DRAGON_EGG, + DROPPER, + ENCHANTING_TABLE, + ENCHANTMENT_TABLE, + END_CRYSTAL, + END_PORTAL_FRAME, + ENDER_PORTAL_FRAME, + ENDER_CHEST, + EXPLOSIVE_MINECART, + FARMLAND, + FLETCHING_TABLE, + FLOWER_POT, + FURNACE, + FURNACE_MINECART, + GRAY_BED, + GRAY_SHULKER_BOX, + GREEN_BED, + GREEN_SHULKER_BOX, + HOPPER, + HOPPER_MINECART, + IRON_DOOR, + IRON_TRAPDOOR, + ITEM_FRAME, + JUKEBOX, + JUNGLE_BUTTON, + JUNGLE_BOAT, + JUNGLE_DOOR, + JUNGLE_FENCE_GATE, + LEVER, + LIGHT_BLUE_BED, + LIGHT_BLUE_SHULKER_BOX, + LIGHT_GRAY_BED, + LIGHT_GRAY_SHULKER_BOX, + LIME_BED, + LIME_SHULKER_BOX, + MAGENTA_BED, + MAGENTA_SHULKER_BOX, + MINECART, + NOTE_BLOCK, + OAK_BOAT, + OAK_BUTTON, + OAK_DOOR, + OAK_FENCE_GATE, + ORANGE_BED, + ORANGE_SHULKER_BOX, + PINK_BED, + PINK_SHULKER_BOX, + POWERED_MINECART, + PURPLE_BED, + PURPLE_SHULKER_BOX, + RED_BED, + RED_SHULKER_BOX, + REDSTONE_ORE, + REDSTONE_COMPARATOR_OFF, + REDSTONE_COMPARATOR_ON, + REPEATING_COMMAND_BLOCK, + REPEATER, + POWERED_REPEATER, + UNPOWERED_REPEATER, + REDSTONE_TORCH, + SADDLE, + SHULKER_BOX, + SIGN, + SIGN_POST, + SMITHING_TABLE, + SMOKER, + SPRUCE_BOAT, + SPRUCE_BUTTON, + SPRUCE_DOOR, + SPRUCE_FENCE_GATE, + STONECUTTER, + STONE_BUTTON, + STORAGE_MINECART, + TNT_MINECART, + TNT, + TRAP_DOOR, + TRAPPED_CHEST, + WHITE_BED, + WHITE_SHULKER_BOX, + WOOD_BUTTON, + YELLOW_BED, + YELOW_SHULKER_BOX; + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/materials/SwitchMaterial.java b/src/main/java/com/modnmetl/virtualrealty/enums/materials/SwitchMaterial.java new file mode 100644 index 0000000..2e15752 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/materials/SwitchMaterial.java @@ -0,0 +1,30 @@ +package com.modnmetl.virtualrealty.enums.materials; + +public enum SwitchMaterial { + + WOOD_PLATE, + STONE_PLATE, + IRON_PLATE, + GOLD_PLATE, + + STONE_BUTTON, + WOOD_BUTTON, + OAK_BUTTON, + ACACIA_BUTTON, + DARK_OAK_BUTTON, + WARPED_BUTTON, + + TRIPWIRE, + COMPARATOR, + DIODE, + DIODE_BLOCK_OFF, + DIODE_BLOCK_ON, + REDSTONE_COMPARATOR_OFF, + REDSTONE_COMPARATOR_ON, + REPEATER, + POWERED_REPEATER, + UNPOWERED_REPEATER, + REDSTONE_TORCH, + LEVER + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/permissions/ManagementPermission.java b/src/main/java/com/modnmetl/virtualrealty/enums/permissions/ManagementPermission.java new file mode 100644 index 0000000..2267a22 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/permissions/ManagementPermission.java @@ -0,0 +1,37 @@ +package com.modnmetl.virtualrealty.enums.permissions; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.utils.data.ItemBuilder; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.inventory.ItemFlag; + +@Getter +public enum ManagementPermission { + + ADD_MEMBER(0, "Add Members", new ItemBuilder(Material.DIAMOND_AXE).addItemFlag(ItemFlag.HIDE_ATTRIBUTES)), + KICK_MEMBER(1, "Kick Members", new ItemBuilder(Material.STONE_AXE).addItemFlag(ItemFlag.HIDE_ATTRIBUTES)), + PLOT_PERMISSIONS(2, "Plot Management", new ItemBuilder(VirtualRealty.legacyVersion ? Material.getMaterial("BOOK_AND_QUILL") : Material.WRITABLE_BOOK)); + + private final int slot; + private final String name; + private final ItemBuilder item; + + ManagementPermission(int slot, String name, ItemBuilder item) { + this.slot = slot; + this.name = name; + this.item = item; + } + + public static ManagementPermission getPermission(int i) { + for (ManagementPermission value : values()) { + if (value.getSlot() == i) return value; + } + return null; + } + + public String getConfigName() { + return name().replaceAll("_", " "); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/permissions/RegionPermission.java b/src/main/java/com/modnmetl/virtualrealty/enums/permissions/RegionPermission.java new file mode 100644 index 0000000..6742998 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/permissions/RegionPermission.java @@ -0,0 +1,41 @@ +package com.modnmetl.virtualrealty.enums.permissions; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.utils.data.ItemBuilder; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.inventory.ItemFlag; + +@Getter +public enum RegionPermission { + + BREAK(0, "Break Blocks", new ItemBuilder(Material.STONE_PICKAXE).addItemFlag(ItemFlag.HIDE_ATTRIBUTES)), + PLACE(1, "Place Blocks", new ItemBuilder(VirtualRealty.legacyVersion ? Material.GRASS : Material.GRASS_BLOCK)), + CHEST_ACCESS(2, "Chest-Access", new ItemBuilder(Material.CHEST)), + ARMOR_STAND(3, "Armor Stand", new ItemBuilder(Material.ARMOR_STAND)), + ENTITY_DAMAGE(4, "Entity Damage", new ItemBuilder(Material.IRON_SWORD).addItemFlag(ItemFlag.HIDE_ATTRIBUTES)), + SWITCH(5, "Switch", new ItemBuilder(Material.LEVER)), + ITEM_USE(6, "Item Use", new ItemBuilder(Material.FLINT_AND_STEEL)); + + private final int slot; + private final String name; + private final ItemBuilder item; + + RegionPermission(int slot, String name, ItemBuilder item) { + this.slot = slot; + this.name = name; + this.item = item; + } + + public static RegionPermission getPermission(int i) { + for (RegionPermission value : values()) { + if (value.getSlot() == i) return value; + } + return null; + } + + public String getConfigName() { + return name().replaceAll("_", " "); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandExecution.java b/src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandExecution.java new file mode 100644 index 0000000..42d716d --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandExecution.java @@ -0,0 +1,9 @@ +package com.modnmetl.virtualrealty.exceptions; + +public class FailedCommandExecution extends Exception { + + public FailedCommandExecution() { + super(); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/PlotEntranceListener.java similarity index 69% rename from src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java rename to src/main/java/com/modnmetl/virtualrealty/listeners/PlotEntranceListener.java index 0c8f181..cadefd3 100644 --- a/src/main/java/com/modnmetl/virtualrealty/listeners/plot/PlotListener.java +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/PlotEntranceListener.java @@ -1,9 +1,10 @@ -package com.modnmetl.virtualrealty.listeners.plot; +package com.modnmetl.virtualrealty.listeners; -import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.enums.PlotSize; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.objects.PlotMember; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Bukkit; @@ -16,12 +17,13 @@ import java.util.AbstractMap; import java.util.HashMap; +import java.util.Map; -public class PlotListener extends VirtualListener { +public class PlotEntranceListener extends VirtualListener { - public HashMap> enteredPlot = new HashMap<>(); + public HashMap> enteredPlot = new HashMap<>(); - public PlotListener(VirtualRealty plugin) { + public PlotEntranceListener(VirtualRealty plugin) { super(plugin); } @@ -41,29 +43,31 @@ public void onPlotMove(PlayerMoveEvent e) { if (!enteredPlot.containsKey(player)) { enteredPlot.put(player, new AbstractMap.SimpleEntry<>(plot, true)); Plot newPlot = enteredPlot.get(player).getKey(); - if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { - if (newPlot.getOwnedBy() != null && newPlot.getOwnedBy().equals(player.getUniqueId())) { - if (newPlot.getSelectedGameMode() != VirtualRealty.getInstance().getServer().getDefaultGameMode() || newPlot.getSelectedGameMode() != VirtualRealty.getPluginConfiguration().getGameMode()) { - newPlot.setSelectedGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); + if (VirtualRealty.getPluginConfiguration().enablePlotGamemode) { + if (newPlot.hasMembershipAccess(player.getUniqueId())) { + if (newPlot.getOwnedBy() != null && newPlot.getOwnedBy().equals(player.getUniqueId())) { + player.setGameMode(newPlot.getSelectedGameMode()); + } else if (newPlot.getMember(player.getUniqueId()) != null) { + PlotMember plotMember = newPlot.getMember(player.getUniqueId()); + player.setGameMode(plotMember.getSelectedGameMode()); } - player.setGameMode(newPlot.getSelectedGameMode()); - } else if (newPlot.getMembers().contains(player.getUniqueId())) { - player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); } } if (!VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8")) { if (VirtualRealty.getPluginConfiguration().plotSound) { player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, 0.4f, 0.8f); } - } - if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(enterPlotString)); + if (enteredPlot.get(player).getKey().getPlotSize() == PlotSize.AREA) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(VirtualRealty.getMessages().enteredProtectedArea)); + } else { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(enterPlotString)); + } } } else { if (!enteredPlot.get(player).getValue()) { enteredPlot.replace(player, new AbstractMap.SimpleEntry<>(plot, true)); - if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { - player.setGameMode(VirtualRealty.getPluginConfiguration().getGameMode()); + if (VirtualRealty.getPluginConfiguration().enablePlotGamemode) { + player.setGameMode(VirtualRealty.getPluginConfiguration().getDefaultPlotGamemode()); } } } @@ -75,8 +79,8 @@ public void onPlotMove(PlayerMoveEvent e) { if (enteredPlot.get(player).getKey().getOwnedBy() != null) { offlinePlayer = Bukkit.getOfflinePlayer(enteredPlot.get(player).getKey().getOwnedBy()); leavePlotString = VirtualRealty.getMessages().leftOwnedPlot.replaceAll("%owner%", offlinePlayer.getName()).replaceAll("%plot_id%", enteredPlot.get(player).getKey().getID() + ""); - if (VirtualRealty.getPluginConfiguration().enablePlotGameMode) { - if (enteredPlot.get(player).getKey().hasPlotMembership(player)) { + if (VirtualRealty.getPluginConfiguration().enablePlotGamemode) { + if (enteredPlot.get(player).getKey().hasMembershipAccess(player.getUniqueId())) { player.setGameMode(Bukkit.getServer().getDefaultGameMode()); } } @@ -85,7 +89,9 @@ public void onPlotMove(PlayerMoveEvent e) { if (VirtualRealty.getPluginConfiguration().plotSound) { player.playSound(player.getLocation(), Sound.BLOCK_WOODEN_TRAPDOOR_CLOSE, 0.3f, 1f); } - if (!(VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8") || VirtualRealty.getInstance().getServer().getBukkitVersion().startsWith("1.8"))) { + if (enteredPlot.get(player).getKey().getPlotSize() == PlotSize.AREA) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(VirtualRealty.getMessages().leftProtectedArea)); + } else { player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(leavePlotString)); } } diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java deleted file mode 100644 index 79660f9..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/listeners/ProtectionListener.java +++ /dev/null @@ -1,472 +0,0 @@ -package com.modnmetl.virtualrealty.listeners; - -import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.enums.Flag; -import com.modnmetl.virtualrealty.managers.PlotManager; -import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.ProtectionUtil; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.*; -import org.bukkit.event.entity.*; -import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.player.PlayerArmorStandManipulateEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.world.StructureGrowEvent; -import org.bukkit.util.Vector; - -import java.time.LocalDateTime; - -public class ProtectionListener extends VirtualListener { - - public ProtectionListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onBlockInteract(PlayerInteractEvent e) { - Player player = e.getPlayer(); - if (e.getClickedBlock() != null && (e.getAction() == Action.RIGHT_CLICK_BLOCK || (e.getAction() == Action.LEFT_CLICK_BLOCK && (!VirtualRealty.isLegacy && e.getClickedBlock().getType().isInteractable())))) { - Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { - if (!Flag.World.BLOCK_PLACE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - @EventHandler - public void onBlockPlace(BlockPlaceEvent e) { - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlockPlaced().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_PLACE)) { - if (!Flag.World.BLOCK_PLACE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - - @EventHandler - public void onBlockBreak(BlockBreakEvent e) { - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.BLOCK_BREAK)) { - if (!Flag.World.BLOCK_BREAK.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - - @EventHandler - public void onBlockMove(BlockPistonExtendEvent e) { - if (VirtualRealty.isLegacy) { - if (e.getBlocks().isEmpty()) { - Location fromLocation = e.getBlock().getLocation(); - Location toLocation = e.getBlock().getLocation(); - toLocation.add(getDirection(e.getDirection())); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - Plot toUnborderedPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - if (fromPlot != null) { - if (toUnborderedPlot == null) { - e.setCancelled(true); - } - } - } else { - for (Block block : e.getBlocks()) { - Location fromLocation = block.getLocation(); - Location toLocation = block.getLocation(); - toLocation.add(getDirection(e.getDirection())); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - Plot toUnborderedPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } else { - e.setCancelled(true); - } - } - if (fromPlot != null) { - if (toUnborderedPlot == null) { - e.setCancelled(true); - } - } - } - } - } else { - if (e.getBlocks().isEmpty()) { - Location fromLocation = e.getBlock().getLocation(); - Location toLocation = e.getBlock().getLocation(); - toLocation.add(e.getDirection().getDirection()); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - Plot toUnborderedPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - if (fromPlot != null) { - if (toUnborderedPlot == null) { - e.setCancelled(true); - } - } - } else { - for (Block block : e.getBlocks()) { - Location fromLocation = block.getLocation(); - Location toLocation = block.getLocation(); - toLocation.add(e.getDirection().getDirection()); - Plot fromPlot = PlotManager.getBorderedPlot(fromLocation); - Plot toPlot = PlotManager.getBorderedPlot(toLocation); - Plot toUnborderedPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } else { - e.setCancelled(true); - } - } - if (fromPlot != null) { - if (toUnborderedPlot == null) { - e.setCancelled(true); - } - } - } - } - } - } - - public Vector getDirection(BlockFace blockFace) { - Vector direction = new Vector(blockFace.getModX(), blockFace.getModY(), blockFace.getModZ()); - if (blockFace.getModX() != 0 || blockFace.getModY() != 0 || blockFace.getModZ() != 0) { - direction.normalize(); - } - - return direction; - } - - @EventHandler - public void onIgniteEvent(BlockIgniteEvent e) { - Player player = e.getPlayer(); - if (player != null) { - if (e.getIgnitingBlock() != null) { - Plot plot = PlotManager.getBorderedPlot(e.getIgnitingBlock().getLocation()); - if (plot != null) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - return; - } - e.setCancelled(!plot.hasPermissionToPlot(player)); - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.IGNITE)) { - if (!Flag.World.IGNITE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - } - - @EventHandler - public void onEntityExplode(ExplosionPrimeEvent e) { - Plot plot = PlotManager.getBorderedPlot(e.getEntity().getLocation()); - if (plot != null) { - e.setCancelled(true); - } else { - if (!Flag.World.EXPLOSION_PRIME.isAllowed()) { - e.setCancelled(true); - } - } - } - -// @EventHandler -// public void onPlotEnter(PlayerMoveEvent e) { -// Player player = e.getPlayer(); -// Plot plot = PlotManager.getPlot(e.getTo()); -// if (plot != null && e.getPlayer().isInsideVehicle()) { -// if (!plot.hasPermissionToPlot(player)) { -// e.getPlayer().getVehicle().eject(); -// player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantRideOnPlot); -// } -// } -// } - - @EventHandler - public void onTreeGrow(StructureGrowEvent e) { - for (BlockState block : e.getBlocks()) { - Location fromLocation = e.getLocation(); - Location toLocation = block.getLocation(); - Plot fromPlot = PlotManager.getPlot(fromLocation); - Plot toPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } - } - - @EventHandler - public void onDragonEggMove(BlockFromToEvent e) { - Material block = e.getBlock().getType(); - if (block == Material.DRAGON_EGG || block == Material.LAVA || block == Material.WATER) { - Location fromLocation = e.getBlock().getLocation(); - Location toLocation = e.getToBlock().getLocation(); - Plot fromPlot = PlotManager.getPlot(fromLocation); - Plot toPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } - } - - @EventHandler - public void onProjectileLaunch(ProjectileLaunchEvent e) { - Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); - if (plot != null) { - if (e.getEntity().getShooter() != null && e.getEntity().getShooter() instanceof Player) { - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId()))) { - Player player = (Player) e.getEntity().getShooter(); - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.getEntity().remove(); - } - } else { - e.getEntity().remove(); - } - } - } - } - } - - @EventHandler - public void onProjectileHit(ProjectileHitEvent e) { - Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); - if (plot != null) { - if (e.getEntity().getShooter() != null && e.getEntity().getShooter() instanceof Player) { - if (!(plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId()))) { - Player player = (Player) e.getEntity().getShooter(); - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.getEntity().remove(); - } - } else { - e.getEntity().remove(); - } - } - } - } - } - - @EventHandler - public void onFireSpread(BlockSpreadEvent e) { - Location fromLocation = e.getSource().getLocation(); - Location toLocation = e.getBlock().getLocation(); - Plot fromPlot = PlotManager.getPlot(fromLocation); - Plot toPlot = PlotManager.getPlot(toLocation); - if (toPlot != null) { - if (fromPlot == null) { - e.setCancelled(true); - } else if (fromPlot.getID() != toPlot.getID()) { - e.setCancelled(true); - } - } - } - - @EventHandler - public void onArmorStandChange(PlayerArmorStandManipulateEvent e) { - Plot plot = PlotManager.getPlot(e.getPlayer().getLocation()); - Player player = e.getPlayer(); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ARMOR_STAND_MANIPULATION)) { - if (!Flag.World.ARMOR_STAND_MANIPULATION.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - - @EventHandler - public void onItemFrameDamage(HangingBreakByEntityEvent e) { - if (e.getRemover() instanceof Player) { - Player player = (Player) e.getRemover(); - Plot plot = PlotManager.getPlot(player.getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_DESTROY)) { - if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - @EventHandler - public void onItemFrameRotate(PlayerInteractEntityEvent e) { - if (e.getRightClicked().getType().equals(EntityType.ITEM_FRAME)) { - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(player.getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ITEM_FRAME_ROTATE)) { - if (!Flag.World.ITEM_FRAME_ROTATE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - - @EventHandler - public void onEntityDamage(EntityDamageByEntityEvent e) { - if (e.getDamager() instanceof Player) { - Player player = (Player) e.getDamager(); - Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); - if (plot != null) { - if (plot.hasPermissionToPlot(player)) { - if (plot.isOwnershipExpired()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); - } - } else { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { - if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - - @EventHandler - public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { - if (e.getDamager() instanceof Projectile) { - if (((Projectile) e.getDamager()).getShooter() instanceof Player) { - Player player = ((Player) ((Projectile) e.getDamager()).getShooter()); - Plot plot = PlotManager.getBorderedPlot(e.getDamager().getLocation()); - if (plot != null) { - if (!plot.hasPermissionToPlot(player)) { - e.getDamager().remove(); - e.setCancelled(true); - } - } else { - if (!ProtectionUtil.hasPermissionToWorld(player, Flag.World.ENTITY_DAMAGE)) { - if (!Flag.World.ENTITY_DAMAGE.isAllowed()) { - e.setCancelled(true); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); - } - } - } - } - } - } - -} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java index 4e2ee5d..8a90af1 100644 --- a/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/VirtualListener.java @@ -9,9 +9,6 @@ public class VirtualListener implements Listener { public VirtualListener(VirtualRealty plugin) { this.plugin = plugin; - } - - public void registerEvents() { this.plugin.getServer().getPluginManager().registerEvents(this, this.plugin); } diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/player/PlayerActionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/player/PlayerActionListener.java new file mode 100644 index 0000000..fff76ca --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/player/PlayerActionListener.java @@ -0,0 +1,30 @@ +package com.modnmetl.virtualrealty.listeners.player; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerJoinEvent; + +public class PlayerActionListener extends VirtualListener { + + public PlayerActionListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent e) { + Player player = e.getPlayer(); + if (!player.isOp()) return; + if (VirtualRealty.upToDate) return; + player.sendMessage(VirtualRealty.PREFIX + "§7A new version of VirtualRealty plugin is available. §a[" + VirtualRealty.latestVersion + "]"); + TextComponent textComponent = new TextComponent(VirtualRealty.PREFIX + "§aDownload the new version of the plugin here!"); + textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent("§f§oClick here to download the update!")})); + textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/virtual-realty.95599/")); + player.spigot().sendMessage(textComponent); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java deleted file mode 100644 index 9c19010..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/listeners/plot/BorderListener.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.modnmetl.virtualrealty.listeners.plot; - -import com.modnmetl.virtualrealty.enums.Permission; -import com.modnmetl.virtualrealty.listeners.VirtualListener; -import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.managers.PlotManager; -import com.modnmetl.virtualrealty.objects.Plot; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -public class BorderListener extends VirtualListener { - - public BorderListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onBorderBreak(BlockBreakEvent e) { - Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); - if (plot != null) { - if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { - if (plot.getBorderBlocks().contains(e.getBlock())) { - e.setCancelled(true); - e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - - @EventHandler - public void onBorderPlace(BlockPlaceEvent e) { - Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); - if (plot != null) { - if (!e.getPlayer().hasPermission(Permission.BORDER_BUILD.getPermission())) { - if (plot.getBorderBlocks().contains(e.getBlock())) { - e.setCancelled(true); - e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - -} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/protection/BorderProtectionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/BorderProtectionListener.java new file mode 100644 index 0000000..811d533 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/BorderProtectionListener.java @@ -0,0 +1,39 @@ +package com.modnmetl.virtualrealty.listeners.protection; + +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; + +public class BorderProtectionListener extends VirtualListener { + + public BorderProtectionListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler + public void onBorderBreak(BlockBreakEvent e) { + Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); + if (plot == null) return; + if (e.getPlayer().isOp()) return; + if (plot.getBorderBlocks().contains(e.getBlock())) { + e.setCancelled(true); + e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + + @EventHandler + public void onBorderPlace(BlockPlaceEvent e) { + Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); + if (plot == null) return; + if (e.getPlayer().isOp()) return; + if (plot.getBorderBlocks().contains(e.getBlock())) { + e.setCancelled(true); + e.getPlayer().sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/protection/PlotProtectionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/PlotProtectionListener.java new file mode 100644 index 0000000..fb0fa1a --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/PlotProtectionListener.java @@ -0,0 +1,609 @@ +package com.modnmetl.virtualrealty.listeners.protection; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.materials.InteractMaterial; +import com.modnmetl.virtualrealty.enums.permissions.RegionPermission; +import com.modnmetl.virtualrealty.enums.materials.SwitchMaterial; +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.objects.PlotMember; +import de.tr7zw.nbtinjector.javassist.expr.Instanceof; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.block.data.type.Switch; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.*; +import org.bukkit.event.hanging.HangingBreakByEntityEvent; +import org.bukkit.event.player.*; +import org.bukkit.event.vehicle.VehicleDestroyEvent; +import org.bukkit.event.world.StructureGrowEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; + +public class PlotProtectionListener extends VirtualListener { + + public static final LinkedList INTERACTABLE = new LinkedList<>(); + public static final LinkedList SWITCHABLE = new LinkedList<>(); + + static { + for (InteractMaterial value : InteractMaterial.values()) { + Material material = Material.getMaterial(value.toString()); + if (Objects.nonNull(material)) { + INTERACTABLE.add(material); + } + } + for (SwitchMaterial value : SwitchMaterial.values()) { + Material material = Material.getMaterial(value.toString()); + if (Objects.nonNull(material)) { + SWITCHABLE.add(material); + } + } + } + + public PlotProtectionListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockInteract(PlayerInteractEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + if (e.getClickedBlock() == null) return; + if (e.getClickedBlock().getType() == Material.CHEST) return; + if (!(e.getAction() == Action.PHYSICAL || e.getAction() == Action.RIGHT_CLICK_BLOCK)) return; + if (player.isSneaking() && e.isBlockInHand()) return; + if (!(INTERACTABLE.contains(e.getClickedBlock().getType()) || SWITCHABLE.contains(e.getClickedBlock().getType()))) return; + if (!VirtualRealty.legacyVersion) { + if (e.getHand() == EquipmentSlot.OFF_HAND) return; + if (!e.getClickedBlock().getType().isInteractable()) return; + } + Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if ((!VirtualRealty.legacyVersion && e.getClickedBlock().getBlockData() instanceof Switch) || SWITCHABLE.contains(e.getClickedBlock().getType())) { + if (!plotMember.hasPermission(RegionPermission.SWITCH)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + return; + } + if (INTERACTABLE.contains(e.getClickedBlock().getType())) { + if (!plotMember.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } else { + if ((!VirtualRealty.legacyVersion && e.getClickedBlock().getBlockData() instanceof Switch) || SWITCHABLE.contains(e.getClickedBlock().getType())) { + if (!plot.hasPermission(RegionPermission.SWITCH)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + return; + } + if (INTERACTABLE.contains(e.getClickedBlock().getType())) { + if (!plot.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onChestEvent(PlayerInteractEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + if (e.getClickedBlock() == null) return; + if (e.getClickedBlock().getType() != Material.CHEST) return; + if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (player.isSneaking() && e.isBlockInHand()) return; + Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.CHEST_ACCESS)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!plot.hasPermission(RegionPermission.CHEST_ACCESS)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onLiquidPlace(PlayerBucketEmptyEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getBorderedPlot(e.getBlockClicked().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!plot.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onVehicleDestroy(VehicleDestroyEvent e) { + if (e.isCancelled()) return; + if (!(e.getAttacker() instanceof Player)) return; + Player player = (Player) e.getAttacker(); + Plot plot = PlotManager.getBorderedPlot(e.getVehicle().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } else { + if (!plot.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onLiquidTake(PlayerBucketFillEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getBorderedPlot(e.getBlockClicked().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!plot.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockPlace(BlockPlaceEvent e) { + Player player = e.getPlayer(); + Plot plot = PlotManager.getBorderedPlot(e.getBlockPlaced().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.PLACE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } else { + if (!plot.hasPermission(RegionPermission.PLACE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockBreak(BlockBreakEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.BREAK)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } else { + if (!plot.hasPermission(RegionPermission.BREAK)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onPistonRetract(BlockPistonRetractEvent e) { + if (e.isCancelled()) return; + Block piston = e.getBlock(); + Plot fromPlot = PlotManager.getPlot(piston.getLocation()); + e.getBlocks().forEach(block -> { + Location toLocation = block.getLocation(); + Plot toPlot = PlotManager.getPlot(toLocation); + Plot toBorderedPlot = PlotManager.getBorderedPlot(toLocation); + if (fromPlot != null) { + if (toPlot == null) { + e.setCancelled(true); + } + } else { + if (toBorderedPlot != null) { + e.setCancelled(true); + } + } + }); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockMove(BlockPistonExtendEvent e) { + if (e.isCancelled()) return; + for (Block block : e.getBlocks()) { + Location blockLocation = block.getLocation(); + Plot plot = PlotManager.getPlot(blockLocation); + Plot borderedPlot = PlotManager.getBorderedPlot(blockLocation); + if (borderedPlot != null) { + if (plot == null) { + e.setCancelled(true); + } else if (plot.getID() != borderedPlot.getID()) { + e.setCancelled(true); + } + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onIgniteEvent(BlockIgniteEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + if (player == null) return; + if (e.getIgnitingBlock() == null) return; + Plot plot = PlotManager.getBorderedPlot(e.getIgnitingBlock().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!plot.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + + @EventHandler + public void onBlockIgnite(BlockIgniteEvent e){ + if (e.isCancelled()) return; + if (e.getCause() != BlockIgniteEvent.IgniteCause.SPREAD) return; + Plot fromPlot = PlotManager.getPlot(e.getBlock().getLocation()); + Plot toPlot = PlotManager.getPlot(e.getIgnitingBlock().getLocation()); + if (toPlot != null && fromPlot == null) { + e.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onTreeGrow(StructureGrowEvent e) { + if (e.isCancelled()) return; + for (BlockState block : new ArrayList<>(e.getBlocks())) { + Location saplingLocation = e.getLocation(); + Location blockLocation = block.getLocation(); + Plot fromPlot = PlotManager.getPlot(saplingLocation); + Plot toPlot = PlotManager.getPlot(blockLocation); + if (fromPlot != null) { + if (toPlot != null) { + if (fromPlot.getID() != toPlot.getID()) { + e.getBlocks().remove(block); + } + } else { + e.getBlocks().remove(block); + } + } else if (toPlot != null) { + e.getBlocks().remove(block); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onDragonEggMove(BlockFromToEvent e) { + if (e.isCancelled()) return; + Material block = e.getBlock().getType(); + if (block == Material.DRAGON_EGG || block == Material.LAVA || block == Material.WATER) { + Location fromLocation = e.getBlock().getLocation(); + Location toLocation = e.getToBlock().getLocation(); + Plot fromPlot = PlotManager.getPlot(fromLocation); + Plot toPlot = PlotManager.getPlot(toLocation); + if (toPlot != null) { + if (fromPlot == null) { + e.setCancelled(true); + } else if (fromPlot.getID() != toPlot.getID()) { + e.setCancelled(true); + } + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onProjectileLaunch(ProjectileLaunchEvent e) { + if (e.isCancelled()) return; + if (e.getEntity().getShooter() == null) return; + if (!(e.getEntity().getShooter() instanceof Player)) return; + Player shooter = ((Player) e.getEntity().getShooter()); + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot == null) return; + if (shooter.isOp()) return; + if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId())) + return; + if (plot.hasMembershipAccess(shooter.getUniqueId())) return; + e.getEntity().remove(); + } + + @EventHandler(priority = EventPriority.LOW) + public void onProjectileHit(ProjectileHitEvent e) { + if (e.getEntity().getShooter() == null) return; + if (!(e.getEntity().getShooter() instanceof Player)) return; + Player shooter = ((Player) e.getEntity().getShooter()); + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot == null) return; + if (shooter.isOp()) return; + if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId())) + return; + if (plot.hasMembershipAccess(shooter.getUniqueId())) return; + e.getEntity().remove(); + } + + @EventHandler(priority = EventPriority.LOW) + public void onArmorStandChange(PlayerArmorStandManipulateEvent e) { + if (e.isCancelled()) return; + Plot plot = PlotManager.getPlot(e.getPlayer().getLocation()); + Player player = e.getPlayer(); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.ARMOR_STAND)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!plot.hasPermission(RegionPermission.ARMOR_STAND)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onItemFrameDamage(HangingBreakByEntityEvent e) { + if (e.isCancelled()) return; + if (!(e.getRemover() instanceof Player)) return; + Player player = (Player) e.getRemover(); + Plot plot = PlotManager.getPlot(player.getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } else { + if (!plot.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onItemFrameRotate(PlayerInteractEntityEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(player.getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } else { + if (!plot.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } + + + @EventHandler(priority = EventPriority.LOW) + public void onEntityDamage(EntityDamageByEntityEvent e) { + if (e.isCancelled()) return; + if (!(e.getDamager() instanceof Player)) return; + Player player = (Player) e.getDamager(); + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } else { + if (!plot.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityExplode(EntityExplodeEvent e) { + for (Block block : new ArrayList<>(e.blockList())) { + Plot plot = PlotManager.getBorderedPlot(block.getLocation()); + if (plot != null) + e.blockList().remove(block); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockExplode(BlockExplodeEvent e) { + for (Block block : new ArrayList<>(e.blockList())) { + Plot plot = PlotManager.getBorderedPlot(block.getLocation()); + if (plot != null) + e.blockList().remove(block); + } + } + + @EventHandler + public void onFireSpread(BlockSpreadEvent e) { + Plot plot = PlotManager.getBorderedPlot(e.getNewState().getLocation()); + if (plot != null) + e.setCancelled(true); + } + + @EventHandler + public void onFireBurn(BlockBurnEvent e) { + if (!VirtualRealty.legacyVersion) { + Plot fromPlot = PlotManager.getPlot(e.getIgnitingBlock().getLocation()); + Plot toPlot = PlotManager.getPlot(e.getBlock().getLocation()); + if (toPlot == null) return; + if (fromPlot != null) { + if (toPlot.getID() != fromPlot.getID()) { + e.setCancelled(true); + } + } else { + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { + if (e.isCancelled()) return; + if (!((e.getDamager() instanceof Projectile) && ((Projectile) e.getDamager()).getShooter() instanceof Player)) + return; + Player player = ((Player) ((Projectile) e.getDamager()).getShooter()); + Plot plot = PlotManager.getBorderedPlot(e.getDamager().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (plot.hasMembershipAccess(player.getUniqueId())) { + PlotMember plotMember = plot.getMember(player.getUniqueId()); + if (plot.isOwnershipExpired()) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); + return; + } + if (plotMember == null) return; + if (!plotMember.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } else { + if (!plot.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/protection/WorldProtectionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/WorldProtectionListener.java new file mode 100644 index 0000000..e0bc6a5 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/WorldProtectionListener.java @@ -0,0 +1,207 @@ +package com.modnmetl.virtualrealty.listeners.protection; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.permissions.RegionPermission; +import com.modnmetl.virtualrealty.listeners.VirtualListener; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.WorldUtil; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.type.Switch; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.hanging.HangingBreakByEntityEvent; +import org.bukkit.event.player.PlayerArmorStandManipulateEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; + +public class WorldProtectionListener extends VirtualListener { + + public WorldProtectionListener(VirtualRealty plugin) { + super(plugin); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onBlockInteract(PlayerInteractEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + if (e.getClickedBlock() == null) return; + if (e.getClickedBlock().getType() == Material.CHEST) return; + if (!(e.getAction() == Action.PHYSICAL || e.getAction() == Action.RIGHT_CLICK_BLOCK)) return; + if (player.isSneaking() && e.isBlockInHand()) return; + if (!(PlotProtectionListener.INTERACTABLE.contains(e.getClickedBlock().getType()) || PlotProtectionListener.SWITCHABLE.contains(e.getClickedBlock().getType()))) + return; + if (!VirtualRealty.legacyVersion) { + if (e.getHand() == EquipmentSlot.OFF_HAND) return; + if (!e.getClickedBlock().getType().isInteractable()) return; + } + Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); + if (plot != null) return; + if (player.isOp()) return; + try { + if ((!VirtualRealty.legacyVersion && e.getClickedBlock().getBlockData() instanceof Switch) || PlotProtectionListener.SWITCHABLE.contains(e.getClickedBlock().getType())) { + Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader", false, VirtualRealty.getCustomClassLoader()); + if (!WorldUtil.hasPermission(RegionPermission.SWITCH)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + return; + } + if (PlotProtectionListener.INTERACTABLE.contains(e.getClickedBlock().getType())) { + Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader", false, VirtualRealty.getCustomClassLoader()); + if (!WorldUtil.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + } catch (Exception ignored) { + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onChestClick(PlayerInteractEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + if (e.getClickedBlock() == null) return; + if (e.getClickedBlock().getType() != Material.CHEST) return; + if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (player.isSneaking() && e.isBlockInHand()) return; + Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); + if (plot != null) return; + if (player.isOp()) return; + if (!WorldUtil.hasPermission(RegionPermission.CHEST_ACCESS)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockPlace(BlockPlaceEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlockPlaced().getLocation()); + if (plot != null) return; + if (player.isOp()) return; + if (!WorldUtil.hasPermission(RegionPermission.PLACE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockBreak(BlockBreakEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); + if (plot != null) return; + if (player.isOp()) return; + if (!WorldUtil.hasPermission(RegionPermission.BREAK)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); + } + } + + + public Vector getDirection(BlockFace blockFace) { + Vector direction = new Vector(blockFace.getModX(), blockFace.getModY(), blockFace.getModZ()); + if (blockFace.getModX() != 0 || blockFace.getModY() != 0 || blockFace.getModZ() != 0) { + direction.normalize(); + } + return direction; + } + + @EventHandler(priority = EventPriority.LOW) + public void onIgniteEvent(BlockIgniteEvent e) { + if (e.isCancelled()) return; + Player player = e.getPlayer(); + if (player == null) return; + if (e.getIgnitingBlock() == null) return; + Plot plot = PlotManager.getBorderedPlot(e.getIgnitingBlock().getLocation()); + if (plot != null) return; + if (player.isOp()) return; + if (!WorldUtil.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onArmorStandChange(PlayerArmorStandManipulateEvent e) { + if (e.isCancelled()) return; + Plot plot = PlotManager.getPlot(e.getPlayer().getLocation()); + Player player = e.getPlayer(); + if (plot != null) return; + if (player.isOp()) return; + if (!WorldUtil.hasPermission(RegionPermission.ARMOR_STAND)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onItemFrameDamage(HangingBreakByEntityEvent e) { + if (e.isCancelled()) return; + if (!(e.getRemover() instanceof Player)) return; + Player player = (Player) e.getRemover(); + Plot plot = PlotManager.getPlot(player.getLocation()); + if (plot != null) return; + if (player.isOp()) return; + if (!WorldUtil.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onItemFrameRotate(PlayerInteractEntityEvent e) { + if (e.isCancelled()) return; + if (!e.getRightClicked().getType().equals(EntityType.ITEM_FRAME)) return; + Player player = e.getPlayer(); + Plot plot = PlotManager.getPlot(player.getLocation()); + if (plot != null) return; + if (player.isOp()) return; + if (!WorldUtil.hasPermission(RegionPermission.ITEM_USE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); + } + } + + + @EventHandler(priority = EventPriority.LOW) + public void onEntityDamage(EntityDamageByEntityEvent e) { + if (e.isCancelled()) return; + if (!(e.getDamager() instanceof Player)) return; + Player player = (Player) e.getDamager(); + Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (!WorldUtil.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { + if (e.isCancelled()) return; + if (!((e.getDamager() instanceof Projectile) && ((Projectile) e.getDamager()).getShooter() instanceof Player)) + return; + Player player = ((Player) ((Projectile) e.getDamager()).getShooter()); + Plot plot = PlotManager.getBorderedPlot(e.getDamager().getLocation()); + if (plot == null) return; + if (player.isOp()) return; + if (!WorldUtil.hasPermission(RegionPermission.ENTITY_DAMAGE)) { + e.setCancelled(true); + player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java deleted file mode 100644 index 2f2501b..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/listeners/world/WorldListener.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.modnmetl.virtualrealty.listeners.world; - -import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.enums.Permission; -import com.modnmetl.virtualrealty.listeners.VirtualListener; -import com.modnmetl.virtualrealty.managers.PlotManager; -import com.modnmetl.virtualrealty.objects.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -public class WorldListener extends VirtualListener { - - public WorldListener(VirtualRealty plugin) { - super(plugin); - } - - @EventHandler - public void onBlockBreak(BlockBreakEvent e) { - if (e.isCancelled()) return; - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); - if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { - if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { - if (plot == null) { - e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - - @EventHandler - public void onBlockPlace(BlockPlaceEvent e) { - if (e.isCancelled()) return; - Player player = e.getPlayer(); - Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); - if (!VirtualRealty.getPluginConfiguration().allowOutPlotBuild) { - if (!player.hasPermission(Permission.WORLD_BUILD.getPermission())) { - if (plot == null) { - e.setCancelled(!VirtualRealty.getPluginConfiguration().allowOutPlotBuild); - player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); - } - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java b/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java index 3e88546..4994e95 100644 --- a/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java +++ b/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java @@ -1,13 +1,14 @@ package com.modnmetl.virtualrealty.managers; -import com.modnmetl.virtualrealty.enums.HighlightType; +import com.modnmetl.virtualrealty.enums.dynmap.HighlightType; import com.modnmetl.virtualrealty.enums.PlotSize; import com.modnmetl.virtualrealty.objects.math.BlockVector2; import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.objects.Cuboid; +import com.modnmetl.virtualrealty.objects.region.Cuboid; import com.modnmetl.virtualrealty.objects.Plot; import com.modnmetl.virtualrealty.objects.math.BlockVector3; -import com.modnmetl.virtualrealty.sql.SQL; +import com.modnmetl.virtualrealty.sql.Database; +import lombok.Getter; import org.bukkit.Location; import org.bukkit.Material; import org.dynmap.markers.AreaMarker; @@ -20,16 +21,17 @@ public class PlotManager { - private static final String markerString = "

Plot #%s

Owned By: Available"; - private static final String markerOwnedString = "

Plot #%s

Owned By: %s
Owned Until: %s"; + private static final String MARKER_STRING = "

Plot #%s

Owned By: Available"; + private static final String MARKER_OWNED_STRING = "

Plot #%s

Owned By: %s
Owned Until: %s"; public static Set areaMarkers = new HashSet<>(); - public static Set plots = new LinkedHashSet<>(); + @Getter + private static Set plots = new LinkedHashSet<>(); public static void loadPlots() { plots.clear(); try { - ResultSet rs = SQL.getStatement().executeQuery("SELECT * FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "`"); + ResultSet rs = Database.getInstance().getStatement().executeQuery("SELECT * FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "`"); while (rs.next()) { plots.add(new Plot(rs)); } @@ -38,17 +40,12 @@ public static void loadPlots() { } } - public static Plot createPlot(Location creationLocation, PlotSize plotSize) { - Plot plot = new Plot(creationLocation, plotSize.getFloorMaterial(), plotSize.getBorderMaterial(), plotSize); - plots.add(plot); - plot.insert(); - return plot; - } - - public static Plot createPlot(Location creationLocation, int length, int width, int height) { - Plot plot = new Plot(creationLocation, Material.matchMaterial(VirtualRealty.isLegacy ? "GRASS" : "GRASS_BLOCK"), Material.matchMaterial(VirtualRealty.isLegacy ? "STEP" : "STONE_BRICK_SLAB"), length, width, height); + public static Plot createPlot(Location creationLocation, PlotSize plotSize, int length, int height, int width, boolean natural) { + Plot plot = new Plot(creationLocation, Material.matchMaterial(VirtualRealty.legacyVersion ? "GRASS" : "GRASS_BLOCK"), Material.matchMaterial(VirtualRealty.legacyVersion ? "STEP" : "STONE_BRICK_SLAB"), plotSize, length, width, height, natural); plots.add(plot); + long time = System.currentTimeMillis(); plot.insert(); + VirtualRealty.debug("Plot database insertion time: " + (System.currentTimeMillis() - time) + " ms"); return plot; } @@ -61,18 +58,38 @@ public static Plot getPlot(int ID) { return null; } + public static HashMap getPlots(UUID owner) { + HashMap plotHashMap = new HashMap<>(); + for (Plot plot : plots) { + if(plot.getOwnedBy() != null && plot.getOwnedBy().equals(owner)) { + plotHashMap.put(plot.getID(), plot); + } + } + return plotHashMap; + } + + public static HashMap getAccessPlots(UUID player) { + HashMap plotHashMap = new HashMap<>(); + for (Plot plot : plots) { + if (plot.getMember(player) != null || (plot.getOwnedBy() != null && plot.getPlotOwner().getUniqueId() == player)) { + plotHashMap.put(plot.getID(), plot); + } + } + return plotHashMap; + } + public static int getPlotMinID() { - return plots.isEmpty() ? null : plots.stream().findFirst().get().getID(); + return plots.isEmpty() ? 0 : plots.stream().findFirst().get().getID(); } public static int getPlotMaxID() { - Plot[] plotArray = PlotManager.plots.toArray(new Plot[PlotManager.plots.size()]); + Plot[] plotArray = PlotManager.plots.toArray(new Plot[0]); Plot lastPlot = plotArray[plotArray.length - 1]; return lastPlot.getID(); } public static List getPlayerPlots(UUID owner) { - List playerPlots = new ArrayList<>(); + LinkedList playerPlots = new LinkedList<>(); for (Plot plot : plots) { if (plot.getOwnedBy() != null) { if (plot.getOwnedBy().equals(owner)) { @@ -94,6 +111,10 @@ public static Plot getPlot(Location location) { return null; } + public static void removePlotFromList(Plot plot) { + plots.remove(plot); + } + public static boolean isLocationInPlot(Location location, Plot plot) { BlockVector3 newVector = BlockVector3.at(location.getBlockX(), location.getBlockY(), location.getBlockZ()); Cuboid region = new Cuboid(plot.getBottomLeftCorner(), plot.getTopRightCorner(), location.getWorld()); @@ -159,17 +180,12 @@ public static void resetPlotMarker(Plot plot) { AreaMarker marker = getAreaMarker("virtualrealty.plots." + plot.getID()); if (marker == null) { marker = VirtualRealty.markerset.createAreaMarker("virtualrealty.plots." + plot.getID(), - - plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true, - - plot.getCreatedWorld(), new double[]{plot.getXMin(), plot.getXMax()}, new double[]{plot.getZMin(), plot.getZMax()}, true); - + plot.getOwnedBy() == null ? String.format(MARKER_STRING, plot.getID()) : String.format(MARKER_OWNED_STRING, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true, + plot.getCreatedWorldString(), new double[]{plot.getXMin(), plot.getXMax()}, new double[]{plot.getZMin(), plot.getZMax()}, true); areaMarkers.add(marker); } else { marker.setLabel( - - plot.getOwnedBy() == null ? String.format(markerString, plot.getID()) : String.format(markerOwnedString, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true); - + plot.getOwnedBy() == null ? String.format(MARKER_STRING, plot.getID()) : String.format(MARKER_OWNED_STRING, plot.getID(), ownedBy, dateTimeFormatter.format(localDateTime)), true); } marker.setFillStyle(opacity, color); marker.setLineStyle(2, 0.8, 0x474747); diff --git a/src/main/java/com/modnmetl/virtualrealty/managers/PlotMemberManager.java b/src/main/java/com/modnmetl/virtualrealty/managers/PlotMemberManager.java new file mode 100644 index 0000000..71c6d19 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/managers/PlotMemberManager.java @@ -0,0 +1,23 @@ +package com.modnmetl.virtualrealty.managers; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.objects.PlotMember; +import com.modnmetl.virtualrealty.sql.Database; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class PlotMemberManager { + + public static void loadMembers() { + try { + ResultSet rs = Database.getInstance().getStatement().executeQuery("SELECT * FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotMembersTableName + "`"); + while (rs.next()) { + new PlotMember(rs); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java b/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java index 96f0949..3bf0d40 100644 --- a/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java +++ b/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java @@ -1,164 +1,185 @@ package com.modnmetl.virtualrealty.objects; +import com.modnmetl.virtualrealty.configs.PluginConfiguration; import com.modnmetl.virtualrealty.enums.Direction; -import com.modnmetl.virtualrealty.enums.Permission; +import com.modnmetl.virtualrealty.enums.permissions.RegionPermission; import com.modnmetl.virtualrealty.enums.PlotSize; import com.modnmetl.virtualrealty.managers.PlotManager; -import com.modnmetl.virtualrealty.sql.SQL; -import com.modnmetl.virtualrealty.utils.SchematicUtil; +import com.modnmetl.virtualrealty.objects.region.Cuboid; +import com.modnmetl.virtualrealty.sql.Database; +import com.modnmetl.virtualrealty.utils.EnumUtils; +import com.modnmetl.virtualrealty.utils.data.OldSchematicUtil; +import com.modnmetl.virtualrealty.utils.data.SchematicUtil; import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.objects.math.BlockVector3; -import org.apache.commons.io.FileUtils; +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; import org.bukkit.*; import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; -import java.time.Instant; -import java.time.LocalDateTime; +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; import java.util.*; +@Getter +@Setter public class Plot { + public static final LocalDateTime MAX_DATE = LocalDateTime.of(2999, 12, 31, 0, 0); + public static final DateTimeFormatter PLOT_DATE_FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); + public static final DateTimeFormatter SHORT_PLOT_DATE_FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + private int ID; private UUID ownedBy; - private Set members; + public final LinkedList members; + public final Set nonMemberPermissions; private String assignedBy; private LocalDateTime ownedUntilDate; private PlotSize plotSize; - private int length; - private int width; - private int height; - private Material floorMaterial; - private byte floorData; - private Material borderMaterial; - private byte borderData; - private Location createdLocation; - private Direction createdDirection; - private BlockVector3 bottomLeftCorner; - private BlockVector3 topRightCorner; - private BlockVector3 borderBottomLeftCorner; - private BlockVector3 borderTopRightCorner; + private final int length, width, height; + private Material floorMaterial, borderMaterial; + private byte floorData, borderData; + private final Location createdLocation; + private final Direction createdDirection; + private BlockVector3 bottomLeftCorner, topRightCorner, borderBottomLeftCorner, borderTopRightCorner; private GameMode selectedGameMode; - private String createdWorld; + private final String createdWorld; private Instant modified; + private LocalDateTime createdAt; - @Override - public String toString() { - return "{ ID: " + ID + ", ownedBy: " + ownedBy + "}"; - } - - public Plot(Location location, Material floorMaterial, Material borderMaterial, PlotSize plotSize) { - this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; + public Plot(Location location, Material floorMaterial, Material borderMaterial, PlotSize plotSize, int length, int width, int height, boolean natural) { + this.ID = PlotManager.getPlots().isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; this.ownedBy = null; - this.members = new HashSet<>(); + this.members = new LinkedList<>(); + this.nonMemberPermissions = new HashSet<>(VirtualRealty.getPermissions().getDefaultNonMemberPlotPerms()); this.assignedBy = null; - this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); + this.ownedUntilDate = MAX_DATE; this.floorMaterial = floorMaterial; this.floorData = 0; this.borderMaterial = borderMaterial; this.borderData = 0; - this.plotSize = plotSize; - this.length = plotSize.getLength(); - this.width = plotSize.getWidth(); - this.height = plotSize.getHeight(); this.createdLocation = location; this.createdDirection = Direction.byYaw(location.getYaw()); - this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); + this.selectedGameMode = VirtualRealty.getPluginConfiguration().getDefaultPlotGamemode(); this.createdWorld = location.getWorld().getName(); this.modified = Instant.now(); - initialize(); - initializeCorners(); - if (VirtualRealty.markerset != null) { - PlotManager.resetPlotMarker(this); - } - } - - public Plot(Location location, Material floorMaterial, Material borderMaterial, int length, int width, int height) { - this.ID = PlotManager.plots.isEmpty() ? 10000 : PlotManager.getPlotMaxID() + 1; - this.ownedBy = null; - this.members = new HashSet<>(); - this.assignedBy = null; - this.ownedUntilDate = LocalDateTime.of(2999, 12, 31, 0, 0); - this.floorMaterial = floorMaterial; - this.floorData = 0; - this.borderMaterial = borderMaterial; - this.borderData = 0; - this.plotSize = PlotSize.CUSTOM; + this.createdAt = LocalDateTime.now(); + this.plotSize = plotSize; this.length = length; this.width = width; this.height = height; - this.createdLocation = location; - this.createdDirection = Direction.byYaw(location.getYaw()); - this.selectedGameMode = VirtualRealty.getPluginConfiguration().getGameMode(); - this.createdWorld = location.getWorld().getName(); - this.modified = Instant.now(); - initialize(); - initializeCorners(); + initialize(natural); if (VirtualRealty.markerset != null) { PlotManager.resetPlotMarker(this); } } - + @SneakyThrows public Plot(ResultSet rs) { - try { - this.ID = rs.getInt("ID"); - this.ownedBy = rs.getString("ownedBy").isEmpty() ? null : UUID.fromString(rs.getString("ownedBy")); - this.members = new HashSet<>(); - String membersString = rs.getString("members"); - if (membersString != null && !membersString.isEmpty()) { - String[] membersArray = membersString.substring(0, membersString.length() - 1).split(";"); - for (String s : membersArray) { - members.add(UUID.fromString(s)); - } + this.ID = rs.getInt("ID"); + this.ownedBy = rs.getString("ownedBy").isEmpty() ? null : UUID.fromString(rs.getString("ownedBy")); + this.members = new LinkedList<>(); + Set plotPermissions = new HashSet<>(); + if (!rs.getString("nonMemberPermissions").isEmpty()) { + for (String s : rs.getString("nonMemberPermissions").split("¦")) { + plotPermissions.add(RegionPermission.valueOf(s.toUpperCase())); } - this.assignedBy = rs.getString("assignedBy").equalsIgnoreCase("null") ? null : rs.getString("assignedBy"); + } + this.nonMemberPermissions = plotPermissions; + this.assignedBy = rs.getString("assignedBy").equalsIgnoreCase("null") ? null : rs.getString("assignedBy"); + DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral(' ').append(DateTimeFormatter.ISO_LOCAL_TIME).toFormatter(); + if (VirtualRealty.getPluginConfiguration().dataModel == PluginConfiguration.DataModel.SQLITE) { + this.ownedUntilDate = LocalDateTime.parse(rs.getString("ownedUntilDate"), dateTimeFormatter); + if (rs.getString("created") != null) + this.createdAt = LocalDateTime.parse(rs.getString("created"), dateTimeFormatter); + } else { this.ownedUntilDate = rs.getTimestamp("ownedUntilDate").toLocalDateTime(); - this.floorMaterial = Material.getMaterial(rs.getString("floorMaterial").split(":")[0]); - this.floorData = rs.getString("floorMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("floorMaterial").split(":")[1]); - if (rs.getString("borderMaterial") != null) { - this.borderMaterial = Material.getMaterial(rs.getString("borderMaterial").split(":")[0]); - this.borderData = rs.getString("borderMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("borderMaterial").split(":")[1]); - } - this.plotSize = PlotSize.valueOf(rs.getString("plotSize")); - this.length = rs.getInt("length"); - this.width = rs.getInt("width"); - this.height = rs.getInt("height"); - ArrayList location = new ArrayList<>(Arrays.asList(rs.getString("createdLocation").subSequence(0, rs.getString("createdLocation").length() - 1).toString().split(";"))); - Location createLocation = new Location(Bukkit.getWorld(location.get(0)), Double.parseDouble(location.get(1)), Double.parseDouble(location.get(2)), Double.parseDouble(location.get(3)), Float.parseFloat(location.get(4)), Float.parseFloat(location.get(5))); - this.createdLocation = rs.getString("createdLocation").isEmpty() ? null : createLocation; - this.createdDirection = Direction.byYaw(createdLocation.getYaw()); - this.selectedGameMode = GameMode.CREATIVE; - this.createdWorld = location.get(0); - if (floorMaterial == null) { - floorMaterial = plotSize.getFloorMaterial(); - floorData = plotSize.getFloorData(); - } - if (borderMaterial == null) { - borderMaterial = plotSize.getBorderMaterial(); - borderData = plotSize.getBorderData(); + if (rs.getTimestamp("created") != null) + this.createdAt = rs.getTimestamp("created").toLocalDateTime(); + } + this.floorMaterial = Material.getMaterial(rs.getString("floorMaterial").split(":")[0]); + this.floorData = rs.getString("floorMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("floorMaterial").split(":")[1]); + if (rs.getString("borderMaterial") != null) { + this.borderMaterial = Material.getMaterial(rs.getString("borderMaterial").split(":")[0]); + this.borderData = rs.getString("borderMaterial").split(":").length == 1 ? 0 : Byte.parseByte(rs.getString("borderMaterial").split(":")[1]); + } + this.plotSize = PlotSize.valueOf(rs.getString("plotSize")); + this.length = rs.getInt("length"); + this.width = rs.getInt("width"); + this.height = rs.getInt("height"); + ArrayList location = new ArrayList<>(Arrays.asList(rs.getString("createdLocation").subSequence(0, rs.getString("createdLocation").length() - 1).toString().split(";"))); + Location createLocation = new Location(Bukkit.getWorld(location.get(0)), Double.parseDouble(location.get(1)), Double.parseDouble(location.get(2)), Double.parseDouble(location.get(3)), Float.parseFloat(location.get(4)), Float.parseFloat(location.get(5))); + this.createdLocation = rs.getString("createdLocation").isEmpty() ? null : createLocation; + this.createdDirection = Direction.byYaw(createdLocation.getYaw()); + if (!rs.getString("selectedGameMode").isEmpty() && EnumUtils.isValidEnum(GameMode.class, rs.getString("selectedGameMode"))) { + this.selectedGameMode = GameMode.valueOf(rs.getString("selectedGameMode")); + } else { + this.selectedGameMode = VirtualRealty.getPluginConfiguration().getDefaultPlotGamemode(); + } + this.createdWorld = location.get(0); + if (floorMaterial == null) { + floorMaterial = plotSize.getFloorMaterial(); + floorData = plotSize.getFloorData(); + } + if (borderMaterial == null) { + borderMaterial = plotSize.getBorderMaterial(); + borderData = plotSize.getBorderData(); + } + prepareCorners(); + } + + public boolean hasMembershipAccess(UUID uuid) { + PlotMember member = getMember(uuid); + if (member != null || (ownedBy != null && getPlotOwner().getUniqueId() == uuid)) return true; + return false; + } + + public void togglePermission(RegionPermission plotPermission) { + modified(); + if (nonMemberPermissions.contains(plotPermission)) { + nonMemberPermissions.remove(plotPermission); + } else { + nonMemberPermissions.add(plotPermission); + } + } + + public boolean hasPermission(RegionPermission plotPermission) { + return nonMemberPermissions.contains(plotPermission); + } + + public void addPermission(RegionPermission plotPermission) { + nonMemberPermissions.add(plotPermission); + } + + public void removePermission(RegionPermission plotPermission) { + nonMemberPermissions.remove(plotPermission); + } + + public PlotMember getMember(UUID uuid) { + for (PlotMember member : members) { + if (member.getUuid().equals(uuid)) { + return member; } - initializeCorners(); - } catch (SQLException e) { - e.printStackTrace(); } + return null; } - public boolean hasPermissionToPlot(Player player) { - if (player.hasPermission(Permission.PLOT_BUILD.getPermission())) return true; - if (members.contains(player.getUniqueId())) return true; - return ownedBy != null && ownedBy.equals(player.getUniqueId()); + public void addMember(UUID uuid) { + PlotMember plotMember = new PlotMember(uuid, this); + members.add(plotMember); + plotMember.insert(); } - public boolean hasPlotMembership(Player player) { - if (members.contains(player.getUniqueId())) return true; - return ownedBy != null && ownedBy.equals(player.getUniqueId()); + public void removeMember(PlotMember plotMember) { + members.remove(plotMember); + plotMember.delete(); } public boolean isOwnershipExpired() { @@ -181,135 +202,62 @@ public int getZMax() { return Math.max(this.getBorderBottomLeftCorner().getBlockZ(), this.borderTopRightCorner.getBlockZ()); } - public int getID() { - return ID; - } - - public void setID(int ID) { - this.ID = ID; - } - - public UUID getOwnedBy() { - return ownedBy; - } - public void setOwnedBy(UUID ownedBy) { + modified(); this.ownedBy = ownedBy; - members.remove(ownedBy); + PlotMember plotMember = getMember(ownedBy); + if (plotMember != null) { + removeMember(plotMember); + } updateMarker(); - modified(); - } - - public String getAssignedBy() { - return assignedBy; - } - - public void setAssignedBy(String assignedBy) { - this.assignedBy = assignedBy; - modified(); - } - - public LocalDateTime getOwnedUntilDate() { - return ownedUntilDate; } public void setOwnedUntilDate(LocalDateTime ownedUntilDate) { + modified(); this.ownedUntilDate = ownedUntilDate; updateMarker(); - modified(); - } - - public PlotSize getPlotSize() { - return plotSize; - } - - public void setPlotSize(PlotSize plotSize) { - this.plotSize = plotSize; - } - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public Material getFloorMaterial() { - return floorMaterial; } public void setFloorMaterial(Material floorMaterial, byte data) { + modified(); this.floorMaterial = floorMaterial; this.floorData = data; initializeFloor(); - modified(); } - public Location getCreatedLocation() { - return createdLocation; + private void initializeFloor() { + for (Block floorBlock : getFloorBlocks()) { + floorBlock.setType(this.floorMaterial); + if (VirtualRealty.legacyVersion) { + try { + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(floorBlock, this.floorData); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } + } } public void setBorderMaterial(Material borderMaterial, byte data) { - this.borderMaterial = borderMaterial; - this.borderData = data; modified(); - } - - public Material getBorderMaterial() { - return borderMaterial; - } - - public void setCreatedLocation(Location createdLocation) { - this.createdLocation = createdLocation; - } - - public BlockVector3 getBottomLeftCorner() { - return bottomLeftCorner; - } - - public void setBottomLeftCorner(BlockVector3 bottomLeftCorner) { - this.bottomLeftCorner = bottomLeftCorner; - } - - public BlockVector3 getTopRightCorner() { - return topRightCorner; - } - - public void setTopRightCorner(BlockVector3 topRightCorner) { - this.topRightCorner = topRightCorner; - } - - public BlockVector3 getBorderBottomLeftCorner() { - return borderBottomLeftCorner; - } - - public void setBorderBottomLeftCorner(BlockVector3 borderBottomLeftCorner) { - this.borderBottomLeftCorner = borderBottomLeftCorner; - } - - public BlockVector3 getBorderTopRightCorner() { - return borderTopRightCorner; - } - - public void setBorderTopRightCorner(BlockVector3 borderTopRightCorner) { - this.borderTopRightCorner = borderTopRightCorner; + this.borderMaterial = borderMaterial; + this. borderData = data; + for (Block borderBlock : getBorderBlocks()) { + if (VirtualRealty.legacyVersion) { + borderBlock.setType(borderMaterial); + try { + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(borderBlock, data); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } else { + borderBlock.setType(borderMaterial); + } + } } public BlockVector3 getBorderedCenter() { @@ -320,11 +268,11 @@ public BlockVector3 getCenter() { return new Cuboid(bottomLeftCorner, topRightCorner, createdLocation.getWorld()).getCenterVector(); } - public GameMode getSelectedGameMode() { - return selectedGameMode; + public org.bukkit.World getCreatedWorld() { + return Bukkit.getWorld(createdWorld); } - public String getCreatedWorld() { + public String getCreatedWorldString() { return createdWorld; } @@ -332,96 +280,16 @@ public OfflinePlayer getPlotOwner() { return ownedBy == null ? null : Bukkit.getOfflinePlayer(ownedBy); } - public void setSelectedGameMode(GameMode selectedGameMode) { - this.selectedGameMode = selectedGameMode; - } - - public void addMember(UUID uuid) { - members.add(uuid); - modified(); - } - - public void removeMember(UUID uuid) { - members.remove(uuid); - } - - public Set getMembers() { - return members; - } - - public Set getMembersPlayer() { + public Set getPlayerMembers() { Set offlinePlayers = new HashSet<>(); - for (UUID member : members) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(member); + for (PlotMember member : members) { + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(member.getUuid()); offlinePlayers.add(offlinePlayer); } return offlinePlayers; } - private void setFloorBlock(Block floorBlock) { - if (VirtualRealty.isLegacy) { - try { - Method m = Block.class.getDeclaredMethod("setType", Material.class); - m.setAccessible(true); - m.invoke(floorBlock, this.floorMaterial); - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(floorBlock, this.floorData); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - floorBlock.setType(floorMaterial); - } - modified(); - } - - private void initializeFloor() { - Location location = createdLocation; - Direction direction = Direction.byYaw(location.getYaw()); - switch(direction) { - case SOUTH: { - for (int x = location.getBlockX() - width + 1; x < location.getBlockX() + 1; x++) { - for (int z = location.getBlockZ(); z < location.getBlockZ() + length; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - case WEST: { - for (int x = location.getBlockX() - length + 1; x < location.getBlockX() + 1; x++) { - for (int z = location.getBlockZ() - width + 1; z < location.getBlockZ() + 1; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - case NORTH: { - for (int x = location.getBlockX(); x < location.getBlockX() + width; x++) { - for (int z = location.getBlockZ() - length + 1; z < location.getBlockZ() + 1; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - case EAST: { - for (int x = location.getBlockX(); x < location.getBlockX() + length; x++) { - for (int z = location.getBlockZ(); z < location.getBlockZ() + width; z++) { - Block floorBlock = location.getWorld().getBlockAt(x, location.getBlockY(), z); - setFloorBlock(floorBlock); - } - } - break; - } - default: - throw new IllegalStateException("Unexpected value: " + direction); - } - } - - public void initializeCorners() { + public void prepareCorners() { Location location = createdLocation; Direction direction = Direction.byYaw(location.getYaw()); Location location1; @@ -466,8 +334,12 @@ public void initializeCorners() { this.borderTopRightCorner = BlockVector3.at(border2.getBlockX(), border2.getBlockY(), border2.getBlockZ()); } - public void initialize() { - prepareBlocks(createdLocation); + public void initialize(boolean natural) { + long time = System.currentTimeMillis(); + prepareCorners(); + if (plotSize == PlotSize.AREA) return; + prepareBlocks(createdLocation, natural); + VirtualRealty.debug("Plot initialize time: " + (System.currentTimeMillis() - time) + " ms"); } public Set getBorderBlocks() { @@ -568,27 +440,7 @@ public Set getFloorBlocks() { return blocks; } - public void setBorder(Material material, byte data) { - borderMaterial = material; - borderData = data; - for (Block borderBlock : getBorderBlocks()) { - if (VirtualRealty.isLegacy) { - borderBlock.setType(material); - try { - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(borderBlock, data); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - } else { - borderBlock.setType(material); - } - } - modified(); - } - - public void prepareBlocks(Location location) { + public void prepareBlocks(Location location, boolean natural) { Direction direction = Direction.byYaw(location.getYaw()); Location location1; Location location2; @@ -618,13 +470,14 @@ public void prepareBlocks(Location location) { break; } } + if (natural) return; for (Block floorBlock : getFloorBlocks()) { for (int y = location.getBlockY() + height; y > location.getBlockY() - 1; y--) { Block airBlock = location.getWorld().getBlockAt(floorBlock.getX(), y, floorBlock.getZ()); - airBlock.setType(Material.AIR); + airBlock.setType(Material.AIR, false); } floorBlock.setType(floorMaterial); - if (VirtualRealty.isLegacy) { + if (VirtualRealty.legacyVersion) { try { Method m2 = Block.class.getDeclaredMethod("setData", byte.class); m2.setAccessible(true); @@ -672,7 +525,7 @@ public void prepareBlocks(Location location) { for (int z = minZ; z < maxZ; z++) { if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { Block borderBlock = location.getWorld().getBlockAt(x, location.getBlockY() + 1, z); - if (VirtualRealty.isLegacy) { + if (VirtualRealty.legacyVersion) { borderBlock.setType(plotSize.getBorderMaterial()); try { Method m2 = Block.class.getDeclaredMethod("setData", byte.class); @@ -690,107 +543,108 @@ public void prepareBlocks(Location location) { } public void unloadPlot() { - switch (createdDirection) { - case SOUTH: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - width, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); - break; - } - case WEST: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - length, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - width)); - break; - } - case NORTH: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - length)); - break; - } - case EAST: { - SchematicUtil.paste(ID, new Location(createdLocation.getWorld(), - createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1)); - break; + if (SchematicUtil.isOldSerialization(ID)) { + Location location = null; + switch (createdDirection) { + case SOUTH: { + location = new Location(createdLocation.getWorld(), createdLocation.getBlockX() - width, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1); + break; + } + case WEST: { + location = new Location(createdLocation.getWorld(), createdLocation.getBlockX() - length, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - width); + break; + } + case NORTH: { + location = new Location(createdLocation.getWorld(), createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - length); + break; + } + case EAST: { + location = new Location(createdLocation.getWorld(), createdLocation.getBlockX() - 1, createdLocation.getBlockY() - 10, createdLocation.getBlockZ() - 1); + break; + } } + OldSchematicUtil.paste(ID, location); + } else { + long time = System.currentTimeMillis(); + SchematicUtil.paste(ID); + VirtualRealty.debug("Region pasted in: " + (System.currentTimeMillis() - time) + " ms"); } } - public String getMembersString() { - StringBuilder stringBuilder = new StringBuilder(); - for (UUID member : members) { - stringBuilder.append(member.toString()).append(";"); - } - return stringBuilder.toString(); + private void modified() { + modified = Instant.now(); } + @SneakyThrows public void insert() { - StringBuilder builder = new StringBuilder(); - builder.append(this.createdLocation.getWorld().getName() + ";"); - builder.append(this.createdLocation.getX() + ";"); - builder.append(this.createdLocation.getY() + ";"); - builder.append(this.createdLocation.getZ() + ";"); - builder.append(this.createdLocation.getYaw() + ";"); - builder.append(this.createdLocation.getPitch() + ";"); - try { - SQL.getStatement().execute("INSERT INTO `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + - "` (`ID`, `ownedBy`, `members`, `assignedBy`, `ownedUntilDate`," + - " `floorMaterial`, `borderMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`, `created`, `modified`) " + - "VALUES ('" + this.ID + "', '" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "','" + getMembersString() + "', '" + this.assignedBy + "', " + - "'" + Timestamp.valueOf(this.ownedUntilDate) + "', '" + this.floorMaterial + ":" + this.floorData + "', '" + this.borderMaterial + ":" + this.borderData + "'," + - " '" + this.plotSize + "', '" + this.length + "', '" + this.width + "', '" + this.height + "', '" + builder + "', '" + Timestamp.from(Instant.now()) + "', '" + Timestamp.from(Instant.now()) + "')"); - } catch (SQLException e) { - e.printStackTrace(); + String serializedLocation = + this.createdLocation.getWorld().getName() + ";" + + this.createdLocation.getX() + ";" + + this.createdLocation.getY() + ";" + + this.createdLocation.getZ() + ";" + + this.createdLocation.getYaw() + ";" + + this.createdLocation.getPitch() + ";"; + StringBuilder permissions = new StringBuilder(); + for (RegionPermission permission : this.nonMemberPermissions) { + permissions.append(permission.name()).append("¦"); } + Database.getInstance().getStatement().execute("INSERT INTO `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + + "` (`ID`, `ownedBy`, `nonMemberPermissions`, `assignedBy`, `ownedUntilDate`, `floorMaterial`, `borderMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`, `created`, `modified`, `selectedGameMode`) " + + "VALUES ('" + this.ID + "', '" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "', '" + permissions + "', '" + this.assignedBy + "', '" + Timestamp.valueOf(this.ownedUntilDate) + "', '" + + this.floorMaterial + ":" + this.floorData + "', '" + this.borderMaterial + ":" + this.borderData + "', '" + this.plotSize + "', '" + this.length + "', '" + this.width + "', '" + + this.height + "', '" + serializedLocation + "', '" + Timestamp.from(Instant.now()) + "', '" + Timestamp.from(Instant.now()) + "', '" + this.selectedGameMode.name() + + "')"); } + @SneakyThrows public void update() { - try { - SQL.getStatement().execute("UPDATE `" + - VirtualRealty.getPluginConfiguration().mysql.plotsTableName + - "` SET `ownedBy`='" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "'," + - " `members`='" + getMembersString() + "', `assignedBy`='" + this.assignedBy + "'," + - " `ownedUntilDate`='" + Timestamp.valueOf(this.ownedUntilDate) + "'," + - " `floorMaterial`='" + this.floorMaterial + ":" + this.floorData + "'," + - " `borderMaterial`='" + this.borderMaterial + ":" + this.borderData + "'," + - " `plotSize`='" + this.plotSize + "'," + - " `length`='" + this.length + "'," + - " `width`='" + this.width + "'," + - " `height`='" + this.height + "'," + - " `modified`='" + (this.modified != null ? Timestamp.from(this.modified) : Timestamp.from(Instant.now())) + "'" + - " WHERE `ID`='" + this.ID + "'"); - } catch (SQLException e) { - e.printStackTrace(); + StringBuilder permissions = new StringBuilder(); + for (RegionPermission permission : this.nonMemberPermissions) { + permissions.append(permission.name()).append("¦"); } + Database.getInstance().getStatement().execute("UPDATE `" + + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + + "` SET `ownedBy`='" + (this.ownedBy == null ? "" : this.ownedBy.toString()) + "'," + + " `nonMemberPermissions`='" + permissions + "'," + + " `assignedBy`='" + this.assignedBy + "'," + + " `ownedUntilDate`='" + Timestamp.valueOf(this.ownedUntilDate) + "'," + + " `floorMaterial`='" + this.floorMaterial + ":" + this.floorData + "'," + + " `borderMaterial`='" + this.borderMaterial + ":" + this.borderData + "'," + + " `plotSize`='" + this.plotSize + "'," + + " `length`='" + this.length + "'," + + " `width`='" + this.width + "'," + + " `height`='" + this.height + "'," + + " `modified`='" + (this.modified != null ? Timestamp.from(this.modified) : Timestamp.from(Instant.now())) + "'," + + " `selectedGameMode`='" + this.selectedGameMode.name() + "'" + + " WHERE `ID`='" + this.ID + "'"); } public void remove() { this.unloadPlot(); + for (PlotMember member : this.getMembers()) { + removeMember(member); + } PlotManager.removeDynMapMarker(this); try { - SQL.getStatement().execute("DELETE FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` WHERE `ID` = '" + ID + "';"); + Database.getInstance().getStatement().execute("DELETE FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` WHERE `ID` = '" + ID + "';"); } catch (SQLException e) { e.printStackTrace(); } - int id = ID; - File file = new File(VirtualRealty.plotsSchemaFolder, "plot" + id + ".region"); - if (file.exists()) - FileUtils.deleteQuietly(file); - PlotManager.plots.remove(this); + SchematicUtil.deletePlotFile(ID); + PlotManager.removePlotFromList(this); } public Direction getCreatedDirection() { return createdDirection; } - public void setCreatedDirection(Direction createdDirection) { - this.createdDirection = createdDirection; - } - public void updateMarker() { PlotManager.resetPlotMarker(this); } - public void modified() { - this.modified = Instant.now(); + @Override + public String toString() { + return "{ ID: " + ID + ", ownedBy: " + ownedBy + "}"; } } \ No newline at end of file diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/PlotMember.java b/src/main/java/com/modnmetl/virtualrealty/objects/PlotMember.java new file mode 100644 index 0000000..b9a2575 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/PlotMember.java @@ -0,0 +1,140 @@ +package com.modnmetl.virtualrealty.objects; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.permissions.ManagementPermission; +import com.modnmetl.virtualrealty.enums.permissions.RegionPermission; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.sql.Database; +import lombok.Data; +import lombok.Setter; +import lombok.SneakyThrows; +import org.bukkit.GameMode; + +import java.sql.ResultSet; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +@Data +public class PlotMember { + + private final UUID uuid; + private final Plot plot; + private GameMode selectedGameMode; + private final Set permissions; + private final Set managementPermissions; + + public PlotMember(UUID uuid, Plot plot) { + this.uuid = uuid; + this.plot = plot; + this.selectedGameMode = plot.getSelectedGameMode(); + this.permissions = new HashSet<>(VirtualRealty.getPermissions().getDefaultMemberPerms()); + this.managementPermissions = new HashSet<>(); + } + + @SneakyThrows + public PlotMember(ResultSet rs) { + this.uuid = UUID.fromString(rs.getString("uuid")); + Plot plot = PlotManager.getPlot(rs.getInt("plot")); + this.plot = plot; + this.selectedGameMode = GameMode.valueOf(rs.getString("selectedGameMode")); + Set plotPermissions = new HashSet<>(); + if (!rs.getString("permissions").isEmpty()) { + for (String s : rs.getString("permissions").split("¦")) { + plotPermissions.add(RegionPermission.valueOf(s.toUpperCase())); + } + } + this.permissions = plotPermissions; + Set managementPermissions = new HashSet<>(); + if (!rs.getString("managementPermissions").isEmpty()) { + for (String s : rs.getString("managementPermissions").split("¦")) { + managementPermissions.add(ManagementPermission.valueOf(s.toUpperCase())); + } + } + this.managementPermissions = managementPermissions; + if (plot != null) + plot.members.add(this); + } + + public void togglePermission(RegionPermission plotPermission) { + if (permissions.contains(plotPermission)) { + permissions.remove(plotPermission); + } else { + permissions.add(plotPermission); + } + } + + public boolean hasPermission(RegionPermission plotPermission) { + return permissions.contains(plotPermission); + } + + public void addPermission(RegionPermission plotPermission) { + permissions.add(plotPermission); + } + + public void removePermission(RegionPermission plotPermission) { + permissions.remove(plotPermission); + } + + + public void toggleManagementPermission(ManagementPermission managementPermission) { + if (managementPermissions.contains(managementPermission)) { + managementPermissions.remove(managementPermission); + } else { + managementPermissions.add(managementPermission); + } + } + + public boolean hasManagementPermission(ManagementPermission managementPermission) { + return managementPermissions.contains(managementPermission); + } + + public void addManagementPermission(ManagementPermission managementPermission) { + managementPermissions.add(managementPermission); + } + + public void removeManagementPermission(ManagementPermission managementPermission) { + managementPermissions.remove(managementPermission); + } + + + @SneakyThrows + public void insert() { + StringBuilder permissions = new StringBuilder(); + for (RegionPermission permission : this.permissions) { + permissions.append(permission.name()).append("¦"); + } + StringBuilder managementPermissions = new StringBuilder(); + for (ManagementPermission permission : this.managementPermissions) { + managementPermissions.append(permission.name()).append("¦"); + } + Database.getInstance().getStatement().execute("INSERT INTO `" + VirtualRealty.getPluginConfiguration().mysql.plotMembersTableName + + "` (`uuid`, `plot`, `selectedGameMode`, `permissions`, `managementPermissions`) " + + "VALUES ('" + this.uuid.toString() + "', '" + this.plot.getID() + "', '" + this.getSelectedGameMode().name() + "', '" + permissions + "', '" + managementPermissions + + "')"); + } + + @SneakyThrows + public void update() { + StringBuilder permissions = new StringBuilder(); + for (RegionPermission permission : this.permissions) { + permissions.append(permission.name()).append("¦"); + } + StringBuilder managementPermissions = new StringBuilder(); + for (ManagementPermission permission : this.managementPermissions) { + managementPermissions.append(permission.name()).append("¦"); + } + Database.getInstance().getStatement().execute("UPDATE `" + + VirtualRealty.getPluginConfiguration().mysql.plotMembersTableName + + "` SET `permissions`='" + permissions + "'," + + "`managementPermissions`='" + managementPermissions + "'," + + "`selectedGameMode`='" + selectedGameMode.name() + "'" + + " WHERE `uuid`='" + this.uuid.toString() + "' AND `plot`='" + this.plot.getID() + "'"); + } + + @SneakyThrows + public void delete() { + Database.getInstance().getStatement().execute("DELETE FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotMembersTableName + "` WHERE `uuid` = '" + this.uuid + "' AND `plot`=" + plot.getID() + ";"); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java index 8c217a9..d8acf26 100644 --- a/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java +++ b/src/main/java/com/modnmetl/virtualrealty/objects/math/BlockVector3.java @@ -1,6 +1,7 @@ package com.modnmetl.virtualrealty.objects.math; import org.bukkit.Location; +import org.bukkit.World; public class BlockVector3 extends BlockVector2 { @@ -19,10 +20,14 @@ public static BlockVector3 at(int x, int y, int z) { return new BlockVector3(x, y, z); } - public static BlockVector3 locationToVector(Location location) { + public static BlockVector3 toVector(Location location) { return new BlockVector3(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } + public Location toLocation(World world) { + return new Location(world, x, y, z); + } + public int getBlockX() { return x; } @@ -47,6 +52,7 @@ public void setZ(int z) { this.z = z; } + @Override public String toString() { return "(" + x + ", " + y + ", " + z + ")"; diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java b/src/main/java/com/modnmetl/virtualrealty/objects/region/Cuboid.java similarity index 98% rename from src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java rename to src/main/java/com/modnmetl/virtualrealty/objects/region/Cuboid.java index 7c0868b..4aec481 100644 --- a/src/main/java/com/modnmetl/virtualrealty/objects/Cuboid.java +++ b/src/main/java/com/modnmetl/virtualrealty/objects/region/Cuboid.java @@ -1,4 +1,4 @@ -package com.modnmetl.virtualrealty.objects; +package com.modnmetl.virtualrealty.objects.region; import com.modnmetl.virtualrealty.objects.math.BlockVector2; import com.modnmetl.virtualrealty.objects.math.BlockVector3; @@ -8,6 +8,7 @@ import org.bukkit.entity.Player; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import java.util.Random; @@ -61,7 +62,7 @@ public Cuboid(BlockVector3 point1, BlockVector3 point2, World world) { public List blockList() { - ArrayList bL = new ArrayList<>((xMax - xMin) * (yMax - yMin) * (zMax - zMin)); + LinkedList bL = new LinkedList<>(); for(int x = this.xMin; x <= this.xMax; ++x) { for(int y = this.yMin; y <= this.yMax; ++y) { for(int z = this.zMin; z <= this.zMax; ++z) { diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/region/GridStructure.java b/src/main/java/com/modnmetl/virtualrealty/objects/region/GridStructure.java new file mode 100644 index 0000000..d90c789 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/objects/region/GridStructure.java @@ -0,0 +1,208 @@ +package com.modnmetl.virtualrealty.objects.region; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.Direction; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.RegionUtil; +import com.modnmetl.virtualrealty.utils.data.VirtualBlock; +import lombok.Data; +import lombok.SneakyThrows; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.*; + +@Data +public class GridStructure { + + public static final HashMap> ACTIVE_GRIDS = new HashMap<>(); + + private final Player viewer; + private final Location previewLocation; + private int length; + private int height; + private int width; + private int cuboidId; + private final Set changedBlocks; + private final World world; + private boolean displayingBlocks; + private long displayTicks; + + public GridStructure(Player viewer, int length, int height, int width, int cuboidId, World world, long displayTicks, Location previewLocation) { + if (!ACTIVE_GRIDS.containsKey(viewer.getUniqueId())) { + ACTIVE_GRIDS.put(viewer.getUniqueId(), new HashSet<>()); + } + ACTIVE_GRIDS.get(viewer.getUniqueId()).add(cuboidId); + this.viewer = viewer; + this.length = length; + this.height = height; + this.width = width; + this.cuboidId = cuboidId; + this.changedBlocks = new HashSet<>(); + this.world = world; + this.displayTicks = displayTicks; + this.previewLocation = previewLocation; + } + + public static boolean isCuboidGridDisplaying(Player player, int cuboidId) { + return ACTIVE_GRIDS.containsKey(player.getUniqueId()) && ACTIVE_GRIDS.get(player.getUniqueId()).contains(cuboidId); + } + + public void preview() { + preview(null); + } + + public void preview(Location playerPreviewLocation) { + changedBlocks.clear(); + Plot plot = PlotManager.getPlot(cuboidId); + Location location = previewLocation; + LinkedList blocks = new LinkedList<>(); + LinkedList borderBlocks = new LinkedList<>(); + Direction direction = Direction.byYaw(location.getYaw()); + int maxX; + int maxZ; + int minX; + int minZ; + switch(direction) { + case SOUTH: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + getLength() + 1; + minX = location.getBlockX() - getWidth() + 1; + minZ = location.getBlockZ() - 1; + break; + } + case WEST: { + maxX = location.getBlockX() + 1 + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX() - getLength() + 1; + minZ = location.getBlockZ() - getWidth(); + break; + } + case NORTH: { + maxX = location.getBlockX() + getWidth() + 1; + maxZ = location.getBlockZ() + 1 + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - getLength(); + break; + } + case EAST: { + maxX = location.getBlockX() + getLength() + 1; + maxZ = location.getBlockZ() + getWidth() + 1; + minX = location.getBlockX(); + minZ = location.getBlockZ() - 1; + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + for (int x = minX - 1; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + if (x == minX - 1 || z == minZ || x == maxX - 1 || z == maxZ - 1) { + borderBlocks.add(location.getWorld().getBlockAt(x, location.getBlockY(), z)); + } + } + } + Location topRightCorner; + Location bottomLeftCorner; + if (plot != null) { + topRightCorner = plot.getBorderTopRightCorner().toLocation(plot.getCreatedWorld()); + bottomLeftCorner = plot.getBorderBottomLeftCorner().toLocation(plot.getCreatedWorld()); + } else { + switch (direction) { + case SOUTH: { + bottomLeftCorner = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() - 1); + topRightCorner = new Location(location.getWorld(), location.getBlockX() - getWidth(), location.getBlockY() + getHeight(), location.getBlockZ() + getLength()); + break; + } + case WEST: { + bottomLeftCorner = new Location(location.getWorld(), location.getBlockX() + 1, location.getBlockY() - 10, location.getBlockZ() + 1); + topRightCorner = new Location(location.getWorld(), location.getBlockX() - getLength(), location.getBlockY() + getHeight(), location.getBlockZ() - getWidth()); + break; + } + case NORTH: { + bottomLeftCorner = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() - 10, location.getBlockZ() + 1); + topRightCorner = new Location(location.getWorld(), location.getBlockX() + getWidth(), location.getBlockY() + getHeight(), location.getBlockZ() - getLength()); + break; + } + case EAST: { + bottomLeftCorner = new Location(location.getWorld(), location.getBlockX() + getLength(), location.getBlockY() - 10, location.getBlockZ() - 1); + topRightCorner = new Location(location.getWorld(), location.getBlockX() - 1, location.getBlockY() + getHeight(), location.getBlockZ() + getWidth()); + break; + } + default: + throw new IllegalStateException("Unexpected value: " + direction); + } + } + for (Block borderBlock : new LinkedList<>(borderBlocks)) { + // top grid floor + blocks.add(borderBlock.getLocation().add(0, topRightCorner.getBlockY() - borderBlock.getLocation().getBlockY(), 0).getBlock()); + // bottom grid floor + blocks.add(borderBlock.getLocation().subtract(0, borderBlock.getLocation().getBlockY() - bottomLeftCorner.getBlockY(), 0).getBlock()); + Location playerBlockLocation = borderBlock.getLocation(); + if (playerPreviewLocation != null) { + playerBlockLocation.setY(playerPreviewLocation.getY()); + } else { + playerBlockLocation.add(0, 1, 0); + } + // plot player level border + blocks.add(playerBlockLocation.getBlock()); + } + // grid pillars + for (int y = bottomLeftCorner.getBlockY(); y < bottomLeftCorner.getBlockY() + getHeight() + 10; y++) { + blocks.add(new Location(world, minX - 1, y, minZ).getBlock()); + blocks.add(new Location(world, maxX - 1, y, minZ).getBlock()); + blocks.add(new Location(world, minX - 1, y, maxZ - 1).getBlock()); + blocks.add(new Location(world, maxX - 1, y, maxZ - 1).getBlock()); + } + swapBlocks( + blocks, + PlotManager.isColliding(RegionUtil.getRegion(location, Direction.byYaw(location.getYaw()), getLength(), getHeight(), getWidth())) + ); + if (displayTicks == 0) return; + new BukkitRunnable() { + @Override + public void run() { + removeGrid(); + ACTIVE_GRIDS.get(viewer.getUniqueId()).remove(cuboidId); + } + }.runTaskLater(VirtualRealty.getInstance(), displayTicks); + } + + @SneakyThrows + public void removeGrid() { + for (VirtualBlock changedBlock : changedBlocks) { + Block changedBukkitBlock = changedBlock.getBlock(world); + if (VirtualRealty.legacyVersion) { + viewer.sendBlockChange(changedBukkitBlock.getLocation(), changedBukkitBlock.getType(), changedBukkitBlock.getData()); + } else { + viewer.sendBlockChange(changedBukkitBlock.getLocation(), changedBukkitBlock.getBlockData()); + } + } + } + + private void swapBlocks(LinkedList blocks, boolean collidingArea) { + Plot plot = PlotManager.getPlot(previewLocation); + for (Block block : blocks) { + Location blockLocation = block.getLocation(); + VirtualBlock convertedBlock; + if (VirtualRealty.legacyVersion) { + convertedBlock = new VirtualBlock(block.getX(), block.getY(), block.getZ(), block.getType().getId(), block.getData()); + viewer.sendBlockChange(blockLocation, Objects.requireNonNull(Material.matchMaterial("STAINED_GLASS")), ((plot != null && plot.getID() == cuboidId) ? (byte)1 : collidingArea ? (byte)14 : (byte)5)); + } else { + convertedBlock = new VirtualBlock(block.getX(), block.getY(), block.getZ(), block.getBlockData().getAsString()); + BlockData greenBlockData = Material.LIME_STAINED_GLASS.createBlockData(); + BlockData redBlockData = Material.RED_STAINED_GLASS.createBlockData(); + BlockData orangeBlockData = Material.ORANGE_STAINED_GLASS.createBlockData(); + viewer.sendBlockChange(blockLocation, ((plot != null && plot.getID() == cuboidId) ? orangeBlockData : collidingArea ? redBlockData : greenBlockData)); + } + changedBlocks.add(convertedBlock); + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java b/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java index 8c7d23b..8f44d51 100644 --- a/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java +++ b/src/main/java/com/modnmetl/virtualrealty/registry/VirtualPlaceholders.java @@ -98,8 +98,7 @@ public String getVersion(){ */ @Override public String onPlaceholderRequest(Player player, String identifier){ - if(player == null) - return ""; + if(player == null) return ""; Plot plot = PlotManager.getBorderedPlot(player.getLocation()); if (identifier.equals("plot_id")) { diff --git a/src/main/java/com/modnmetl/virtualrealty/sql/Database.java b/src/main/java/com/modnmetl/virtualrealty/sql/Database.java new file mode 100644 index 0000000..ee8caeb --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/sql/Database.java @@ -0,0 +1,117 @@ +package com.modnmetl.virtualrealty.sql; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.configs.PluginConfiguration; +import com.zaxxer.hikari.HikariDataSource; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; +import org.sqlite.SQLiteDataSource; + +import javax.sql.DataSource; +import java.io.File; +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.logging.Level; + +public class Database { + + private static Database instance; + + @Getter + private final PluginConfiguration.DataModel dataModel; + + @Getter + private final DataSource dataSource; + @Getter + private final Connection connection; + @Getter + private final Statement statement; + + public Database(File file) throws SQLException { + dataModel = VirtualRealty.getPluginConfiguration().dataModel; + SQLiteDataSource sqLiteDataSource = new SQLiteDataSource(); + sqLiteDataSource.setUrl("jdbc:sqlite:" + file.getAbsolutePath()); + dataSource = sqLiteDataSource; + connection = dataSource.getConnection(); + statement = connection.createStatement(); + createTables(); + updateTables(); + } + + public Database(String hostname, int port, String username, String password, String database) throws SQLException { + dataModel = VirtualRealty.getPluginConfiguration().dataModel; + dataSource = new HikariDataSource(); + HikariDataSource hikariDataSource = (HikariDataSource) dataSource; + hikariDataSource.setJdbcUrl("jdbc:mysql://" + hostname + ":" + port + "/" + database); + hikariDataSource.setUsername(username); + if (!password.isEmpty()) { + hikariDataSource.setPassword(password); + } + dataSource.setLogWriter(new PrintWriter(System.out)); + connection = dataSource.getConnection(); + statement = connection.createStatement(); + createTables(); + updateTables(); + } + + private void createTables() { + try { + statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `nonMemberPermissions` TEXT NOT NULL, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, `selectedGameMode` TEXT, PRIMARY KEY(`ID`))"); + statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotMembersTableName + "` (`uuid` VARCHAR(36) NOT NULL, `plot` INT(11) NOT NULL, `selectedGameMode` TEXT NOT NULL, `permissions` TEXT NOT NULL, `managementPermissions` TEXT NOT NULL)"); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + private void updateTables() { + if (dataModel == PluginConfiguration.DataModel.MYSQL) { + try { + statement.execute("ALTER TABLE IF EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `borderMaterial` VARCHAR(32) AFTER `floorMaterial`;"); + } catch (SQLException ignored) {} + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` DROP `members`;"); + } catch (SQLException ignored) {} + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `created` DATETIME AFTER `createdLocation`;"); + } catch (SQLException ignored) {} + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `modified` DATETIME AFTER `created`;"); + } catch (SQLException ignored) {} + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `selectedGameMode` TEXT;"); + } catch (SQLException ignored) {} + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `nonMemberPermissions` TEXT NOT NULL AFTER `ownedBy`;"); + } catch (SQLException ignored) {} + } + if (dataModel == PluginConfiguration.DataModel.SQLITE) { + try { + statement.execute("SELECT `nonMemberPermissions` FROM `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "`"); + } catch (SQLException ex) { + try { + statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` RENAME TO `_" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "_old`;"); + createTables(); + statement.execute("INSERT INTO `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID`, `ownedBy`, `nonMemberPermissions`, `assignedBy`, `ownedUntilDate`, `floorMaterial`, `borderMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`, `created`, `modified`, `selectedGameMode`)" + + " SELECT `ID`, `ownedBy`, '" + "" + "', `assignedBy`, `ownedUntilDate`, `floorMaterial`, `borderMaterial`, `plotSize`, `length`, `width`, `height`, `createdLocation`, `created`, `modified`, '" + "" + "'" + + " FROM _" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "_old;"); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + } + + public static Database getInstance() { + return instance; + } + + public static void setInstance(Database database) { + instance = database; + } + +} + diff --git a/src/main/java/com/modnmetl/virtualrealty/sql/SQL.java b/src/main/java/com/modnmetl/virtualrealty/sql/SQL.java deleted file mode 100644 index 17d4854..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/sql/SQL.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.modnmetl.virtualrealty.sql; - -import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.configs.PluginConfiguration; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; - -public class SQL { - - private static Connection connection; - private static Statement statement; - public static final long MYSQL_TIMEOUT_MS = 28800000; - private static long lastQuery = System.currentTimeMillis(); - - public static void connect() { - try { - switch (VirtualRealty.getPluginConfiguration().dataModel) { - case SQLITE: { - Class.forName("org.sqlite.JDBC"); - File dataDir = new File(VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + File.separator + "data"); - if (!dataDir.exists()) { - dataDir.mkdirs(); - } - connection = DriverManager.getConnection("jdbc:sqlite:" + VirtualRealty.getInstance().getDataFolder().getAbsolutePath() + File.separator + "data" + File.separator + "data.db"); - break; - } - case MYSQL: { - Class.forName("com.mysql.jdbc.Driver"); - connection = DriverManager.getConnection("jdbc:mysql://" + VirtualRealty.getPluginConfiguration().mysql.hostname + ":" + VirtualRealty.getPluginConfiguration().mysql.port + "/" + VirtualRealty.getPluginConfiguration().mysql.database + "?useSSL=" + VirtualRealty.getPluginConfiguration().mysql.useSSL + "&autoReconnect=true", VirtualRealty.getPluginConfiguration().mysql.user, VirtualRealty.getPluginConfiguration().mysql.password); - break; - } - } - createStatement(); - } catch (SQLException | ClassNotFoundException ex) { - ex.printStackTrace(); - } - } - - public static void createStatement() { - try { - statement = connection.createStatement(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public static void closeConnection() { - try { - if (statement != null && (VirtualRealty.getPluginConfiguration().dataModel != PluginConfiguration.DataModel.SQLITE && !statement.isClosed())) { - statement.close(); - } - if (connection != null) - connection.close(); - VirtualRealty.debug("Database connection closed"); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public static void createTables() { - try { - statement.execute("CREATE TABLE IF NOT EXISTS `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` (`ID` INT(12) NOT NULL, `ownedBy` VARCHAR(36) NOT NULL, `members` TEXT, `assignedBy` VARCHAR(36) NOT NULL, `ownedUntilDate` DATETIME NOT NULL, `floorMaterial` VARCHAR(32) NOT NULL, `borderMaterial` VARCHAR(32) NOT NULL, `plotSize` VARCHAR(32) NOT NULL, `length` INT(24) NOT NULL, `width` INT(24) NOT NULL, `height` INT(24) NOT NULL, `createdLocation` TEXT(500) NOT NULL, `created` DATETIME, `modified` DATETIME, PRIMARY KEY(`ID`))"); - updateTables(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - public static void updateTables() { - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `borderMaterial` VARCHAR(32) AFTER `floorMaterial`;"); - } catch (SQLException ignored) { - - } - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `members` TEXT AFTER `ownedBy`;"); - } catch (SQLException ignored) { - - } - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `created` DATETIME AFTER `createdLocation`;"); - } catch (SQLException ignored) { - - } - try { - statement.execute("ALTER TABLE `" + VirtualRealty.getPluginConfiguration().mysql.plotsTableName + "` ADD `modified` DATETIME AFTER `created`;"); - } catch (SQLException ignored) { - - } - } - - public static Statement getStatement() { - try { - if (System.currentTimeMillis() - lastQuery > MYSQL_TIMEOUT_MS) { - connection.close(); - statement.close(); - connect(); - } else if(connection.isClosed()) { - connect(); - } - lastQuery = System.currentTimeMillis(); - } catch (SQLException e) { - e.printStackTrace(); - } - return statement; - } - - - public static void setConnection(Connection connection) { - SQL.connection = connection; - } - - public static void setStatement(Statement statement) { - SQL.statement = statement; - } - -} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java b/src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java deleted file mode 100644 index 1e1b393..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/utils/ConfigurationFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.modnmetl.virtualrealty.utils; - -import com.modnmetl.virtualrealty.configs.SizesConfiguration; -import eu.okaeri.configs.ConfigManager; -import eu.okaeri.configs.serdes.commons.SerdesCommons; -import eu.okaeri.configs.validator.okaeri.OkaeriValidator; -import eu.okaeri.configs.yaml.bukkit.YamlBukkitConfigurer; -import com.modnmetl.virtualrealty.configs.MessagesConfiguration; -import com.modnmetl.virtualrealty.configs.PluginConfiguration; - -import java.io.File; - -public class ConfigurationFactory { - - public ConfigurationFactory() { - - } - - public PluginConfiguration createPluginConfiguration(File pluginConfigurationFile) { - return ConfigManager.create(PluginConfiguration.class, (it) -> { - it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); - it.withBindFile(pluginConfigurationFile); - it.saveDefaults(); - it.load(true); - }); - } - - public SizesConfiguration createSizesConfiguration(File sizesConfigurationFile) { - return ConfigManager.create(SizesConfiguration.class, (it) -> { - it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); - it.withBindFile(sizesConfigurationFile); - it.saveDefaults(); - it.load(true); - }); - } - - public MessagesConfiguration createMessagesConfiguration(File messagesConfigurationFile) { - return ConfigManager.create(MessagesConfiguration.class, (it) -> { - it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons()); - it.withBindFile(messagesConfigurationFile); - it.saveDefaults(); - it.load(true); - }); - } - -} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/EnumUtils.java b/src/main/java/com/modnmetl/virtualrealty/utils/EnumUtils.java new file mode 100644 index 0000000..03f2181 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/EnumUtils.java @@ -0,0 +1,18 @@ +package com.modnmetl.virtualrealty.utils; + +public class EnumUtils { + + public static > boolean isValidEnum(Class enumClass, String enumName) { + if (enumName == null) { + return false; + } else { + try { + Enum.valueOf(enumClass, enumName); + return true; + } catch (IllegalArgumentException var3) { + return false; + } + } + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/PermissionUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/PermissionUtil.java new file mode 100644 index 0000000..230ea00 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/PermissionUtil.java @@ -0,0 +1,18 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.VirtualRealty; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; + +public class PermissionUtil { + + public static boolean hasPermission(CommandSender sender, String permission) { + Permission finalPermission = new Permission(permission); + if (!sender.hasPermission(finalPermission)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().insufficientPermissions.replaceAll("%permission%", finalPermission.getName())); + return false; + } + return true; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java deleted file mode 100644 index 84c2450..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/utils/ProtectionUtil.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.modnmetl.virtualrealty.utils; - -import com.modnmetl.virtualrealty.enums.Permission; -import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.enums.Flag; -import com.modnmetl.virtualrealty.managers.PlotManager; -import com.modnmetl.virtualrealty.objects.Plot; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.time.LocalDateTime; - -public class ProtectionUtil { - - public static boolean canBuild(Player player, Location location) { - Plot plot = PlotManager.getBorderedPlot(location); - if (plot != null) { - if (plot.getOwnedBy() != null) { - if (!plot.getOwnedBy().equals(player.getUniqueId())) { - return false; - } else { - if (plot.getOwnedUntilDate().isBefore(LocalDateTime.now())) { - return false; - } - } - } else { - return false; - } - } - return true; - } - - public static boolean hasPermissionToWorld(Player player, Flag.World flag) { - if (player.hasPermission(Permission.WORLD_BUILD.getPermission())) return true; - if (player.hasPermission(VirtualRealty.GLOBAL_PERMISSION.getName() + ".world." + flag.name().toLowerCase())) return true; - if (player.isOp()) return true; - return false; - } - -} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java b/src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java deleted file mode 100644 index 95bd794..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/utils/Reflections.java +++ /dev/null @@ -1,271 +0,0 @@ -package com.modnmetl.virtualrealty.utils; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Entity; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public final class Reflections { - - public static final String SERVER_VERSION = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; - public static final boolean USE_PRE_13_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 13; - public static final boolean USE_PRE_12_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 12; - public static final boolean USE_PRE_9_METHODS = Integer.parseInt(SERVER_VERSION.split("_")[1]) < 9; - - private static final Map> CLASS_CACHE = new HashMap<>(); - private static final Map FIELD_CACHE = new HashMap<>(); - private static final Map> FIELD_ACCESSOR_CACHE = new HashMap<>(); - private static final Map METHOD_CACHE = new HashMap<>(); - private static final Class INVALID_CLASS = InvalidMarker.class; - private static final Method INVALID_METHOD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredMethod("invalidMethodMaker")); - private static final Field INVALID_FIELD = SafeUtil.safeInit(() -> InvalidMarker.class.getDeclaredField("invalidFieldMarker")); - private static final FieldAccessor INVALID_FIELD_ACCESSOR = getField(INVALID_CLASS, Void.class, 0); - - public static Class getClassOmitCache(String className) { - CLASS_CACHE.remove(className); - return getClass(className); - } - - public static Class getClass(String className) { - Class c = CLASS_CACHE.get(className); - - if (c != null) { - return c != INVALID_CLASS ? c : null; - } - - try { - c = Class.forName(className); - CLASS_CACHE.put(className, c); - } - catch (Exception ex) { - System.err.println("Could not retrieve class"); - - CLASS_CACHE.put(className, INVALID_CLASS); - } - return c; - } - - public static Class getNMSClass(String name) { - return getClass("net.minecraft.server." + SERVER_VERSION + "." + name); - } - - public static Class getCraftBukkitClass(String name) { - return getClass("org.bukkit.craftbukkit." + SERVER_VERSION + "." + name); - } - - public static Class getBukkitClass(String name) { - return getClass("org.bukkit." + name); - } - - public static Object getHandle(Entity entity) { - try { - return getMethod(entity.getClass(), "getHandle").invoke(entity); - } - catch (Exception ex) { - System.err.println("Could not get entity handle"); - return null; - } - } - - public static Object getHandle(World world) { - try { - return getMethod(world.getClass(), "getHandle").invoke(world); - } - catch (Exception ex) { - System.err.println("Could not get world handle"); - - return null; - } - } - - private static String constructFieldCacheKey(Class cl, String fieldName) { - return cl.getName() + "." + fieldName; - } - - public static Field getField(Class cl, String fieldName) { - String cacheKey = constructFieldCacheKey(cl, fieldName); - - Field field = FIELD_CACHE.get(cacheKey); - - if (field != null) { - return field != INVALID_FIELD ? field : null; - } - - try { - field = cl.getDeclaredField(fieldName); - FIELD_CACHE.put(cacheKey, field); - } - catch (Exception ex) { - System.err.println("Could not retrieve field"); - - FIELD_CACHE.put(cacheKey, INVALID_FIELD); - } - - return field; - } - - public static FieldAccessor getField(Class target, Class fieldType, int index) { - return getField(target, null, fieldType, index); - } - - @SuppressWarnings("unchecked") - private static FieldAccessor getField(Class target, String name, Class fieldType, int index) { - final String cacheKey = target.getName() + "." + (name != null ? name : "NONE") + "." + fieldType.getName() + "." + index; - - FieldAccessor output = (FieldAccessor) FIELD_ACCESSOR_CACHE.get(cacheKey); - - if (output != null) { - if (output == INVALID_FIELD_ACCESSOR) { - throw new IllegalArgumentException("Cannot find field with type " + fieldType); - } - - return output; - } - - for (final Field field : target.getDeclaredFields()) { - if ((name == null || field.getName().equals(name)) && fieldType.isAssignableFrom(field.getType()) && index-- <= 0) { - field.setAccessible(true); - - output = new FieldAccessor() { - - @Override - public T get(Object target) { - try { - return (T) field.get(target); - } catch (IllegalAccessException e) { - throw new RuntimeException("Cannot access reflection.", e); - } - } - - @Override - public void set(Object target, Object value) { - try { - field.set(target, value); - } catch (IllegalAccessException e) { - throw new RuntimeException("Cannot access reflection.", e); - } - } - - @Override - public boolean hasField(Object target) { - return field.getDeclaringClass().isAssignableFrom(target.getClass()); - } - }; - - break; - } - } - - if (output == null && target.getSuperclass() != null) { - output = getField(target.getSuperclass(), name, fieldType, index); - } - - FIELD_ACCESSOR_CACHE.put(cacheKey, output != null ? output : INVALID_FIELD_ACCESSOR); - - if (output == null) { - throw new IllegalArgumentException("Cannot find field with type " + fieldType); - } - - return output; - } - - public static Field getPrivateField(Class cl, String fieldName) { - String cacheKey = constructFieldCacheKey(cl, fieldName); - - Field c = FIELD_CACHE.get(cacheKey); - if (c != null) { - return c != INVALID_FIELD ? c : null; - } - - try { - c = cl.getDeclaredField(fieldName); - c.setAccessible(true); - FIELD_CACHE.put(cacheKey, c); - } - catch (Exception ex) { - System.err.println("Could not retrieve field"); - - FIELD_CACHE.put(cacheKey, INVALID_FIELD); - } - - return c; - } - - public static Method getMethod(Class cl, String method, Class... args) { - String cacheKey = cl.getName() + "." + method + "." + (args == null ? "NONE" : Arrays.toString(args)); - - Method output = METHOD_CACHE.get(cacheKey); - if (output != null) { - return output != INVALID_METHOD ? output : null; - } - - for (Method m : cl.getMethods()) { - if (m.getName().equals(method) && (args == null || classListEqual(args, m.getParameterTypes()))) { - output = m; - break; - } - } - - METHOD_CACHE.put(cacheKey, output == null ? INVALID_METHOD : output); - return output; - } - - public static Method getMethod(Class cl, String method) { - return getMethod(cl, method, null); - } - - public static Constructor getConstructor(Class clazz, Class... arguments) { - for (Constructor constructor : clazz.getDeclaredConstructors()) { - if (Arrays.equals(constructor.getParameterTypes(), arguments)) { - return constructor; - } - } - - return null; - } - - public static boolean classListEqual(Class[] l1, Class[] l2) { - if (l1.length != l2.length) { - return false; - } - - for (int i = 0; i < l1.length; i++) { - if (l1[i] != l2[i]) { - return false; - } - } - - return true; - } - - public interface ConstructorInvoker { - Object invoke(Object... arguments); - } - - public interface MethodInvoker { - Object invoke(Object target, Object... arguments); - } - - public interface FieldAccessor { - T get(Object target); - - void set(Object target, Object value); - - boolean hasField(Object target); - } - - private static class InvalidMarker { - public Void invalidFieldMarker; - public void invalidMethodMaker() {} - } - - private Reflections() {} - -} - diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/RegionUtil.java similarity index 91% rename from src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java rename to src/main/java/com/modnmetl/virtualrealty/utils/RegionUtil.java index a4cc196..a4bb4d3 100644 --- a/src/main/java/com/modnmetl/virtualrealty/utils/PlotUtil.java +++ b/src/main/java/com/modnmetl/virtualrealty/utils/RegionUtil.java @@ -1,13 +1,13 @@ package com.modnmetl.virtualrealty.utils; import com.modnmetl.virtualrealty.enums.Direction; -import com.modnmetl.virtualrealty.objects.Cuboid; +import com.modnmetl.virtualrealty.objects.region.Cuboid; import com.modnmetl.virtualrealty.objects.math.BlockVector3; import org.bukkit.Location; -public class PlotUtil { +public class RegionUtil { - public static Cuboid getPlotRegion(Location location, Direction direction, int length, int width, int height) { + public static Cuboid getRegion(Location location, Direction direction, int length, int height, int width) { Location location1; Location location2; switch(direction) { diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java deleted file mode 100644 index bfe1722..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/utils/SafeUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.modnmetl.virtualrealty.utils; - -public class SafeUtil { - - private static void reportUnsafe(Throwable th) { - try { - throw new Exception(th.getMessage()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static T safeInit(SafeInitializer initializer) { - try { - return initializer.initialize(); - } catch (Exception e) { - reportUnsafe(e); - return null; - } - } - - @FunctionalInterface - public interface SafeInitializer { - T initialize() throws Exception; - } - -} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java deleted file mode 100644 index 28f0670..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/utils/SchematicUtil.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.modnmetl.virtualrealty.utils; - -import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; -import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.managers.PlotManager; -import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.data.Data; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; - -import java.io.*; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.util.*; - -public class SchematicUtil { - - public static String[] getStructure(Block block, Block block2) { - long time = System.currentTimeMillis(); - int minX = Math.min(block.getX(), block2.getX()); - int minZ = Math.min(block.getZ(), block2.getZ()); - int minY = Math.min(block.getY(), block2.getY()); - int maxX = Math.max(block.getX(), block2.getX()); - int maxZ = Math.max(block.getZ(), block2.getZ()); - int maxY = Math.max(block.getY(), block2.getY()); - List blocks = new ArrayList<>(); - for (int x = minX; x <= maxX; ++x) { - for (int y = minY; y <= maxY; ++y) { - for (int z = minZ; z <= maxZ; ++z) { - Block b = block.getWorld().getBlockAt(x, y, z); - if (b.getType() != Material.AIR) { - if (VirtualRealty.isLegacy) { - blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getType().getId() + ";" + b.getData()); - } else { - blocks.add(x - minX + ";" + (y - minY) + ";" + (z - minZ) + ";" + b.getBlockData().getAsString().substring(10)); - } - } - } - } - } - VirtualRealty.debug("Getted and serialized blocks in: " + (System.currentTimeMillis() - time) + " ms"); - return blocks.toArray(new String[0]); - } - - public static void paste(int plotID, Location l) { - long time = System.currentTimeMillis(); - String[] blocks = load(plotID); - if (blocks == null) return; - Plot plot = PlotManager.getPlot(plotID); - Location location = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderBottomLeftCorner().getBlockX(), plot.getBorderBottomLeftCorner().getBlockY(), plot.getBorderBottomLeftCorner().getBlockZ()); - Location location2 = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderTopRightCorner().getBlockX(), plot.getBorderTopRightCorner().getBlockY(), plot.getBorderTopRightCorner().getBlockZ()); - Block pos1Block = location.getBlock(); - Block pos2Block = location2.getBlock(); - int minX = Math.min(pos1Block.getX(), pos2Block.getX()); - int minZ = Math.min(pos1Block.getZ(), pos2Block.getZ()); - int minY = Math.min(pos1Block.getY(), pos2Block.getY()); - int maxX = Math.max(pos1Block.getX(), pos2Block.getX()); - int maxZ = Math.max(pos1Block.getZ(), pos2Block.getZ()); - int maxY = Math.max(pos1Block.getY(), pos2Block.getY()); - for (int x = minX; x <= maxX; ++x) { - for (int y = minY; y <= maxY; ++y) { - for (int z = minZ; z <= maxZ; ++z) { - Block b = location.getWorld().getBlockAt(x, y, z); - b.setType(Material.AIR); - } - } - } - if (blocks[0].isEmpty()) return; - for (String block : blocks) { - String[] cords = block.split(";"); - int x = Integer.parseInt(cords[0]); - int y = Integer.parseInt(cords[1]); - int z = Integer.parseInt(cords[2]); - Location displaced = l.clone(); - displaced.add(x, y, z); - Block b = displaced.getBlock(); - if (VirtualRealty.isLegacy) { - try { - Method m = Block.class.getDeclaredMethod("setType", Material.class); - m.setAccessible(true); - m.invoke(b, VMaterial.getMaterial(Integer.parseInt(cords[3]))); - Method m2 = Block.class.getDeclaredMethod("setData", byte.class); - m2.setAccessible(true); - m2.invoke(b, (byte) Integer.parseInt(cords[4])); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - BlockData blockData = Bukkit.createBlockData("minecraft:" + cords[3]); - b.setBlockData(blockData); - } - b.getState().update(true); - } - VirtualRealty.debug("Pasted in: " + (System.currentTimeMillis() - time) + " ms"); - } - - public static void save(int plotID, String[] blocks) { - long time = System.currentTimeMillis(); - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); - - StringBuilder stringBuilder = new StringBuilder(); - for (String s : blocks) { - stringBuilder.append(s).append("|"); - } - String plotString = stringBuilder.toString(); - if (plotString.isEmpty()) - plotString = "clear|"; - try { - new Data().compressData(plotString.substring(0, plotString.length() - 1).getBytes(StandardCharsets.UTF_8), f); - } catch (IOException e) { - e.printStackTrace(); - } - VirtualRealty.debug("Saved in: " + (System.currentTimeMillis() - time) + " ms"); - } - - public static String[] load(int plotID) { - long time = System.currentTimeMillis(); - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); - if (f.exists()) { - String loaded = null; - try { - loaded = new String(new Data().decompressData(f)); - } catch (IOException e) { - e.printStackTrace(); - } - if (loaded.equalsIgnoreCase("clear")) return new String[]{""}; - VirtualRealty.debug("Loaded in: " + (System.currentTimeMillis() - time) + " ms"); - return loaded.split("\\|"); - } - return null; - } - - public static List oldLoad(int plotID) { - File f = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".schem"); - List loaded = new ArrayList<>(); - try { - FileInputStream streamIn = new FileInputStream(f); - ObjectInputStream objectinputstream = new ObjectInputStream(streamIn); - loaded = (List)objectinputstream.readObject(); - objectinputstream.close(); - } catch (Exception e) { - e.printStackTrace(); - } - return loaded; - } - -} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/WorldUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/WorldUtil.java new file mode 100644 index 0000000..98a6ca8 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/WorldUtil.java @@ -0,0 +1,34 @@ +package com.modnmetl.virtualrealty.utils; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.enums.permissions.RegionPermission; + +import java.util.List; + +public class WorldUtil { + + public static List getWorldPermissions() { + return VirtualRealty.getPermissions().getWorldProtection(); + } + + public static void togglePermission(RegionPermission plotPermission) { + if (getWorldPermissions().contains(plotPermission)) { + VirtualRealty.getPermissions().worldProtection.remove(plotPermission); + } else { + VirtualRealty.getPermissions().worldProtection.add(plotPermission); + } + } + + public static boolean hasPermission(RegionPermission plotPermission) { + return getWorldPermissions().contains(plotPermission); + } + + public static void addPermission(RegionPermission plotPermission) { + VirtualRealty.getPermissions().worldProtection.add(plotPermission); + } + + public static void removePermission(RegionPermission plotPermission) { + VirtualRealty.getPermissions().worldProtection.remove(plotPermission); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/configuration/ConfigurationFactory.java b/src/main/java/com/modnmetl/virtualrealty/utils/configuration/ConfigurationFactory.java new file mode 100644 index 0000000..b729d8c --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/configuration/ConfigurationFactory.java @@ -0,0 +1,91 @@ +package com.modnmetl.virtualrealty.utils.configuration; + +import com.modnmetl.virtualrealty.configs.PermissionsConfiguration; +import com.modnmetl.virtualrealty.configs.SizesConfiguration; +import eu.okaeri.configs.ConfigManager; +import eu.okaeri.configs.postprocessor.SectionSeparator; +import eu.okaeri.configs.validator.okaeri.OkaeriValidator; +import eu.okaeri.configs.yaml.bukkit.YamlBukkitConfigurer; +import com.modnmetl.virtualrealty.configs.MessagesConfiguration; +import com.modnmetl.virtualrealty.configs.PluginConfiguration; +import eu.okaeri.configs.yaml.bukkit.serdes.SerdesBukkit; +import lombok.NoArgsConstructor; + +import java.io.File; + +@NoArgsConstructor +public class ConfigurationFactory { + + public PluginConfiguration loadPluginConfiguration(File pluginConfigurationFile) { + return ConfigManager.create(PluginConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesBukkit()); + it.withBindFile(pluginConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + + public SizesConfiguration loadSizesConfiguration(File sizesConfigurationFile) { + return ConfigManager.create(SizesConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesBukkit()); + it.withBindFile(sizesConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + + public MessagesConfiguration loadMessagesConfiguration(File messagesConfigurationFile) { + return ConfigManager.create(MessagesConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesBukkit()); + it.withBindFile(messagesConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + + public PermissionsConfiguration loadPermissionsConfiguration(File permissionsConfigurationFile) { + return ConfigManager.create(PermissionsConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesBukkit()); + it.withBindFile(permissionsConfigurationFile); + it.saveDefaults(); + it.load(true); + }); + } + + public PermissionsConfiguration updatePluginConfiguration(File pluginConfigurationFile) { + return ConfigManager.create(PermissionsConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesBukkit()); + it.withBindFile(pluginConfigurationFile); + it.saveDefaults(); + it.update(); + }); + } + + public PermissionsConfiguration updateSizesConfiguration(File sizesConfigurationFile) { + return ConfigManager.create(PermissionsConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesBukkit()); + it.withBindFile(sizesConfigurationFile); + it.saveDefaults(); + it.update(); + }); + } + + public PermissionsConfiguration updateMessagesConfiguration(File messagesConfigurationFile) { + return ConfigManager.create(PermissionsConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesBukkit()); + it.withBindFile(messagesConfigurationFile); + it.saveDefaults(); + it.update(); + }); + } + + public PermissionsConfiguration updatePermissionsConfiguration(File permissionsConfigurationFile) { + return ConfigManager.create(PermissionsConfiguration.class, (it) -> { + it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesBukkit()); + it.withBindFile(permissionsConfigurationFile); + it.saveDefaults(); + it.update(); + }); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java b/src/main/java/com/modnmetl/virtualrealty/utils/data/DataCompressor.java similarity index 92% rename from src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java rename to src/main/java/com/modnmetl/virtualrealty/utils/data/DataCompressor.java index f13a3ef..ec6dae5 100644 --- a/src/main/java/com/modnmetl/virtualrealty/utils/data/Data.java +++ b/src/main/java/com/modnmetl/virtualrealty/utils/data/DataCompressor.java @@ -3,11 +3,12 @@ import java.io.*; import java.util.zip.*; -public class Data { +public class DataCompressor { public void compressData(byte[] data, File file) throws IOException { try (OutputStream outputStream = new FileOutputStream(file)) { Deflater d = new Deflater(); + d.setLevel(4); DeflaterOutputStream dout = new DeflaterOutputStream(outputStream, d); dout.write(data); dout.close(); @@ -17,7 +18,7 @@ public void compressData(byte[] data, File file) throws IOException { public byte[] decompressData(File file) throws IOException { try (InputStream inputStream = new FileInputStream(file)) { InflaterInputStream newInput = new InflaterInputStream(inputStream); - ByteArrayOutputStream bout = new ByteArrayOutputStream(512); + ByteArrayOutputStream bout = new ByteArrayOutputStream(512*2*2*2*2); int b; while ((b = newInput.read()) != -1) { bout.write(b); diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/data/ItemBuilder.java b/src/main/java/com/modnmetl/virtualrealty/utils/data/ItemBuilder.java new file mode 100644 index 0000000..9963359 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/data/ItemBuilder.java @@ -0,0 +1,244 @@ +package com.modnmetl.virtualrealty.utils.data; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.SkullMeta; + +/** + * Easily create itemstacks, without messing your hands. + * Note that if you do use this in one of your projects, leave this notice. + * Please do credit me if you do use this in one of your projects. + * @author NonameSL + */ +public class ItemBuilder { + private ItemStack is; + /** + * Create a new ItemBuilder from scratch. + * @param m The material to create the ItemBuilder with. + */ + public ItemBuilder(Material m){ + this(m, 1); + } + /** + * Create a new ItemBuilder over an existing itemstack. + * @param is The itemstack to create the ItemBuilder over. + */ + public ItemBuilder(ItemStack is){ + this.is=is; + } + /** + * Create a new ItemBuilder from scratch. + * @param m The material of the item. + * @param amount The amount of the item. + */ + public ItemBuilder(Material m, int amount){ + is= new ItemStack(m, amount); + } + /** + * Create a new ItemBuilder from scratch. + * @param m The material of the item. + * @param amount The amount of the item. + * @param durability The durability of the item. + */ + public ItemBuilder(Material m, int amount, byte durability){ + is = new ItemStack(m, amount, durability); + } + /** + * Clone the ItemBuilder into a new one. + * @return The cloned instance. + */ + public ItemBuilder clone(){ + return new ItemBuilder(is); + } + /** + * Change the durability of the item. + * @param dur The durability to set it to. + */ + public ItemBuilder setDurability(short dur){ + is.setDurability(dur); + return this; + } + /** + * Set the displayname of the item. + * @param name The name to change it to. + */ + public ItemBuilder setName(String name){ + ItemMeta im = is.getItemMeta(); + im.setDisplayName(name); + is.setItemMeta(im); + return this; + } + /** + * Add an unsafe enchantment. + * @param ench The enchantment to add. + * @param level The level to put the enchant on. + */ + public ItemBuilder addUnsafeEnchantment(Enchantment ench, int level){ + is.addUnsafeEnchantment(ench, level); + return this; + } + /** + * Remove a certain enchant from the item. + * @param ench The enchantment to remove + */ + public ItemBuilder removeEnchantment(Enchantment ench){ + is.removeEnchantment(ench); + return this; + } + /** + * Set the skull owner for the item. Works on skulls only. + * @param owner The name of the skull's owner. + */ + public ItemBuilder setSkullOwner(String owner){ + try{ + SkullMeta im = (SkullMeta)is.getItemMeta(); + im.setOwner(owner); + is.setItemMeta(im); + }catch(ClassCastException expected){} + return this; + } + /** + * Add an enchant to the item. + * @param ench The enchant to add + * @param level The level + */ + public ItemBuilder addEnchant(Enchantment ench, int level){ + ItemMeta im = is.getItemMeta(); + im.addEnchant(ench, level, true); + is.setItemMeta(im); + return this; + } + /** + * Add multiple enchants at once. + * @param enchantments The enchants to add. + */ + public ItemBuilder addEnchantments(Map enchantments){ + is.addEnchantments(enchantments); + return this; + } + /** + * Sets infinity durability on the item by setting the durability to Short.MAX_VALUE. + */ + public ItemBuilder setInfinityDurability(){ + is.setDurability(Short.MAX_VALUE); + return this; + } + /** + * Re-sets the lore. + * @param lore The lore to set it to. + */ + public ItemBuilder setLore(String... lore){ + ItemMeta im = is.getItemMeta(); + im.setLore(Arrays.asList(lore)); + is.setItemMeta(im); + return this; + } + /** + * Re-sets the lore. + * @param lore The lore to set it to. + */ + public ItemBuilder setLore(List lore) { + ItemMeta im = is.getItemMeta(); + im.setLore(lore); + is.setItemMeta(im); + return this; + } + /** + * Remove a lore line. + */ + public ItemBuilder removeLoreLine(String line){ + ItemMeta im = is.getItemMeta(); + List lore = new ArrayList<>(im.getLore()); + if(!lore.contains(line))return this; + lore.remove(line); + im.setLore(lore); + is.setItemMeta(im); + return this; + } + /** + * Remove a lore line. + * @param index The index of the lore line to remove. + */ + public ItemBuilder removeLoreLine(int index){ + ItemMeta im = is.getItemMeta(); + List lore = new ArrayList<>(im.getLore()); + if(index<0||index>lore.size())return this; + lore.remove(index); + im.setLore(lore); + is.setItemMeta(im); + return this; + } + /** + * Add a lore line. + * @param line The lore line to add. + */ + public ItemBuilder addLoreLine(String line){ + ItemMeta im = is.getItemMeta(); + List lore = new ArrayList<>(); + if(im.hasLore())lore = new ArrayList<>(im.getLore()); + lore.add(line); + im.setLore(lore); + is.setItemMeta(im); + return this; + } + /** + * Add a lore line. + * @param line The lore line to add. + * @param pos The index of where to put it. + */ + public ItemBuilder addLoreLine(String line, int pos){ + ItemMeta im = is.getItemMeta(); + List lore = new ArrayList<>(im.getLore()); + lore.set(pos, line); + im.setLore(lore); + is.setItemMeta(im); + return this; + } + + /** + * Sets the armor color of a leather armor piece. Works only on leather armor pieces. + * @param color The color to set it to. + */ + public ItemBuilder setLeatherArmorColor(Color color){ + try{ + LeatherArmorMeta im = (LeatherArmorMeta)is.getItemMeta(); + im.setColor(color); + is.setItemMeta(im); + }catch(ClassCastException expected){} + return this; + } + + /** + * Retrieves the itemstack from the ItemBuilder. + * @return The itemstack created/modified by the ItemBuilder instance. + */ + public ItemStack toItemStack(){ + return is; + } + + + public ItemBuilder addItemFlag(ItemFlag itemFlag) { + ItemMeta im = is.getItemMeta(); + im.addItemFlags(itemFlag); + is.setItemMeta(im); + return this; + } + + public ItemBuilder addItemFlags(ItemFlag... itemFlags) { + ItemMeta im = is.getItemMeta(); + im.addItemFlags(itemFlags); + is.setItemMeta(im); + return this; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/data/OldSchematicUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/data/OldSchematicUtil.java new file mode 100644 index 0000000..5684567 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/data/OldSchematicUtil.java @@ -0,0 +1,90 @@ +package com.modnmetl.virtualrealty.utils.data; + +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.data.DataCompressor; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; + +import java.io.*; +import java.lang.reflect.Method; + +@Deprecated +public class OldSchematicUtil { + + public static final String OLD_REGION_PREFIX = "plot"; + public static final String OLD_REGION_SUFFIX = ".region"; + + public static void paste(int plotID, Location l) { + long time = System.currentTimeMillis(); + String[] blocks = load(plotID); + if (blocks == null) return; + Plot plot = PlotManager.getPlot(plotID); + Location location = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderBottomLeftCorner().getBlockX(), plot.getBorderBottomLeftCorner().getBlockY(), plot.getBorderBottomLeftCorner().getBlockZ()); + Location location2 = new Location(plot.getCreatedLocation().getWorld(), plot.getBorderTopRightCorner().getBlockX(), plot.getBorderTopRightCorner().getBlockY(), plot.getBorderTopRightCorner().getBlockZ()); + Block pos1Block = location.getBlock(); + Block pos2Block = location2.getBlock(); + int minX = Math.min(pos1Block.getX(), pos2Block.getX()); + int minZ = Math.min(pos1Block.getZ(), pos2Block.getZ()); + int minY = Math.min(pos1Block.getY(), pos2Block.getY()); + int maxX = Math.max(pos1Block.getX(), pos2Block.getX()); + int maxZ = Math.max(pos1Block.getZ(), pos2Block.getZ()); + int maxY = Math.max(pos1Block.getY(), pos2Block.getY()); + for (int x = minX; x <= maxX; x++) { + for (int y = maxY; y > minY; y--) { + for (int z = minZ; z <= maxZ; z++) { + Block b = location.getWorld().getBlockAt(x, y, z); + b.setType(Material.AIR); + } + } + } + if (blocks[0].isEmpty()) return; + for (String block : blocks) { + String[] cords = block.split(";"); + int x = Integer.parseInt(cords[0]); + int y = Integer.parseInt(cords[1]); + int z = Integer.parseInt(cords[2]); + Location displaced = l.clone(); + displaced.add(x, y, z); + Block b = displaced.getBlock(); + if (VirtualRealty.legacyVersion) { + try { + Method m = Block.class.getDeclaredMethod("setType", Material.class); + m.setAccessible(true); + m.invoke(b, VMaterial.getMaterial(Integer.parseInt(cords[3]))); + Method m2 = Block.class.getDeclaredMethod("setData", byte.class); + m2.setAccessible(true); + m2.invoke(b, (byte) Integer.parseInt(cords[4])); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + BlockData blockData = Bukkit.createBlockData("minecraft:" + cords[3]); + b.setBlockData(blockData); + } + b.getState().update(true); + } + VirtualRealty.debug("Pasted in: " + (System.currentTimeMillis() - time) + " ms"); + } + + @SneakyThrows + private static String[] load(int plotID) { + long time = System.currentTimeMillis(); + File region = new File(VirtualRealty.plotsSchemaFolder, OLD_REGION_PREFIX + plotID + OLD_REGION_SUFFIX); + if (region.exists()) { + String loaded = new String(new DataCompressor().decompressData(region)); + if (loaded.equalsIgnoreCase("clear")) return new String[]{""}; + VirtualRealty.debug("Loaded in: " + (System.currentTimeMillis() - time) + " ms"); + return loaded.split("\\|"); + } + return null; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/data/SchematicUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/data/SchematicUtil.java new file mode 100644 index 0000000..0d64ab7 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/data/SchematicUtil.java @@ -0,0 +1,163 @@ +package com.modnmetl.virtualrealty.utils.data; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.managers.PlotManager; +import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.SerializationUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; + +import java.io.*; +import java.lang.reflect.Method; +import java.util.*; + +public class SchematicUtil { + + public static final String LEGACY_REGION_PREFIX = "legacy_plot-"; + public static final String REGION_PREFIX = "plot-"; + public static final String REGION_SUFFIX = ".region"; + + public static LinkedList getStructure(Block block, Block block2) { + long time = System.currentTimeMillis(); + int minX = Math.min(block.getX(), block2.getX()); + int minZ = Math.min(block.getZ(), block2.getZ()); + int minY = Math.min(block.getY(), block2.getY()); + int maxX = Math.max(block.getX(), block2.getX()); + int maxZ = Math.max(block.getZ(), block2.getZ()); + int maxY = Math.max(block.getY(), block2.getY()); + LinkedList blocks = new LinkedList<>(); + for (int x = minX; x <= maxX; x++) { + for (int z = minZ; z <= maxZ; z++) { + if (block.getWorld().getHighestBlockAt(x, z).getLocation().getY() < minY) continue; + for (int y = minY; y <= maxY; ++y) { + Block oldBlock = block.getWorld().getBlockAt(x, y, z); + if (oldBlock.getType() == Material.AIR) continue; + if (VirtualRealty.legacyVersion) { + blocks.add(new VirtualBlock(x, y, z, oldBlock.getType().getId(), oldBlock.getData())); + } else { + blocks.add(new VirtualBlock(x, y, z, oldBlock.getBlockData().getAsString().substring(10))); + } + } + } + } + VirtualRealty.debug("Got " + blocks.size() + " blocks in: " + (System.currentTimeMillis() - time) + " ms"); + return blocks; + } + + public static void paste(int plotID) { + LinkedList blocks = load(plotID); + if (blocks == null) return; + Plot plot = PlotManager.getPlot(plotID); + if (plot == null) return; + long time = System.currentTimeMillis(); + Location location = plot.getBorderBottomLeftCorner().toLocation(plot.getCreatedWorld()); + Location location2 = plot.getBorderTopRightCorner().toLocation(plot.getCreatedWorld()); + Block pos1Block = location.getBlock(); + Block pos2Block = location2.getBlock(); + int minX = Math.min(pos1Block.getX(), pos2Block.getX()); + int minZ = Math.min(pos1Block.getZ(), pos2Block.getZ()); + int minY = Math.min(pos1Block.getY(), pos2Block.getY()); + int maxX = Math.max(pos1Block.getX(), pos2Block.getX()); + int maxZ = Math.max(pos1Block.getZ(), pos2Block.getZ()); + int maxY = Math.max(pos1Block.getY(), pos2Block.getY()); + World world = location.getWorld(); + if (world == null) return; + int i = 0; + for (int x = minX; x <= maxX; x++) { + for (int z = minZ; z <= maxZ; z++) { + for (int y = maxY; y > minY; y--) { + Block block = world.getBlockAt(x, y, z); + if (block.getType() == Material.AIR) continue; + block.setType(Material.AIR); + i++; + } + } + } + VirtualRealty.debug("Pasted " + i + " air blocks in: " + (System.currentTimeMillis() - time) + " ms"); + for (VirtualBlock block : blocks) { + Location blockLocation = new Location(plot.getCreatedWorld(), block.getX(), block.getY(), block.getZ()); + Block oldBlock = blockLocation.getBlock(); + if (VirtualRealty.legacyVersion) { + try { + oldBlock.setType(VMaterial.getMaterial(block.getMaterial())); + Method m = Block.class.getDeclaredMethod("setData", byte.class); + m.setAccessible(true); + m.invoke(oldBlock, block.getData()); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + oldBlock.setBlockData(Bukkit.createBlockData("minecraft:" + block.getBlockData()), false); + } + } + VirtualRealty.debug("Pasted " + blocks.size() + " blocks in: " + (System.currentTimeMillis() - time) + " ms"); + } + + @SneakyThrows + public static void save(int plotID, LinkedList blocks) { + long time = System.currentTimeMillis(); + File f = new File(VirtualRealty.plotsSchemaFolder, (VirtualRealty.legacyVersion ? LEGACY_REGION_PREFIX : REGION_PREFIX) + plotID + REGION_SUFFIX); + long serialization = System.currentTimeMillis(); + byte[] data = SerializationUtils.serialize(blocks); + VirtualRealty.debug("Serialized in: " + (System.currentTimeMillis() - serialization) + " ms"); + long compression = System.currentTimeMillis(); + new DataCompressor().compressData(data, f); + VirtualRealty.debug("Compressed in: " + (System.currentTimeMillis() - compression) + " ms"); + VirtualRealty.debug("Region saved in: " + (System.currentTimeMillis() - time) + " ms"); + } + + @SneakyThrows + public static LinkedList load(int plotID) { + long time = System.currentTimeMillis(); + File region = new File(VirtualRealty.plotsSchemaFolder, REGION_PREFIX + plotID + REGION_SUFFIX); + File legacyRegion = new File(VirtualRealty.plotsSchemaFolder, LEGACY_REGION_PREFIX + plotID + REGION_SUFFIX); + ByteArrayInputStream bais; + ObjectInputStream ois; + if (region.exists()) { + byte[] bytes = new DataCompressor().decompressData(region); + bais = new ByteArrayInputStream(bytes); + ois = new ObjectInputStream(bais); + VirtualRealty.debug("Loaded in: " + (System.currentTimeMillis() - time) + " ms"); + return (LinkedList) ois.readObject(); + } else if (legacyRegion.exists()) { + byte[] bytes = new DataCompressor().decompressData(legacyRegion); + bais = new ByteArrayInputStream(bytes); + ois = new ObjectInputStream(bais); + VirtualRealty.debug("Loaded in: " + (System.currentTimeMillis() - time) + " ms"); + return (LinkedList) ois.readObject(); + } + return null; + } + + public static boolean isPlotFileLegacy(int plotID) throws FileNotFoundException { + File region = new File(VirtualRealty.plotsSchemaFolder, REGION_PREFIX + plotID + REGION_SUFFIX); + File legacyRegion = new File(VirtualRealty.plotsSchemaFolder, LEGACY_REGION_PREFIX + plotID + REGION_SUFFIX); + if (region.exists()) return false; + if (legacyRegion.exists()) return true; + throw new FileNotFoundException(); + } + + public static void deletePlotFile(int id) { + File file = new File(VirtualRealty.plotsSchemaFolder, "plot" + id + ".region"); + if (file.exists()) + FileUtils.deleteQuietly(file); + File file2 = new File(VirtualRealty.plotsSchemaFolder, REGION_PREFIX + id + REGION_SUFFIX); + if (file2.exists()) + FileUtils.deleteQuietly(file2); + File file3 = new File(VirtualRealty.plotsSchemaFolder, LEGACY_REGION_PREFIX + id + REGION_SUFFIX); + if (file3.exists()) + FileUtils.deleteQuietly(file3); + } + + public static boolean isOldSerialization(int plotID) { + File oldRegion = new File(VirtualRealty.plotsSchemaFolder, "plot" + plotID + ".region"); + return oldRegion.exists(); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/data/SkullUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/data/SkullUtil.java new file mode 100644 index 0000000..210971f --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/data/SkullUtil.java @@ -0,0 +1,46 @@ +package com.modnmetl.virtualrealty.utils.data; + +import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import java.lang.reflect.Field; +import java.util.Base64; +import java.util.UUID; + +public class SkullUtil { + + public static ItemStack getSkull(String url) { + ItemStack skull; + if (VirtualRealty.legacyVersion) { + skull = new ItemStack(VMaterial.getMaterial("SKULL_ITEM"), 1, (short) 3); + } else { + skull = new ItemStack(Material.PLAYER_HEAD, 1, (short) 3); + } + if (url == null || url.isEmpty()) + return skull; + SkullMeta skullMeta = (SkullMeta) skull.getItemMeta(); + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + byte[] encodedData = Base64.getEncoder().encode(String.format("{textures:{SKIN:{url:\"%s\"}}}", "http://textures.minecraft.net/texture/" + url).getBytes()); + profile.getProperties().put("textures", new Property("textures", new String(encodedData))); + Field profileField = null; + try { + profileField = skullMeta.getClass().getDeclaredField("profile"); + } catch (NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } + profileField.setAccessible(true); + try { + profileField.set(skullMeta, profile); + } catch (IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); + } + skull.setItemMeta(skullMeta); + return skull; + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/data/VirtualBlock.java b/src/main/java/com/modnmetl/virtualrealty/utils/data/VirtualBlock.java new file mode 100644 index 0000000..782f893 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/data/VirtualBlock.java @@ -0,0 +1,47 @@ +package com.modnmetl.virtualrealty.utils.data; + +import lombok.Data; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.InflaterInputStream; + +@Data +public class VirtualBlock implements Serializable { + + private int x; + private int y; + private int z; + + private int material; + private byte data; + + private String blockData; + + public VirtualBlock(int x, int y, int z, int material, byte data) { + this.x = x; + this.y = y; + this.z = z; + this.material = material; + this.data = data; + } + + public VirtualBlock(int x, int y, int z, String blockData) { + this.x = x; + this.y = y; + this.z = z; + this.blockData = blockData; + } + + public Block getBlock(World world) { + return world.getBlockAt(x,y,z); + } + + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/loader/CustomClassLoader.java b/src/main/java/com/modnmetl/virtualrealty/utils/loader/CustomClassLoader.java new file mode 100644 index 0000000..98f6e71 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/utils/loader/CustomClassLoader.java @@ -0,0 +1,12 @@ +package com.modnmetl.virtualrealty.utils.loader; + +import java.net.URL; +import java.net.URLClassLoader; + +public class CustomClassLoader extends URLClassLoader { + + public CustomClassLoader(URL[] urls, ClassLoader parent) { + super(urls, parent); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java index 159f406..95a2597 100644 --- a/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java +++ b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/Chat.java @@ -24,7 +24,7 @@ public Chat(String text) { public void sendTo(CommandSender sender) { if (sender instanceof Player) { Player player = (Player) sender; - if (VirtualRealty.isLegacy) { + if (VirtualRealty.legacyVersion) { try { Method m = Player.class.getDeclaredMethod("sendMessage", BaseComponent.class); m.setAccessible(true); diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java index feac87d..d39b011 100644 --- a/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java +++ b/src/main/java/com/modnmetl/virtualrealty/utils/multiversion/VMaterial.java @@ -10,7 +10,7 @@ public class VMaterial { public static Material getMaterial(int materialID) throws MaterialMatchException { - if (VirtualRealty.isLegacy) { + if (VirtualRealty.legacyVersion) { try { Method m = Material.class.getDeclaredMethod("getMaterial", int.class); m.setAccessible(true); diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index f7c37b5..1d199d9 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -10,4 +10,5 @@ commands: virtualrealty: aliases: [vrplot, virtualr] plot: - aliases: [p] \ No newline at end of file + aliases: [p] + test: \ No newline at end of file diff --git a/virtualrealty.iml b/virtualrealty.iml index d44b105..2fec24b 100644 --- a/virtualrealty.iml +++ b/virtualrealty.iml @@ -11,8 +11,8 @@ - - + + @@ -22,21 +22,24 @@ - + - - - - - - - + + + + + + + - - + + + + + \ No newline at end of file From e14064d918bd1178422f67074b6fe7bca33f560f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 3 Mar 2022 20:28:20 +0100 Subject: [PATCH 11/23] Update --- .../virtualrealty/enums/dynmap/HighlightType.java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 src/main/java/com/modnmetl/virtualrealty/enums/dynmap/HighlightType.java diff --git a/src/main/java/com/modnmetl/virtualrealty/enums/dynmap/HighlightType.java b/src/main/java/com/modnmetl/virtualrealty/enums/dynmap/HighlightType.java new file mode 100644 index 0000000..31ca896 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/enums/dynmap/HighlightType.java @@ -0,0 +1,9 @@ +package com.modnmetl.virtualrealty.enums.dynmap; + +public enum HighlightType { + + ALL, + AVAILABLE, + OWNED + +} From 72c2481a7a9672b0b3e1a92d57e3641bed06ccb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 3 Mar 2022 20:44:06 +0100 Subject: [PATCH 12/23] Update --- .../modnmetl/virtualrealty/VirtualRealty.java | 18 +++++++----- src/main/resources/plugin.yml | 6 ++-- virtualrealty.iml | 29 ++++++------------- 3 files changed, 22 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java index db5b2e8..bca866c 100644 --- a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -186,7 +186,8 @@ public void onDisable() { dataSource.getConnection().close(); } } - } catch (SQLException ignored) {} + } catch (SQLException ignored) { + } ConfigurationFactory configurationFactory = new ConfigurationFactory(); configurationFactory.updatePluginConfiguration(pluginConfigurationFile); FileUtils.deleteQuietly(loaderFile); @@ -215,7 +216,7 @@ private void runLoader(URL url, String licenseKey, String licenseEmail, String p Files.copy(in, Paths.get(loaderFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); } URL jarUrl = loaderFile.toURI().toURL(); - loader = new CustomClassLoader(new URL[]{ jarUrl }, getClassLoader()); + loader = new CustomClassLoader(new URL[]{jarUrl}, getClassLoader()); try { Class clazz = Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader", true, loader); premium = clazz.newInstance(); @@ -271,11 +272,11 @@ public void run() { if (in != null && in.available() > 0) { markerIcon = dapi.getMarkerAPI().createMarkerIcon("virtualrealty_main_icon", "Plots", in); } + } else { + markerIcon = dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon"); } - else { - markerIcon = dapi.getMarkerAPI().getMarkerIcon("virtualrealty_main_icon"); - } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } VirtualRealty.debug("Registering plots markers.."); for (Plot plot : PlotManager.getPlots()) { PlotManager.resetPlotMarker(plot); @@ -285,7 +286,7 @@ public void run() { } } } - }.runTaskTimer(this, 20, 20*5); + }.runTaskTimer(this, 20, 20 * 5); } private void registerCommands() { @@ -310,7 +311,8 @@ private void registerListeners() { Class draftListener = Class.forName("com.modnmetl.virtualrealty.listeners.premium.DraftListener", true, loader); panelListener.getConstructors()[0].newInstance(this); draftListener.getConstructors()[0].newInstance(this); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException ignored) {} + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException ignored) { + } debug("Registered listeners"); } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 1d199d9..b98223e 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -5,10 +5,10 @@ prefix: Virtual Realty authors: [ plytki ] api-version: 1.13 description: §7A plot creation and management plugin for Minecraft -softdepend: [dynmap, PlaceholderAPI] +softdepend: [ dynmap, PlaceholderAPI ] commands: virtualrealty: - aliases: [vrplot, virtualr] + aliases: [ vrplot, virtualr ] plot: - aliases: [p] + aliases: [ p ] test: \ No newline at end of file diff --git a/virtualrealty.iml b/virtualrealty.iml index 2fec24b..3b734c7 100644 --- a/virtualrealty.iml +++ b/virtualrealty.iml @@ -5,7 +5,6 @@ SPIGOT - BUKKIT @@ -22,24 +21,14 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + + + \ No newline at end of file From 872b7fbd29d513d3b49dd2dbbd1653cae82fc6e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 3 Mar 2022 20:44:29 +0100 Subject: [PATCH 13/23] Update --- virtualrealty.iml | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/virtualrealty.iml b/virtualrealty.iml index 3b734c7..edbfa79 100644 --- a/virtualrealty.iml +++ b/virtualrealty.iml @@ -21,14 +21,24 @@ - - - - - - - - - + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 40be564505c37f1ab544d800e5ad273bb583b34d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Thu, 3 Mar 2022 20:47:05 +0100 Subject: [PATCH 14/23] Update --- .gitignore | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4788b4b --- /dev/null +++ b/.gitignore @@ -0,0 +1,113 @@ +# User-specific stuff +.idea/ + +*.iml +*.ipr +*.iws + +# IntelliJ +out/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +target/ + +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next + +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar +.flattened-pom.xml + +# Common working directory +run/ From dc264361125eaff9d916bb980b559a79e743743f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Sat, 5 Mar 2022 17:55:02 +0100 Subject: [PATCH 15/23] Update --- .../modnmetl/virtualrealty/VirtualRealty.java | 4 +++- .../virtualrealty/commands/CommandManager.java | 18 ++++++++++++------ .../commands/plot/PlotCommand.java | 16 +++++++++++++--- .../commands/vrplot/VirtualRealtyCommand.java | 15 ++++++++++++--- .../configs/MessagesConfiguration.java | 6 ++++++ 5 files changed, 46 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java index bca866c..7295695 100644 --- a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -149,7 +149,7 @@ public void onEnable() { try { connectToDatabase(); } catch (SQLException e) { - getLogger().log(Level.WARNING, "Failed to connect to MySQL database."); + getLogger().log(Level.WARNING, "Failed to connect to the database."); this.getPluginLoader().disablePlugin(this); return; } @@ -309,8 +309,10 @@ private void registerListeners() { try { Class panelListener = Class.forName("com.modnmetl.virtualrealty.listeners.premium.PanelListener", true, loader); Class draftListener = Class.forName("com.modnmetl.virtualrealty.listeners.premium.DraftListener", true, loader); + Class stakeListener = Class.forName("com.modnmetl.virtualrealty.listeners.premium.StakeConfirmationListener", true, loader); panelListener.getConstructors()[0].newInstance(this); draftListener.getConstructors()[0].newInstance(this); + stakeListener.getConstructors()[0].newInstance(this); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException ignored) { } debug("Registered listeners"); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java b/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java index 3d6573a..198595a 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java @@ -209,7 +209,9 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman } case "ITEM": { if (args.length > 1) { - int backwardsArgs = 3; + boolean isNatural = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--natural")); + args = Arrays.stream(args).filter(s1 -> !s1.equalsIgnoreCase("--natural")).toArray(String[]::new); + int backwardsArgs = 3 + (isNatural ? 2 : 0); if (args.length == 2) { for (PlotSize value : PlotSize.values()) { if (args[1].isEmpty()) { @@ -228,7 +230,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman switch (plotSize) { case AREA: case CUSTOM: { - backwardsArgs = 0; + backwardsArgs = (isNatural ? 2 : 0); if (args.length == 3 && args[2].isEmpty()) { tabCompleter.add(String.valueOf(plotSize.getLength())); return tabCompleter; @@ -249,6 +251,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman } } if (args.length == 6-backwardsArgs) { + tabCompleter.add("default"); for (Material value : Material.values()) { if (!value.isSolid()) continue; if (args[5 - backwardsArgs].isEmpty()) { @@ -259,6 +262,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman } } if (args.length == 7-backwardsArgs) { + tabCompleter.add("default"); for (Material value : Material.values()) { if (!value.isSolid()) continue; if (args[6 - backwardsArgs].isEmpty()) { @@ -307,14 +311,16 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman } } } + @NotNull String[] finalArgs = args; + @NotNull String[] finalArgs1 = args; switch (args[0].toUpperCase(Locale.ROOT)) { case "KICK": case "ADD": { if (args.length == 2) { PlotManager.getAccessPlots(player.getUniqueId()).forEach((integer, plot) -> { - if (args[1].isEmpty()) { + if (finalArgs[1].isEmpty()) { tabCompleter.add(String.valueOf(plot.getID())); - } else if (String.valueOf(plot.getID()).toLowerCase().startsWith(args[0].toLowerCase())) { + } else if (String.valueOf(plot.getID()).toLowerCase().startsWith(finalArgs[0].toLowerCase())) { tabCompleter.add(String.valueOf(plot.getID())); } }); @@ -334,9 +340,9 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman case "TP": { if (args.length == 2) { PlotManager.getAccessPlots(player.getUniqueId()).forEach((integer, plot) -> { - if (args[1].isEmpty()) { + if (finalArgs1[1].isEmpty()) { tabCompleter.add(String.valueOf(plot.getID())); - } else if (String.valueOf(plot.getID()).toLowerCase().startsWith(args[0].toLowerCase())) { + } else if (String.valueOf(plot.getID()).toLowerCase().startsWith(finalArgs1[0].toLowerCase())) { tabCompleter.add(String.valueOf(plot.getID())); } }); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java index 858c8cd..a74b126 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java @@ -1,12 +1,14 @@ package com.modnmetl.virtualrealty.commands.plot; import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import java.lang.reflect.InvocationTargetException; import java.util.*; +import java.util.logging.Level; public class PlotCommand implements CommandExecutor { @@ -47,11 +49,19 @@ public boolean onCommand(CommandSender sender, Command command, String label, St Class clazz = Class.forName("com.modnmetl.virtualrealty.commands.plot.subcommand." + String.valueOf(args[0].toCharArray()[0]).toUpperCase(Locale.ROOT) + args[0].substring(1) + "SubCommand", true, VirtualRealty.getCustomClassLoader()); clazz.getConstructors()[0].newInstance(sender, command, label, args); } catch (Exception e) { - if (displayError) { - e.printStackTrace(); - } if(!(e instanceof InvocationTargetException)) { printHelp(sender); + return false; + } + + if (displayError) { + e.printStackTrace(); + } else { + if (e.getCause() instanceof FailedCommandExecution) return false; + sender.sendMessage("§cAn error occurred while executing the command."); + sender.sendMessage("§cCheck console for details."); + VirtualRealty.getInstance().getLogger().log(Level.SEVERE, "Failed command execution | Command Sender: " + sender.getName()); + VirtualRealty.getInstance().getLogger().log(Level.SEVERE, "To print more details add \"--error\" argument at the end of the command."); } } return false; diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java index c24c26c..010d782 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java @@ -1,5 +1,6 @@ package com.modnmetl.virtualrealty.commands.vrplot; +import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; import com.modnmetl.virtualrealty.utils.PermissionUtil; import com.modnmetl.virtualrealty.VirtualRealty; import org.bukkit.command.*; @@ -8,6 +9,7 @@ import java.lang.reflect.InvocationTargetException; import java.util.*; +import java.util.logging.Level; public class VirtualRealtyCommand implements CommandExecutor { @@ -53,11 +55,18 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command Class clazz = Class.forName("com.modnmetl.virtualrealty.commands.vrplot.subcommand." + String.valueOf(args[0].toCharArray()[0]).toUpperCase(Locale.ROOT) + args[0].substring(1) + "SubCommand", true, VirtualRealty.getCustomClassLoader()); clazz.getConstructors()[0].newInstance(sender, command, label, args); } catch (Exception e) { - if (displayError) { - e.printStackTrace(); - } if(!(e instanceof InvocationTargetException)) { printHelp(sender); + return false; + } + if (displayError) { + e.printStackTrace(); + } else { + if (e.getCause() instanceof FailedCommandExecution) return false; + sender.sendMessage("§cAn error occurred while executing the command."); + sender.sendMessage("§cCheck console for details."); + VirtualRealty.getInstance().getLogger().log(Level.SEVERE, "Failed command execution | Command Sender: " + sender.getName()); + VirtualRealty.getInstance().getLogger().log(Level.SEVERE, "To print more details add \"--error\" argument at the end of the command."); } } return false; diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java index 1a23b3c..ba226eb 100644 --- a/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java +++ b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java @@ -110,6 +110,12 @@ public class MessagesConfiguration extends OkaeriConfig { " " ); + public String stakeCancelled = "§cStake cancelled."; + public List stakeConfirmation = Arrays.asList( + "§7You are about to stake your claim to the plot shown, once done you cannot undo.", + "§7Type §aYES §7to proceed." + ); + //Other public String visualBoundaryDisplayed = "§aThe visual boundary was displayed."; public String visualBoundaryActive = "§cThe visual boundary is already active for this region."; From 172beaad9bed7966ab58d8ef7d8ecfca0ff4053e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Sat, 5 Mar 2022 20:31:10 +0100 Subject: [PATCH 16/23] Update --- .../java/com/modnmetl/virtualrealty/VirtualRealty.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java index 7295695..f348dba 100644 --- a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -252,10 +252,9 @@ public void registerDynmap() { @Override public void run() { Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); - if (plugin != null) { - isDynmapPresent = true; - } - if (plugin != null && plugin.isEnabled()) { + if (plugin == null) return; + isDynmapPresent = true; + if (plugin.isEnabled()) { dapi = (DynmapAPI) plugin; if (dapi.markerAPIInitialized()) { markerset = dapi.getMarkerAPI().getMarkerSet("virtualrealty.plots"); From e9892d8d15c78bcf59aaeadf8331a9f29d8d96ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Sat, 5 Mar 2022 20:49:38 +0100 Subject: [PATCH 17/23] Update --- virtualrealty.iml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/virtualrealty.iml b/virtualrealty.iml index edbfa79..caec6a7 100644 --- a/virtualrealty.iml +++ b/virtualrealty.iml @@ -35,7 +35,7 @@ - + From 95618ab0fe5bbdb8e232e7f94d0064e54401a09c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= <53957038+plytki@users.noreply.github.com> Date: Sat, 5 Mar 2022 20:53:36 +0100 Subject: [PATCH 18/23] Update --- virtualrealty.iml | 44 -------------------------------------------- 1 file changed, 44 deletions(-) delete mode 100644 virtualrealty.iml diff --git a/virtualrealty.iml b/virtualrealty.iml deleted file mode 100644 index caec6a7..0000000 --- a/virtualrealty.iml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - SPIGOT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From 3d3234b10f9909101cb0294d1ee2c61d337f0bf3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Sat, 5 Mar 2022 21:23:41 +0100 Subject: [PATCH 19/23] Update --- src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java index f348dba..053067d 100644 --- a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -30,7 +30,6 @@ import org.bstats.charts.SimplePie; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.command.CommandExecutor; import org.bukkit.permissions.Permission; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; From 8eb5660e9c38bf6a01e81dff50164507b994f7ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= <53957038+plytki@users.noreply.github.com> Date: Sat, 5 Mar 2022 21:29:42 +0100 Subject: [PATCH 20/23] Update --- src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java index 053067d..57cc8b8 100644 --- a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -311,8 +311,7 @@ private void registerListeners() { panelListener.getConstructors()[0].newInstance(this); draftListener.getConstructors()[0].newInstance(this); stakeListener.getConstructors()[0].newInstance(this); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException ignored) { - } + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException ignored) {} debug("Registered listeners"); } From 3d0c93dbb17d4100c4dc78a700abff96326fb38c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Sat, 5 Mar 2022 21:33:19 +0100 Subject: [PATCH 21/23] Update --- src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java index 57cc8b8..1f7e0ce 100644 --- a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -54,9 +54,8 @@ public final class VirtualRealty extends JavaPlugin { - public Locale locale = Locale.getDefault(); - //CORE + public Locale locale = Locale.getDefault(); private static VirtualRealty instance; private static ClassLoader loader; public static final String PREFIX = "§a§lVR §8§l» §7"; From 966864c454222bd6e8d44c3e014bae52cf2a9c4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Mon, 7 Mar 2022 18:13:01 +0100 Subject: [PATCH 22/23] Update --- .../modnmetl/virtualrealty/VirtualRealty.java | 35 ++++++++-- .../commands/CommandManager.java | 14 +++- .../virtualrealty/commands/SubCommand.java | 27 +++++--- .../commands/plot/PlotCommand.java | 4 +- .../plot/subcommand/AddSubCommand.java | 6 +- .../plot/subcommand/GmSubCommand.java | 8 +-- .../plot/subcommand/InfoSubCommand.java | 7 +- .../plot/subcommand/KickSubCommand.java | 7 +- .../plot/subcommand/ListSubCommand.java | 7 +- .../plot/subcommand/TpSubCommand.java | 7 +- .../commands/vrplot/VirtualRealtyCommand.java | 12 ++-- .../vrplot/subcommand/AssignSubCommand.java | 11 ++-- .../vrplot/subcommand/CreateSubCommand.java | 10 ++- .../vrplot/subcommand/InfoSubCommand.java | 9 ++- .../vrplot/subcommand/ListSubCommand.java | 10 ++- .../vrplot/subcommand/ReloadSubCommand.java | 10 ++- .../vrplot/subcommand/RemoveSubCommand.java | 13 ++-- .../vrplot/subcommand/SetSubCommand.java | 19 +++--- .../vrplot/subcommand/TpSubCommand.java | 10 ++- .../vrplot/subcommand/UnassignSubCommand.java | 12 ++-- .../configs/MessagesConfiguration.java | 1 + .../exceptions/FailedCommandException.java | 9 +++ .../exceptions/FailedCommandExecution.java | 9 --- .../InsufficientPermissionsException.java | 9 +++ .../protection/BorderProtectionListener.java | 1 + .../protection/PlotProtectionListener.java | 43 +++++++------ .../protection/WorldProtectionListener.java | 40 ++++++------ .../virtualrealty/utils/PermissionUtil.java | 18 ------ src/main/resources/messages_es_ES.yml | 62 ------------------ src/main/resources/messages_pl_PL.yml | 64 ------------------- 30 files changed, 196 insertions(+), 298 deletions(-) create mode 100644 src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandException.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandExecution.java create mode 100644 src/main/java/com/modnmetl/virtualrealty/exceptions/InsufficientPermissionsException.java delete mode 100644 src/main/java/com/modnmetl/virtualrealty/utils/PermissionUtil.java delete mode 100644 src/main/resources/messages_es_ES.yml delete mode 100644 src/main/resources/messages_pl_PL.yml diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java index 1f7e0ce..2c717de 100644 --- a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -1,5 +1,8 @@ package com.modnmetl.virtualrealty; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; import com.modnmetl.virtualrealty.commands.CommandManager; import com.modnmetl.virtualrealty.commands.SubCommand; import com.modnmetl.virtualrealty.commands.plot.PlotCommand; @@ -45,6 +48,7 @@ import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; @@ -137,7 +141,7 @@ public void onEnable() { } if (!pluginConfiguration.license.key.isEmpty() && !pluginConfiguration.license.email.isEmpty()) { try { - runLoader(new URL("http://license.mineproxy.com/virtualrealty/premium"), pluginConfiguration.license.key, pluginConfiguration.license.email, this.getDescription().getVersion()); + runLoader(pluginConfiguration.license.key, pluginConfiguration.license.email, this.getDescription().getVersion()); } catch (IOException | InstantiationException | IllegalAccessException | ClassNotFoundException e) { getLogger().log(Level.WARNING, "Loading of premium features failed."); } @@ -197,12 +201,30 @@ public static void debug(String debugMessage) { VirtualRealty.getInstance().getLogger().warning("DEBUG > " + debugMessage); } - private void runLoader(URL url, String licenseKey, String licenseEmail, String pluginVersion) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { - url = new URL(url.toString() + "?license=" + licenseKey + "&email=" + licenseEmail + "&version=" + pluginVersion); + private void runLoader(String licenseKey, String licenseEmail, String pluginVersion) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { + URL url = new URL("https://api.modnmetl.com/auth/key"); + debug("Injecting premium.."); - HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); - httpConn.setConnectTimeout(1200); - httpConn.setReadTimeout(5000); + HttpURLConnection httpConn = (HttpURLConnection)url.openConnection(); + httpConn.setRequestMethod("POST"); + httpConn.setDoOutput(true); + httpConn.setRequestProperty("Content-Type", "application/json"); + + Gson gson = new Gson(); + JsonObject jsonObject = new JsonObject(); +// jsonObject.addProperty("license", licenseKey); +// jsonObject.addProperty("email", licenseEmail); +// jsonObject.addProperty("version", pluginVersion); + jsonObject.addProperty("id", "62110bdbf58570001812deb8"); + jsonObject.addProperty("key", "cVvW6fuGV5a6Mbm7nWlXSC4m0J5cazYz"); + jsonObject.addProperty("version", pluginVersion); + String data = gson.toJson(jsonObject); + + byte[] out = data.getBytes(StandardCharsets.UTF_8); + OutputStream stream = httpConn.getOutputStream(); + stream.write(out); + System.out.println(httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); + int responseCode = httpConn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { debug("Authentication error"); @@ -215,6 +237,7 @@ private void runLoader(URL url, String licenseKey, String licenseEmail, String p } URL jarUrl = loaderFile.toURI().toURL(); loader = new CustomClassLoader(new URL[]{jarUrl}, getClassLoader()); + httpConn.disconnect(); try { Class clazz = Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader", true, loader); premium = clazz.newInstance(); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java b/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java index 198595a..87bb0ed 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java @@ -1,5 +1,6 @@ package com.modnmetl.virtualrealty.commands; +import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.plot.PlotCommand; import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; import com.modnmetl.virtualrealty.enums.PlotSize; @@ -34,7 +35,7 @@ public static void addSubCommand(String subCommand, Class mainCommandClass) { public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { LinkedList tabCompleter = new LinkedList<>(); if (command.getName().equalsIgnoreCase("virtualrealty")) { - if (!sender.isOp()) return null; + if (assertPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName())) return null; if (args.length <= 1) { for (String subcommand : SUBCOMMANDS.get(VirtualRealtyCommand.class)) { if (args[0].isEmpty()) { @@ -46,6 +47,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman } switch (args[0].toUpperCase(Locale.ROOT)) { case "CREATE": { + if (assertPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase())) return null; if (args.length > 1) { if (args.length == 2) { for (PlotSize value : PlotSize.values()) { @@ -74,6 +76,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman return tabCompleter; } case "SET": { + if (assertPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase())) return null; if (args.length == 2) { for (Plot plot : PlotManager.getPlots()) { if (args[1].isEmpty()) { @@ -171,6 +174,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman } case "ASSIGN": case "UNASSIGN": { + if (assertPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase())) return null; if (args.length == 2) { for (Plot plot : PlotManager.getPlots()) { if (args[1].isEmpty()) { @@ -196,6 +200,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman case "INFO": case "REMOVE": case "TP": { + if (assertPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase())) return null; if (args.length == 2) { for (Plot plot : PlotManager.getPlots()) { if (args[1].isEmpty()) { @@ -208,6 +213,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman } } case "ITEM": { + if (assertPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase())) return null; if (args.length > 1) { boolean isNatural = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--natural")); args = Arrays.stream(args).filter(s1 -> !s1.equalsIgnoreCase("--natural")).toArray(String[]::new); @@ -299,7 +305,6 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman } return tabCompleter; } else if (command.getName().equalsIgnoreCase("plot")) { - if (!sender.isOp()) return null; if (!(sender instanceof Player)) return null; Player player = ((Player) sender); if (args.length <= 1) { @@ -355,4 +360,9 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman return null; } + + public boolean assertPermission(CommandSender sender, String permission) { + return !sender.hasPermission(permission); + } + } diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/SubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/SubCommand.java index bf9dab2..1342d70 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/SubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/SubCommand.java @@ -1,8 +1,8 @@ package com.modnmetl.virtualrealty.commands; import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.commands.vrplot.subcommand.AssignSubCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; +import com.modnmetl.virtualrealty.exceptions.InsufficientPermissionsException; import lombok.SneakyThrows; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -17,26 +17,37 @@ public abstract class SubCommand { private final LinkedList helpList; @SneakyThrows - public SubCommand(CommandSender sender, Command command, String label, String[] args, LinkedList helpList) throws FailedCommandExecution { + public SubCommand(CommandSender sender, Command command, String label, String[] args, LinkedList helpList) throws FailedCommandException { this.helpList = helpList; this.commandSender = sender; exec(sender, command, label, args); } - public abstract void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution; + public abstract void exec(CommandSender sender, Command command, String label, String[] args) throws Exception; - public void assertPlayer() throws FailedCommandExecution { + public void assertPlayer() throws FailedCommandException { if (!(commandSender instanceof Player)) { commandSender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cmdOnlyPlayers); - throw new FailedCommandExecution(); + throw new FailedCommandException(); } } - public void printHelp() throws FailedCommandExecution { + public void assertPermission(String permission) throws InsufficientPermissionsException { + if (!commandSender.hasPermission(permission)) { + if (commandSender.isOp()) { + commandSender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().insufficientPermissions.replaceAll("%permission%", permission)); + } else { + commandSender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().insufficientPermissionsShort.replaceAll("%permission%", permission)); + } + throw new InsufficientPermissionsException(); + } + } + + public void printHelp() throws FailedCommandException { for (String s : helpList) { commandSender.sendMessage(s); } - throw new FailedCommandExecution(); + throw new FailedCommandException(); } public static void registerSubCommands(String[] subCommand, Class mainCommandClass) { diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java index a74b126..53abb2b 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java @@ -1,7 +1,7 @@ package com.modnmetl.virtualrealty.commands.plot; import com.modnmetl.virtualrealty.VirtualRealty; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; @@ -57,7 +57,7 @@ public boolean onCommand(CommandSender sender, Command command, String label, St if (displayError) { e.printStackTrace(); } else { - if (e.getCause() instanceof FailedCommandExecution) return false; + if (e.getCause() instanceof FailedCommandException) return false; sender.sendMessage("§cAn error occurred while executing the command."); sender.sendMessage("§cCheck console for details."); VirtualRealty.getInstance().getLogger().log(Level.SEVERE, "Failed command execution | Command Sender: " + sender.getName()); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/AddSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/AddSubCommand.java index 6715647..d91cdec 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/AddSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/AddSubCommand.java @@ -3,7 +3,7 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; import com.modnmetl.virtualrealty.enums.permissions.ManagementPermission; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; import com.modnmetl.virtualrealty.objects.PlotMember; @@ -26,12 +26,12 @@ public class AddSubCommand extends SubCommand { HELP.add(" §a/plot add §8<§7plot§8> §8<§7player§8>"); } - public AddSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public AddSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { assertPlayer(); Player player = ((Player) sender); if (args.length < 3) { diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/GmSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/GmSubCommand.java index 7e33807..c8b89d8 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/GmSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/GmSubCommand.java @@ -2,9 +2,8 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; -import com.modnmetl.virtualrealty.managers.PlotMemberManager; import com.modnmetl.virtualrealty.objects.Plot; import com.modnmetl.virtualrealty.objects.PlotMember; import org.bukkit.GameMode; @@ -12,7 +11,6 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; import java.util.LinkedList; public class GmSubCommand extends SubCommand { @@ -25,12 +23,12 @@ public class GmSubCommand extends SubCommand { HELP.add(" §a/plot gm §8<§7gamemode§8>"); } - public GmSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public GmSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { assertPlayer(); Player player = ((Player) sender); if (args.length < 2) { diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/InfoSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/InfoSubCommand.java index 641bf9b..d72cae3 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/InfoSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/InfoSubCommand.java @@ -2,7 +2,7 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; import org.bukkit.Bukkit; @@ -13,17 +13,16 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.LinkedList; public class InfoSubCommand extends SubCommand { - public InfoSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public InfoSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, new LinkedList<>()); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { assertPlayer(); Player player = ((Player) sender); Plot plot = PlotManager.getPlot(player.getLocation()); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/KickSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/KickSubCommand.java index a64b236..c54b81b 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/KickSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/KickSubCommand.java @@ -3,7 +3,7 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; import com.modnmetl.virtualrealty.enums.permissions.ManagementPermission; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; import com.modnmetl.virtualrealty.objects.PlotMember; @@ -14,7 +14,6 @@ import org.bukkit.entity.Player; import java.time.LocalDateTime; -import java.util.ArrayList; import java.util.LinkedList; public class KickSubCommand extends SubCommand { @@ -27,12 +26,12 @@ public class KickSubCommand extends SubCommand { HELP.add(" §a/plot kick §8<§7plot§8> §8<§7player§8>"); } - public KickSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public KickSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { assertPlayer(); Player player = ((Player) sender); if (args.length < 3) { diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/ListSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/ListSubCommand.java index 33c20c6..83d21da 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/ListSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/ListSubCommand.java @@ -2,7 +2,7 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; import net.md_5.bungee.api.chat.BaseComponent; @@ -14,17 +14,16 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.LinkedList; public class ListSubCommand extends SubCommand { - public ListSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public ListSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, new LinkedList<>()); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { assertPlayer(); Player player = ((Player) sender); boolean hasPlot = false; diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java index 13bd0f6..62043ce 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java @@ -2,7 +2,7 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; import org.bukkit.Location; @@ -10,7 +10,6 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; import java.util.LinkedList; import java.util.Objects; @@ -24,12 +23,12 @@ public class TpSubCommand extends SubCommand { HELP.add(" §a/plot tp §8<§7plot§8>"); } - public TpSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public TpSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { assertPlayer(); Player player = ((Player) sender); if (args.length < 2) { diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java index 010d782..803eb60 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/VirtualRealtyCommand.java @@ -1,8 +1,8 @@ package com.modnmetl.virtualrealty.commands.vrplot; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; -import com.modnmetl.virtualrealty.utils.PermissionUtil; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.VirtualRealty; +import com.modnmetl.virtualrealty.exceptions.InsufficientPermissionsException; import org.bukkit.command.*; import org.bukkit.permissions.Permission; import org.jetbrains.annotations.NotNull; @@ -37,7 +37,10 @@ public class VirtualRealtyCommand implements CommandExecutor { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { boolean displayError = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--error")); args = Arrays.stream(args).filter(s1 -> !s1.equalsIgnoreCase("--error")).toArray(String[]::new); - if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName())) return false; + if (!sender.hasPermission(COMMAND_PERMISSION)) { + sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().insufficientPermissions.replaceAll("%permission%", COMMAND_PERMISSION.getName())); + return false; + } if ((args.length > 0 && args[0].equalsIgnoreCase("help")) || args.length == 0) { printHelp(sender); return false; @@ -62,7 +65,8 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command if (displayError) { e.printStackTrace(); } else { - if (e.getCause() instanceof FailedCommandExecution) return false; + if (e.getCause() instanceof FailedCommandException) return false; + if (e.getCause() instanceof InsufficientPermissionsException) return false; sender.sendMessage("§cAn error occurred while executing the command."); sender.sendMessage("§cCheck console for details."); VirtualRealty.getInstance().getLogger().log(Level.SEVERE, "Failed command execution | Command Sender: " + sender.getName()); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/AssignSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/AssignSubCommand.java index 8c73e6b..125855d 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/AssignSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/AssignSubCommand.java @@ -2,11 +2,9 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.PermissionUtil; import com.modnmetl.virtualrealty.utils.UUIDUtils; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; @@ -15,7 +13,6 @@ import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; import java.util.LinkedList; import java.util.UUID; @@ -31,13 +28,13 @@ public class AssignSubCommand extends SubCommand { HELP.add(" §a/vrplot assign §8<§7plot§8> §8<§7username§8>"); } - public AssignSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public AssignSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { - if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + public void exec(CommandSender sender, Command command, String label, String[] args) throws Exception { + assertPermission(COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase()); if (args.length < 2) { for (String helpMessage : HELP) { sender.sendMessage(helpMessage); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java index 240afcf..48ec357 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java @@ -4,11 +4,10 @@ import com.modnmetl.virtualrealty.commands.SubCommand; import com.modnmetl.virtualrealty.enums.Direction; import com.modnmetl.virtualrealty.enums.PlotSize; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; import com.modnmetl.virtualrealty.objects.region.GridStructure; -import com.modnmetl.virtualrealty.utils.PermissionUtil; import com.modnmetl.virtualrealty.utils.RegionUtil; import com.modnmetl.virtualrealty.utils.multiversion.Chat; import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; @@ -23,7 +22,6 @@ import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; -import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; @@ -40,14 +38,14 @@ public class CreateSubCommand extends SubCommand { HELP.add(" §a/vrplot create §8<§7length§8> §8<§7height§8> §8<§7width§8> §8<§7floor (optional)§8> §8<§7border (optional)§8>"); } - public CreateSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public CreateSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public void exec(CommandSender sender, Command command, String label, String[] args) throws Exception { assertPlayer(); - if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + assertPermission(COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase()); if (args.length < 2) { printHelp(); return; diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java index 0fdeced..b244e83 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java @@ -2,10 +2,9 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.PermissionUtil; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; @@ -21,13 +20,13 @@ public class InfoSubCommand extends SubCommand { - public InfoSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public InfoSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, new LinkedList<>()); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { - if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + public void exec(CommandSender sender, Command command, String label, String[] args) throws Exception { + assertPermission(COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase()); if (args.length < 2) { assertPlayer(); Plot plot = PlotManager.getPlot(((Player) sender).getLocation()); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ListSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ListSubCommand.java index 9d56291..a04fa23 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ListSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ListSubCommand.java @@ -2,10 +2,9 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.PermissionUtil; import com.modnmetl.virtualrealty.utils.multiversion.Chat; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; @@ -17,20 +16,19 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.LinkedList; import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; public class ListSubCommand extends SubCommand { - public ListSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public ListSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, new LinkedList<>()); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { - if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + public void exec(CommandSender sender, Command command, String label, String[] args) throws Exception { + assertPermission(COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase()); if (PlotManager.getPlots().isEmpty()) { sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlots); return; diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ReloadSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ReloadSubCommand.java index 8d673a8..fdc275f 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ReloadSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/ReloadSubCommand.java @@ -2,27 +2,25 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.PermissionUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; -import java.util.ArrayList; import java.util.LinkedList; import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; public class ReloadSubCommand extends SubCommand { - public ReloadSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public ReloadSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, new LinkedList<>()); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { - if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + public void exec(CommandSender sender, Command command, String label, String[] args) throws Exception { + assertPermission(COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase()); try { VirtualRealty.getInstance().reloadConfigs(); if (VirtualRealty.getPluginConfiguration().dynmapMarkers) { diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/RemoveSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/RemoveSubCommand.java index ea1a07a..aa7e2f3 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/RemoveSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/RemoveSubCommand.java @@ -2,17 +2,16 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.PermissionUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; -import java.util.ArrayList; import java.util.LinkedList; +import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; + public class RemoveSubCommand extends SubCommand { public static final LinkedList HELP = new LinkedList<>(); @@ -23,13 +22,13 @@ public class RemoveSubCommand extends SubCommand { HELP.add(" §a/vrplot remove §8<§7plot§8>"); } - public RemoveSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public RemoveSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { - if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + public void exec(CommandSender sender, Command command, String label, String[] args) throws Exception { + assertPermission(COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase()); if (args.length < 2) { printHelp(); return; diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/SetSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/SetSubCommand.java index 44a7c7a..1b8ad67 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/SetSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/SetSubCommand.java @@ -3,10 +3,9 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.PermissionUtil; import com.modnmetl.virtualrealty.utils.UUIDUtils; import com.modnmetl.virtualrealty.utils.multiversion.VMaterial; import org.bukkit.Bukkit; @@ -19,6 +18,8 @@ import java.time.LocalDateTime; import java.util.*; +import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; + public class SetSubCommand extends SubCommand { public static final LinkedList HELP = new LinkedList<>(); @@ -32,20 +33,20 @@ public class SetSubCommand extends SubCommand { HELP.add(" §a/vrplot set §8<§7plot§8> §aexpiry §8<§7dd/mm/YYYY§8> §8<§7HH:mm (optional)§8>"); } - public SetSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public SetSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { - if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + public void exec(CommandSender sender, Command command, String label, String[] args) throws Exception { + assertPermission(COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase()); if (args.length < 3) { printHelp(); return; } switch (args[2].toUpperCase()) { case "OWNER": { - if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase())) return; + assertPermission(COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase()); if (args.length < 4) { sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyUsername); return; @@ -111,7 +112,7 @@ public void exec(CommandSender sender, Command command, String label, String[] a return; } case "FLOOR": { - if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase())) return; + assertPermission(COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase()); if (args.length < 4) { sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); return; @@ -149,7 +150,7 @@ public void exec(CommandSender sender, Command command, String label, String[] a return; } case "BORDER": { - if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase())) return; + assertPermission(COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase()); if (args.length < 4) { sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyMaterialName); return; @@ -187,7 +188,7 @@ public void exec(CommandSender sender, Command command, String label, String[] a return; } case "EXPIRY": { - if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase())) return; + assertPermission(COMMAND_PERMISSION.getName() + args[0].toLowerCase() + "." + args[2].toLowerCase()); if (args.length < 4) { sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().specifyExpiryDate); return; diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java index c60d3a7..8eda0bf 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java @@ -2,16 +2,14 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.PermissionUtil; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; import java.util.LinkedList; import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; @@ -26,14 +24,14 @@ public class TpSubCommand extends SubCommand { HELP.add(" §a/vrplot tp §8<§7plot§8>"); } - public TpSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public TpSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public void exec(CommandSender sender, Command command, String label, String[] args) throws Exception { assertPlayer(); - if (!PermissionUtil.hasPermission(sender, COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + assertPermission(COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase()); if (args.length < 2) { printHelp(); return; diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/UnassignSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/UnassignSubCommand.java index 30c5d84..bd9907e 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/UnassignSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/UnassignSubCommand.java @@ -3,16 +3,16 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.commands.SubCommand; import com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand; -import com.modnmetl.virtualrealty.exceptions.FailedCommandExecution; +import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; -import com.modnmetl.virtualrealty.utils.PermissionUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; -import java.util.ArrayList; import java.util.LinkedList; +import static com.modnmetl.virtualrealty.commands.vrplot.VirtualRealtyCommand.COMMAND_PERMISSION; + public class UnassignSubCommand extends SubCommand { public static final LinkedList HELP = new LinkedList<>(); @@ -23,13 +23,13 @@ public class UnassignSubCommand extends SubCommand { HELP.add(" §a/vrplot unassign §8<§7plot§8>"); } - public UnassignSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { + public UnassignSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { super(sender, command, label, args, HELP); } @Override - public void exec(CommandSender sender, Command command, String label, String[] args) throws FailedCommandExecution { - if (!PermissionUtil.hasPermission(sender, VirtualRealtyCommand.COMMAND_PERMISSION.getName() + args[0].toLowerCase())) return; + public void exec(CommandSender sender, Command command, String label, String[] args) throws Exception { + assertPermission(COMMAND_PERMISSION.getName() + "." + args[0].toLowerCase()); if (args.length < 2) { printHelp(); return; diff --git a/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java index ba226eb..773fff9 100644 --- a/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java +++ b/src/main/java/com/modnmetl/virtualrealty/configs/MessagesConfiguration.java @@ -32,6 +32,7 @@ public class MessagesConfiguration extends OkaeriConfig { public String creationPlotComponent3 = " §acreated! §8(§7%creation_time% ms§8)"; //Checks + public String insufficientPermissionsShort = "§cInsufficient permissions!"; public String insufficientPermissions = "§cInsufficient permissions! §8(§7%permission%§8)"; public String useNaturalNumbersOnly = "§cUse only natural numbers!"; public String incorrectGamemode = "§cIncorrect gamemode value!"; diff --git a/src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandException.java b/src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandException.java new file mode 100644 index 0000000..b221512 --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandException.java @@ -0,0 +1,9 @@ +package com.modnmetl.virtualrealty.exceptions; + +public class FailedCommandException extends Exception { + + public FailedCommandException() { + super(); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandExecution.java b/src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandExecution.java deleted file mode 100644 index 42d716d..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/exceptions/FailedCommandExecution.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.modnmetl.virtualrealty.exceptions; - -public class FailedCommandExecution extends Exception { - - public FailedCommandExecution() { - super(); - } - -} diff --git a/src/main/java/com/modnmetl/virtualrealty/exceptions/InsufficientPermissionsException.java b/src/main/java/com/modnmetl/virtualrealty/exceptions/InsufficientPermissionsException.java new file mode 100644 index 0000000..b56fdac --- /dev/null +++ b/src/main/java/com/modnmetl/virtualrealty/exceptions/InsufficientPermissionsException.java @@ -0,0 +1,9 @@ +package com.modnmetl.virtualrealty.exceptions; + +public class InsufficientPermissionsException extends Exception { + + public InsufficientPermissionsException() { + super(); + } + +} diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/protection/BorderProtectionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/BorderProtectionListener.java index 811d533..20e1e0d 100644 --- a/src/main/java/com/modnmetl/virtualrealty/listeners/protection/BorderProtectionListener.java +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/BorderProtectionListener.java @@ -4,6 +4,7 @@ import com.modnmetl.virtualrealty.VirtualRealty; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; +import org.bukkit.command.CommandSender; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/protection/PlotProtectionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/PlotProtectionListener.java index fb0fa1a..1d1ef52 100644 --- a/src/main/java/com/modnmetl/virtualrealty/listeners/protection/PlotProtectionListener.java +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/PlotProtectionListener.java @@ -8,14 +8,12 @@ import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; import com.modnmetl.virtualrealty.objects.PlotMember; -import de.tr7zw.nbtinjector.javassist.expr.Instanceof; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.World; import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.data.type.Switch; +import org.bukkit.command.CommandSender; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -26,14 +24,15 @@ import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.util.Vector; +import org.bukkit.permissions.Permission; import java.util.ArrayList; import java.util.LinkedList; -import java.util.List; import java.util.Objects; public class PlotProtectionListener extends VirtualListener { + + public static final Permission PLOT_BUILD = new Permission("virtualrealty.build.plot"); public static final LinkedList INTERACTABLE = new LinkedList<>(); public static final LinkedList SWITCHABLE = new LinkedList<>(); @@ -72,7 +71,7 @@ public void onBlockInteract(PlayerInteractEvent e) { } Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -121,7 +120,7 @@ public void onChestEvent(PlayerInteractEvent e) { if (player.isSneaking() && e.isBlockInHand()) return; Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -148,7 +147,7 @@ public void onLiquidPlace(PlayerBucketEmptyEvent e) { Player player = e.getPlayer(); Plot plot = PlotManager.getBorderedPlot(e.getBlockClicked().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -176,7 +175,7 @@ public void onVehicleDestroy(VehicleDestroyEvent e) { Player player = (Player) e.getAttacker(); Plot plot = PlotManager.getBorderedPlot(e.getVehicle().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -203,7 +202,7 @@ public void onLiquidTake(PlayerBucketFillEvent e) { Player player = e.getPlayer(); Plot plot = PlotManager.getBorderedPlot(e.getBlockClicked().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -229,7 +228,7 @@ public void onBlockPlace(BlockPlaceEvent e) { Player player = e.getPlayer(); Plot plot = PlotManager.getBorderedPlot(e.getBlockPlaced().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -256,7 +255,7 @@ public void onBlockBreak(BlockBreakEvent e) { Player player = e.getPlayer(); Plot plot = PlotManager.getBorderedPlot(e.getBlock().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -323,7 +322,7 @@ public void onIgniteEvent(BlockIgniteEvent e) { if (e.getIgnitingBlock() == null) return; Plot plot = PlotManager.getBorderedPlot(e.getIgnitingBlock().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -404,7 +403,7 @@ public void onProjectileLaunch(ProjectileLaunchEvent e) { Player shooter = ((Player) e.getEntity().getShooter()); Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); if (plot == null) return; - if (shooter.isOp()) return; + if (hasPermission(shooter, PLOT_BUILD)) return; if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId())) return; if (plot.hasMembershipAccess(shooter.getUniqueId())) return; @@ -418,7 +417,7 @@ public void onProjectileHit(ProjectileHitEvent e) { Player shooter = ((Player) e.getEntity().getShooter()); Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); if (plot == null) return; - if (shooter.isOp()) return; + if (hasPermission(shooter, PLOT_BUILD)) return; if (plot.getOwnedBy() != null && plot.getOwnedBy().equals(((Player) e.getEntity().getShooter()).getUniqueId())) return; if (plot.hasMembershipAccess(shooter.getUniqueId())) return; @@ -431,7 +430,7 @@ public void onArmorStandChange(PlayerArmorStandManipulateEvent e) { Plot plot = PlotManager.getPlot(e.getPlayer().getLocation()); Player player = e.getPlayer(); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -459,7 +458,7 @@ public void onItemFrameDamage(HangingBreakByEntityEvent e) { Player player = (Player) e.getRemover(); Plot plot = PlotManager.getPlot(player.getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -486,7 +485,7 @@ public void onItemFrameRotate(PlayerInteractEntityEvent e) { Player player = e.getPlayer(); Plot plot = PlotManager.getPlot(player.getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -515,7 +514,7 @@ public void onEntityDamage(EntityDamageByEntityEvent e) { Player player = (Player) e.getDamager(); Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -585,7 +584,7 @@ public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { Player player = ((Player) ((Projectile) e.getDamager()).getShooter()); Plot plot = PlotManager.getBorderedPlot(e.getDamager().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, PLOT_BUILD)) return; if (plot.hasMembershipAccess(player.getUniqueId())) { PlotMember plotMember = plot.getMember(player.getUniqueId()); if (plot.isOwnershipExpired()) { @@ -606,4 +605,8 @@ public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { } } + public boolean hasPermission(CommandSender sender, Permission permission) { + return sender.hasPermission(permission); + } + } diff --git a/src/main/java/com/modnmetl/virtualrealty/listeners/protection/WorldProtectionListener.java b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/WorldProtectionListener.java index e0bc6a5..1108722 100644 --- a/src/main/java/com/modnmetl/virtualrealty/listeners/protection/WorldProtectionListener.java +++ b/src/main/java/com/modnmetl/virtualrealty/listeners/protection/WorldProtectionListener.java @@ -9,6 +9,7 @@ import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.block.data.type.Switch; +import org.bukkit.command.CommandSender; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; @@ -21,10 +22,13 @@ import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.permissions.Permission; import org.bukkit.util.Vector; public class WorldProtectionListener extends VirtualListener { + public static final Permission WORLD_BUILD = new Permission("virtualrealty.build.world"); + public WorldProtectionListener(VirtualRealty plugin) { super(plugin); } @@ -45,7 +49,7 @@ public void onBlockInteract(PlayerInteractEvent e) { } Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); if (plot != null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; try { if ((!VirtualRealty.legacyVersion && e.getClickedBlock().getBlockData() instanceof Switch) || PlotProtectionListener.SWITCHABLE.contains(e.getClickedBlock().getType())) { Class.forName("com.modnmetl.virtualrealty.premiumloader.PremiumLoader", false, VirtualRealty.getCustomClassLoader()); @@ -62,8 +66,7 @@ public void onBlockInteract(PlayerInteractEvent e) { player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); } } - } catch (Exception ignored) { - } + } catch (Exception ignored) {} } @EventHandler(priority = EventPriority.LOW) @@ -76,7 +79,7 @@ public void onChestClick(PlayerInteractEvent e) { if (player.isSneaking() && e.isBlockInHand()) return; Plot plot = PlotManager.getPlot(e.getClickedBlock().getLocation()); if (plot != null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; if (!WorldUtil.hasPermission(RegionPermission.CHEST_ACCESS)) { e.setCancelled(true); player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); @@ -89,7 +92,7 @@ public void onBlockPlace(BlockPlaceEvent e) { Player player = e.getPlayer(); Plot plot = PlotManager.getPlot(e.getBlockPlaced().getLocation()); if (plot != null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; if (!WorldUtil.hasPermission(RegionPermission.PLACE)) { e.setCancelled(true); player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); @@ -102,21 +105,12 @@ public void onBlockBreak(BlockBreakEvent e) { Player player = e.getPlayer(); Plot plot = PlotManager.getPlot(e.getBlock().getLocation()); if (plot != null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; if (!WorldUtil.hasPermission(RegionPermission.BREAK)) { e.setCancelled(true); player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantBuildHere); } } - - - public Vector getDirection(BlockFace blockFace) { - Vector direction = new Vector(blockFace.getModX(), blockFace.getModY(), blockFace.getModZ()); - if (blockFace.getModX() != 0 || blockFace.getModY() != 0 || blockFace.getModZ() != 0) { - direction.normalize(); - } - return direction; - } @EventHandler(priority = EventPriority.LOW) public void onIgniteEvent(BlockIgniteEvent e) { @@ -126,7 +120,7 @@ public void onIgniteEvent(BlockIgniteEvent e) { if (e.getIgnitingBlock() == null) return; Plot plot = PlotManager.getBorderedPlot(e.getIgnitingBlock().getLocation()); if (plot != null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; if (!WorldUtil.hasPermission(RegionPermission.ITEM_USE)) { e.setCancelled(true); player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); @@ -139,7 +133,7 @@ public void onArmorStandChange(PlayerArmorStandManipulateEvent e) { Plot plot = PlotManager.getPlot(e.getPlayer().getLocation()); Player player = e.getPlayer(); if (plot != null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; if (!WorldUtil.hasPermission(RegionPermission.ARMOR_STAND)) { e.setCancelled(true); player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); @@ -153,7 +147,7 @@ public void onItemFrameDamage(HangingBreakByEntityEvent e) { Player player = (Player) e.getRemover(); Plot plot = PlotManager.getPlot(player.getLocation()); if (plot != null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; if (!WorldUtil.hasPermission(RegionPermission.ENTITY_DAMAGE)) { e.setCancelled(true); player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); @@ -167,7 +161,7 @@ public void onItemFrameRotate(PlayerInteractEntityEvent e) { Player player = e.getPlayer(); Plot plot = PlotManager.getPlot(player.getLocation()); if (plot != null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; if (!WorldUtil.hasPermission(RegionPermission.ITEM_USE)) { e.setCancelled(true); player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantInteract); @@ -182,7 +176,7 @@ public void onEntityDamage(EntityDamageByEntityEvent e) { Player player = (Player) e.getDamager(); Plot plot = PlotManager.getPlot(e.getEntity().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; if (!WorldUtil.hasPermission(RegionPermission.ENTITY_DAMAGE)) { e.setCancelled(true); player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); @@ -197,11 +191,15 @@ public void onEntityProjectileDamage(EntityDamageByEntityEvent e) { Player player = ((Player) ((Projectile) e.getDamager()).getShooter()); Plot plot = PlotManager.getBorderedPlot(e.getDamager().getLocation()); if (plot == null) return; - if (player.isOp()) return; + if (hasPermission(player, WORLD_BUILD)) return; if (!WorldUtil.hasPermission(RegionPermission.ENTITY_DAMAGE)) { e.setCancelled(true); player.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantDoAnyDMG); } } + public boolean hasPermission(CommandSender sender, Permission permission) { + return sender.hasPermission(permission); + } + } diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/PermissionUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/PermissionUtil.java deleted file mode 100644 index 230ea00..0000000 --- a/src/main/java/com/modnmetl/virtualrealty/utils/PermissionUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.modnmetl.virtualrealty.utils; - -import com.modnmetl.virtualrealty.VirtualRealty; -import org.bukkit.command.CommandSender; -import org.bukkit.permissions.Permission; - -public class PermissionUtil { - - public static boolean hasPermission(CommandSender sender, String permission) { - Permission finalPermission = new Permission(permission); - if (!sender.hasPermission(finalPermission)) { - sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().insufficientPermissions.replaceAll("%permission%", finalPermission.getName())); - return false; - } - return true; - } - -} diff --git a/src/main/resources/messages_es_ES.yml b/src/main/resources/messages_es_ES.yml deleted file mode 100644 index f50e1ff..0000000 --- a/src/main/resources/messages_es_ES.yml +++ /dev/null @@ -1,62 +0,0 @@ -useNaturalNumbersOnly: §c¡Usa sólo números naturales! -noPlotFound: §cNo se ha podido obtener el gráfico con el ID especificado -notYourPlot: §c¡No es tu parcela! -ownershipExpired: §c¡La propiedad de la parcela ha expirado! -teleportedToPlot: §a¡Has sido teletransportado a la parcela! -gamemodeFeatureDisabled: §c¡La función de modo de juego está desactivada! -incorrectGamemode: §c¡Valor de modo de juego incorrecto! -gamemodeDisabled: §cEste modo de juego está desactivado. -cantSwitchGamemode: §c¡No puedes cambiar de modo de juego aquí! -creativeIsEnabled: §c¡El modo creativo ya está habilitado! -creativeIsDisabled: §c¡El modo creativo ya está desactivado! -creativeEnabled: §aEl modo creativo está habilitado. -creativeDisabled: §e¡El modo creativo ha sido desactivado! -notStandingOnPlot: §c¡No estás parado en ninguna parcela! -assignedByConsole: §eConsola -assignedByShopPurchase: §eCompra en tienda -noPlots: §c¡No hay parcelas! -available: §cDisponible -reloadCompleted: §a¡El plugin ha sido recargado! -cantCreateOnExisting: §c¡No se puede crear una nueva parcela en una parcela existente! -cantGetFloorMaterial: §c¡No se ha podido obtener el material del suelo con el nombre especificado! -cantGetBorderMaterial: §c¡No se ha podido obtener el material del borde con el nombre especificado! -cantGetMaterial: §c¡No se ha podido obtener el material con el nombre especificado! -notCollidingCreating: §aNo colisiona. Creando parcela.. -clickToShowDetailedInfo: '§a§o¡Haz click para mostrar información detallada sobre la parcela! §8(§7ID: §f%plot_id%§8)' -sizeNotRecognised: §c¡Tamaño no reconocido! -LWHHardLimit: §c¡El limite máximo L, W y H es de 500! -removedPlot: §a¡Se ha eliminado la parcela con éxito! -specifyUsername: §c¡Especificar nombre de usuario! -playerNotFoundWithUsername: §c¡No se ha podido encontrar al jugador con el nombre de usuario especificado! -invalidDateProvided: §c¡Formato de fecha inválido proporcionado! -assignedTo: §a¡La parcela ha sido asignada a §f%assigned_to%§a! -specifyMaterialName: §c¡Especifique el nombre del material! -specifyExpiryDate: §c¡Especifique la fecha de expiración! -newFloorMaterialSet: §a¡Se ha establecido un nuevo material para el suelo! -newBorderMaterialSet: §a¡Se ha establecido un nuevo material para los bordes! -ownedUntilUpdated: §a¡La propiedad está actualizada hasta este momento! -assignedToBy: §a¡La parcela ha sido asignada a §f%assigned_to% §apor §f%assigned_by%§a! -notAssigned: §cNo asignado -unassigned: §a¡La parcela ha sido desasignada! -minPlotID: §c¡El ID de parcela mínimo es %min_id%! -maxPlotID: §c¡El ID máximo de la parcela es %max_id%! -cmdOnlyPlayers: §c¡Comando sólo para jugadores! -enteredAvailablePlot: §2¡Has entrado en una parcela disponible! -enteredOwnedPlot: §7¡Has entrado en la parcela de §2%owner%§7! -leftAvailablePlot: §c¡Has salido de una parcela disponible! -leftOwnedPlot: §7¡Has salido de la parcela de §2%owner%§7! -cantInteract: §c¡No puedes interactuar aquí! -cantBuildHere: §c¡No puedes construir aquí! -cantRideOnPlot: §c¡No puedes montar entidades en la parcela de alguien más! -creationPlotComponent1: '§a¡Parcela ' -creationPlotComponent2: §8#§7%plot_id% -creationPlotComponent3: ' §aha sido creada! §8(§7%creation_time% ms§8)' -cantAddYourself: §c¡No puedes añadirte tu mismo a la parecela! -cantKickYourself: §cNo puedes salirte de la parcela. -alreadyInMembers: §c¡Este jugador ya es miembro de la parcela! -notInMembers: §c¡Este jugador no es miembro de la parcela! -cantDoAnyDMG: §c¡No puedes hacer daño aquí! -playerKick: §a¡El jugador §7%player% §aha sido expulsado de tu parcela! -playerAdd: §a¡El jugador §7%player% §aha sido añadido a tu parcela! -gamemodeSwitched: §aEl modo de juego ya está seleccionado. -gamemodeAlreadySelected: §cEste modo de juego ya está seleccionado. \ No newline at end of file diff --git a/src/main/resources/messages_pl_PL.yml b/src/main/resources/messages_pl_PL.yml deleted file mode 100644 index e18e3b0..0000000 --- a/src/main/resources/messages_pl_PL.yml +++ /dev/null @@ -1,64 +0,0 @@ -useNaturalNumbersOnly: §cUżywaj tylko liczb naturalnych! -noPlotFound: §cNie można uzyskać działki o podanym ID! -notYourPlot: §cTo nie jest twoja działka! -ownershipExpired: §cTwoje prawo własności wygasło! -teleportedToPlot: §aZostałeś teleportowany na działkę! -gamemodeFeatureDisabled: §cFunkcja zmiany trybu gry jest wyłączona! -incorrectGamemode: §cNieprawidłowa wartość trybu gry! -gamemodeDisabled: §cTen tryb gry jest wyłączony! -cantSwitchGamemode: §cNie możesz tu zmienić trybu! -creativeIsEnabled: §cTryb kreatywny jest już włączony! -creativeIsDisabled: §cTryb kreatywny jest już wyłączony! -creativeEnabled: §aTryb kreatywny został włączony! -creativeDisabled: §eTryb kreatywny został wyłączony! -notStandingOnPlot: §cNie stoisz na żadnej z działek! -assignedByConsole: §eKonsola -assignedByShopPurchase: §eZakup w Sklepie -noPlots: §cNie ma żadnych działek! -available: §cDostępny -reloadCompleted: §aPomyślnie przeładowano! -cantCreateOnExisting: §cNie można utworzyć nowej działki na istniejącej działce! -cantGetFloorMaterial: §cNie udało się znaleźć materiału podłogowego o podanej nazwie! -cantGetBorderMaterial: §cNie udało się znaleźć materiału granicznego o podanej nazwie! -cantGetMaterial: §cNie udało sie znaleźć materiału z podaną nazwą! -notCollidingCreating: §aTworzenie działki... -clickToShowDetailedInfo: '§a§oClick to show detailed information about the plot! §8(§7ID: - §f%plot_id%§8)' -sizeNotRecognised: §cNie rozpoznano rozmiaru! -LWHHardLimit: §cTwardy limit dla L, W i H to 500! -removedPlot: §aPomyślnie usunięto działkę! -specifyUsername: §cPodaj nazwe użytkownika! -playerNotFoundWithUsername: §cCouldn't find player with specified username! -invalidDateProvided: §cPodano nieprawidłowy format daty! -assignedTo: §aDziałka została przypisana do §f%assigned_to%! -specifyMaterialName: §cOkreśl nazwę materiału! -specifyExpiryDate: §cOkreśl datę ważności! -newFloorMaterialSet: §aUstawiono nowy materiał podłogowy! -newBorderMaterialSet: §aUstawiono nowy materiał graniczny! -ownedUntilUpdated: §aData wygaśnięcia własności została zaktualizowana! -assignedToBy: §aDziałka została przypisana do §f%assigned_to% §aprzez §f%assigned_by%! -notAssigned: §cNieprzypisane -unassigned: §aDziałka została zwolniona! -minPlotID: §cMinimalne ID działki to %min_id%! -maxPlotID: §cMaksymalne ID działki to %max_id%! -cmdOnlyPlayers: §cKomenda tylko dla graczy! -enteredAvailablePlot: §2Wszedłeś na wolną działke! -enteredOwnedPlot: §7Wszedłeś na działke gracza §2%owner%! -leftAvailablePlot: §cOpuściłeś wolną działke! -leftOwnedPlot: §7Opuściłeś działke gracza §2%owner%! -cantInteract: §cNie możesz tutaj tego robić! -cantBuildHere: §cNie możesz tutaj budować! -cantBuildThere: §cNie możesz tam budować! -cantRideOnPlot: §cNie możesz jeździć na czyjejś działce! -creationPlotComponent1: '§aDziałka ' -creationPlotComponent2: §8#§7%plot_id% -creationPlotComponent3: ' §azostała stworzona! §8(§7%creation_time% ms§8)' -cantAddYourself: §cNie możesz dodać siebie do działki! -cantKickYourself: §cNie możesz wyrzucić siebie z działki! -alreadyInMembers: §cTen gracz jest już jednym z członków działki! -notInMembers: §cTen gracz nie jest członkiem twojej działki! -cantDoAnyDMG: §cNie możesz tutaj zdawać żadnych obrażeń! -playerKick: §aGracz §7%player% §azostał wyrzucony z działki! -playerAdd: §aGracz §7%player% §azostał dodany do działki! -gamemodeSwitched: §aTwój tryb gry się zmienił! -gamemodeAlreadySelected: §cTen tryb gry jest już wybrany! \ No newline at end of file From d68f9958e4ae290761ba9efeb3e959320c965870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Cichocki?= Date: Tue, 8 Mar 2022 13:20:38 +0100 Subject: [PATCH 23/23] Update --- pom.xml | 2 +- .../modnmetl/virtualrealty/VirtualRealty.java | 9 ++--- .../commands/CommandManager.java | 3 ++ .../commands/plot/PlotCommand.java | 4 +-- .../plot/subcommand/TpSubCommand.java | 4 +-- .../vrplot/subcommand/CreateSubCommand.java | 13 ++++--- .../vrplot/subcommand/InfoSubCommand.java | 4 +-- .../vrplot/subcommand/TpSubCommand.java | 4 +-- .../virtualrealty/managers/PlotManager.java | 2 +- .../modnmetl/virtualrealty/objects/Plot.java | 34 ++++++++++++++++--- .../virtualrealty/objects/region/Cuboid.java | 4 +++ .../virtualrealty/utils/data/SkullUtil.java | 30 ++++++++++++++++ 12 files changed, 86 insertions(+), 27 deletions(-) diff --git a/pom.xml b/pom.xml index 1416b96..10932cb 100644 --- a/pom.xml +++ b/pom.xml @@ -175,7 +175,7 @@ de.tr7zw item-nbt-api-plugin - 2.9.1 + 2.9.2 compile diff --git a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java index 2c717de..3928e86 100644 --- a/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java +++ b/src/main/java/com/modnmetl/virtualrealty/VirtualRealty.java @@ -212,22 +212,19 @@ private void runLoader(String licenseKey, String licenseEmail, String pluginVers Gson gson = new Gson(); JsonObject jsonObject = new JsonObject(); -// jsonObject.addProperty("license", licenseKey); -// jsonObject.addProperty("email", licenseEmail); -// jsonObject.addProperty("version", pluginVersion); jsonObject.addProperty("id", "62110bdbf58570001812deb8"); - jsonObject.addProperty("key", "cVvW6fuGV5a6Mbm7nWlXSC4m0J5cazYz"); + jsonObject.addProperty("key", licenseKey); + jsonObject.addProperty("email", licenseEmail); jsonObject.addProperty("version", pluginVersion); String data = gson.toJson(jsonObject); byte[] out = data.getBytes(StandardCharsets.UTF_8); OutputStream stream = httpConn.getOutputStream(); stream.write(out); - System.out.println(httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); int responseCode = httpConn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { - debug("Authentication error"); + debug("Authentication error | " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); return; } try (InputStream in = httpConn.getInputStream()) { diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java b/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java index 87bb0ed..49cf771 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/CommandManager.java @@ -59,6 +59,9 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman } } } + boolean isNatural = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--natural")); + args = Arrays.stream(args).filter(s1 -> !s1.equalsIgnoreCase("--natural")).toArray(String[]::new); + if (isNatural) return null; if (args.length > 2) { boolean predefinedValue = EnumUtils.isValidEnum(PlotSize.class, args[1].toUpperCase()); if ((predefinedValue && args.length < 5) || (!predefinedValue && args.length > 4 && args.length < 7)) { diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java index 53abb2b..3495249 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/PlotCommand.java @@ -18,8 +18,8 @@ public class PlotCommand implements CommandExecutor { HELP_LIST.add(" "); HELP_LIST.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); HELP_LIST.add(" §a/plot panel §8- §7Opens your plots panel"); - HELP_LIST.add(" §a/plot draft §8- §7Enables draft mode"); - HELP_LIST.add(" §a/plot stake §8- §7Creates a plot when not colliding"); + HELP_LIST.add(" §a/plot draft §8- §7Shows layout of potential new plot"); + HELP_LIST.add(" §a/plot stake §8- §7Creates the plot shown with draft"); HELP_LIST.add(" §a/plot info §8- §7Shows plot info"); HELP_LIST.add(" §a/plot gm §8- §7Changes gamemode"); HELP_LIST.add(" §a/plot add §8- §7Adds a member"); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java index 62043ce..6dd15fd 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/plot/subcommand/TpSubCommand.java @@ -55,9 +55,7 @@ public void exec(CommandSender sender, Command command, String label, String[] a sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().ownershipExpired); return; } - Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); - loc.setY(Objects.requireNonNull(loc.getWorld()).getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); - player.teleport(loc); + plot.teleportPlayer(player); sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); } diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java index 48ec357..631e88b 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/CreateSubCommand.java @@ -7,6 +7,7 @@ import com.modnmetl.virtualrealty.exceptions.FailedCommandException; import com.modnmetl.virtualrealty.managers.PlotManager; import com.modnmetl.virtualrealty.objects.Plot; +import com.modnmetl.virtualrealty.objects.region.Cuboid; import com.modnmetl.virtualrealty.objects.region.GridStructure; import com.modnmetl.virtualrealty.utils.RegionUtil; import com.modnmetl.virtualrealty.utils.multiversion.Chat; @@ -34,8 +35,8 @@ public class CreateSubCommand extends SubCommand { static { HELP.add(" "); HELP.add(" §8§l«§8§m §8[§aVirtualRealty§8]§m §8§l»"); - HELP.add(" §a/vrplot create §8<§7small/medium/large/area§8> §8<§7floor (optional)§8> §8<§7border (optional)§8>"); - HELP.add(" §a/vrplot create §8<§7length§8> §8<§7height§8> §8<§7width§8> §8<§7floor (optional)§8> §8<§7border (optional)§8>"); + HELP.add(" §a/vrplot create §8<§7small/medium/large/area§8> §8<§7floor (optional)§8> §8<§7border (optional)§8> §8<§7--natural(optional)§8>"); + HELP.add(" §a/vrplot create §8<§7length§8> §8<§7height§8> §8<§7width§8> §8<§7floor (optional)§8> §8<§7border (optional)§8> §8<§7--natural(optional)§8>"); } public CreateSubCommand(CommandSender sender, Command command, String label, String[] args) throws FailedCommandException { @@ -59,7 +60,8 @@ public void exec(CommandSender sender, Command command, String label, String[] a plotSize = PlotSize.valueOf(args[1].toUpperCase()); } catch (IllegalArgumentException ignored) {} if (plotSize != null) { - if (PlotManager.isColliding(RegionUtil.getRegion(location, Direction.byYaw(location.getYaw()), plotSize.getLength(), plotSize.getHeight(), plotSize.getWidth()))) { + Cuboid cuboid = RegionUtil.getRegion(location, Direction.byYaw(location.getYaw()), plotSize.getLength(), plotSize.getHeight(), plotSize.getWidth()); + if (PlotManager.isColliding(cuboid) || PlotManager.getPlot(player.getLocation()) != null) { sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); } else { boolean natural = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--natural")); @@ -131,8 +133,8 @@ public void run() { } } else { int length; - int width; int height; + int width; try { length = Integer.parseInt(args[1]); height = Integer.parseInt(args[2]); @@ -145,7 +147,8 @@ public void run() { sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().LHWHardLimit); return; } - if (PlotManager.isColliding(RegionUtil.getRegion(location, Direction.byYaw(location.getYaw()), length, height, width))) { + Cuboid cuboid = RegionUtil.getRegion(location, Direction.byYaw(location.getYaw()), length, height, width); + if (PlotManager.isColliding(cuboid) || PlotManager.getPlot(player.getLocation()) != null) { sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().cantCreateOnExisting); } else { boolean natural = Arrays.stream(args).anyMatch(s -> s.equalsIgnoreCase("--natural")); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java index b244e83..c51a3d9 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/InfoSubCommand.java @@ -100,8 +100,8 @@ private void printInfo(CommandSender sender, Plot plot) { sender.sendMessage(" §7Length §8§l‣ §f" + plot.getLength()); sender.sendMessage(" §7Height §8§l‣ §f" + plot.getHeight()); sender.sendMessage(" §7Width §8§l‣ §f" + plot.getWidth()); - sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterial().name()); - sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterial().name()); + sender.sendMessage(" §7Floor Material §8§l‣ §f" + plot.getFloorMaterialName()); + sender.sendMessage(" §7Border Material §8§l‣ §f" + plot.getBorderMaterialName()); sender.sendMessage(" §7Pos 1 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getBottomLeftCorner().toString()); sender.sendMessage(" §7Pos 2 §8( §7X §8| §7Y §8| §7Z §8) §8§l‣ §f" + plot.getTopRightCorner().toString()); sender.sendMessage(" §7Created Direction §8§l‣ §f" + plot.getCreatedDirection().name()); diff --git a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java index 8eda0bf..73ce292 100644 --- a/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java +++ b/src/main/java/com/modnmetl/virtualrealty/commands/vrplot/subcommand/TpSubCommand.java @@ -49,9 +49,7 @@ public void exec(CommandSender sender, Command command, String label, String[] a sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().noPlotFound); return; } - Location loc = new Location(plot.getCreatedLocation().getWorld(), plot.getCenter().getBlockX(), plot.getCenter().getBlockY() + 1, plot.getCenter().getBlockZ()); - loc.setY(loc.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); - player.teleport(loc); + plot.teleportPlayer(player); sender.sendMessage(VirtualRealty.PREFIX + VirtualRealty.getMessages().teleportedToPlot); } diff --git a/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java b/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java index 4994e95..d90bd83 100644 --- a/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java +++ b/src/main/java/com/modnmetl/virtualrealty/managers/PlotManager.java @@ -143,7 +143,7 @@ public static boolean isColliding(Cuboid newPlot) { Cuboid region = new Cuboid(plot.getBorderBottomLeftCorner(), plot.getBorderTopRightCorner(), plot.getCreatedLocation().getWorld()); for (BlockVector2 vector2 : region.getWalls()) { if (vector2.containedWithin(newPlot.getMinimumPoint(), newPlot.getMaximumPoint())) { - return true; + return plot.getCreatedWorldString().equals(newPlot.getWorld().getName()); } } } diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java b/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java index 3bf0d40..f809421 100644 --- a/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java +++ b/src/main/java/com/modnmetl/virtualrealty/objects/Plot.java @@ -17,6 +17,7 @@ import lombok.SneakyThrows; import org.bukkit.*; import org.bukkit.block.Block; +import org.bukkit.entity.Player; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -61,10 +62,17 @@ public Plot(Location location, Material floorMaterial, Material borderMaterial, this.nonMemberPermissions = new HashSet<>(VirtualRealty.getPermissions().getDefaultNonMemberPlotPerms()); this.assignedBy = null; this.ownedUntilDate = MAX_DATE; - this.floorMaterial = floorMaterial; - this.floorData = 0; - this.borderMaterial = borderMaterial; - this.borderData = 0; + if (natural) { + this.floorMaterial = Material.AIR; + this.floorData = 0; + this.borderMaterial = Material.AIR; + this.borderData = 0; + } else { + this.floorMaterial = floorMaterial; + this.floorData = 0; + this.borderMaterial = borderMaterial; + this.borderData = 0; + } this.createdLocation = location; this.createdDirection = Direction.byYaw(location.getYaw()); this.selectedGameMode = VirtualRealty.getPluginConfiguration().getDefaultPlotGamemode(); @@ -135,6 +143,24 @@ public Plot(ResultSet rs) { prepareCorners(); } + public String getFloorMaterialName() { + if (this.floorMaterial == Material.AIR) return "NONE"; + return this.floorMaterial.name(); + } + + public String getBorderMaterialName() { + if (this.borderMaterial == Material.AIR) return "NONE"; + return this.borderMaterial.name(); + } + + public void teleportPlayer(Player player) { + Location loc = new Location(createdLocation.getWorld(), getCenter().getBlockX(), getCenter().getBlockY() + 1, getCenter().getBlockZ()); + if (!createdLocation.getWorld().getName().endsWith("_nether")) { + loc.setY(Objects.requireNonNull(loc.getWorld()).getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()).getY() + 1); + } + player.teleport(loc); + } + public boolean hasMembershipAccess(UUID uuid) { PlotMember member = getMember(uuid); if (member != null || (ownedBy != null && getPlotOwner().getUniqueId() == uuid)) return true; diff --git a/src/main/java/com/modnmetl/virtualrealty/objects/region/Cuboid.java b/src/main/java/com/modnmetl/virtualrealty/objects/region/Cuboid.java index 4aec481..88d72ba 100644 --- a/src/main/java/com/modnmetl/virtualrealty/objects/region/Cuboid.java +++ b/src/main/java/com/modnmetl/virtualrealty/objects/region/Cuboid.java @@ -185,4 +185,8 @@ public List getWalls() { return walls; } + public World getWorld() { + return world; + } + } diff --git a/src/main/java/com/modnmetl/virtualrealty/utils/data/SkullUtil.java b/src/main/java/com/modnmetl/virtualrealty/utils/data/SkullUtil.java index 210971f..3d11ce8 100644 --- a/src/main/java/com/modnmetl/virtualrealty/utils/data/SkullUtil.java +++ b/src/main/java/com/modnmetl/virtualrealty/utils/data/SkullUtil.java @@ -43,4 +43,34 @@ public static ItemStack getSkull(String url) { return skull; } + + public static ItemStack getSkull(String url, UUID uuid) { + ItemStack skull; + if (VirtualRealty.legacyVersion) { + skull = new ItemStack(VMaterial.getMaterial("SKULL_ITEM"), 1, (short) 3); + } else { + skull = new ItemStack(Material.PLAYER_HEAD, 1, (short) 3); + } + if (url == null || url.isEmpty()) + return skull; + SkullMeta skullMeta = (SkullMeta) skull.getItemMeta(); + GameProfile profile = new GameProfile(uuid, null); + byte[] encodedData = Base64.getEncoder().encode(String.format("{textures:{SKIN:{url:\"%s\"}}}", "http://textures.minecraft.net/texture/" + url).getBytes()); + profile.getProperties().put("textures", new Property("textures", new String(encodedData))); + Field profileField = null; + try { + profileField = skullMeta.getClass().getDeclaredField("profile"); + } catch (NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } + profileField.setAccessible(true); + try { + profileField.set(skullMeta, profile); + } catch (IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); + } + skull.setItemMeta(skullMeta); + return skull; + } + }