From 6dba31b257170ceda73afac49fe28def7f4f9f0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Tue, 21 Jul 2020 14:28:54 +0200 Subject: [PATCH 01/25] Start working on the new permission system --- .../plotsquared/bukkit/BukkitPlatform.java | 10 +- .../bukkit/inject/PermissionModule.java | 52 +++++++++ .../permissions/BukkitPermissionHandler.java | 84 +++++++++++++++ .../permissions/VaultPermissionHandler.java | 102 ++++++++++++++++++ .../bukkit/player/BukkitOfflinePlayer.java | 14 ++- .../bukkit/player/BukkitPlayer.java | 22 ++-- .../bukkit/player/BukkitPlayerManager.java | 14 ++- .../plotsquared/bukkit/util/BukkitUtil.java | 2 +- .../com/plotsquared/core/PlotPlatform.java | 10 ++ .../permissions/ConsolePermissionProfile.java | 37 +++++++ .../permissions/NullPermissionProfile.java | 37 +++++++ .../core/permissions/PermissionHandler.java | 95 ++++++++++++++++ .../core/permissions/PermissionHolder.java | 43 ++++++++ .../core/permissions/PermissionProfile.java | 43 ++++++++ .../core/player/ConsolePlayer.java | 14 ++- .../core/player/OfflinePlotPlayer.java | 5 +- .../plotsquared/core/player/PlotPlayer.java | 17 ++- .../com/plotsquared/core/util/ChunkUtil.java | 25 +++++ .../com/plotsquared/core/util/MainUtil.java | 47 ++++++++ 19 files changed, 638 insertions(+), 35 deletions(-) create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index 01cf8114e..d83813d14 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -33,6 +33,7 @@ import com.google.inject.Stage; import com.plotsquared.bukkit.generator.BukkitPlotGenerator; import com.plotsquared.bukkit.inject.BackupModule; import com.plotsquared.bukkit.inject.BukkitModule; +import com.plotsquared.bukkit.inject.PermissionModule; import com.plotsquared.bukkit.inject.WorldManagerModule; import com.plotsquared.bukkit.listener.ChunkListener; import com.plotsquared.bukkit.listener.EntitySpawnListener; @@ -245,8 +246,11 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; // We create the injector after PlotSquared has been initialized, so that we have access // to generated instances and settings - this.injector = Guice.createInjector(Stage.PRODUCTION, new WorldManagerModule(), new PlotSquaredModule(), - new BukkitModule(this), new BackupModule()); + this.injector = Guice.createInjector(Stage.PRODUCTION, new PermissionModule(), + new WorldManagerModule(), + new PlotSquaredModule(), + new BukkitModule(this), + new BackupModule()); this.injector.injectMembers(this); if (PremiumVerification.isPremium() && Settings.Enabled_Components.UPDATE_NOTIFICATIONS) { @@ -1140,7 +1144,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; return names; } - @Override public com.plotsquared.core.location.World getPlatformWorld(@Nonnull final String worldName) { + @Override @Nonnull public com.plotsquared.core.location.World getPlatformWorld(@Nonnull final String worldName) { return BukkitWorld.of(worldName); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java new file mode 100644 index 000000000..b22cb3648 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java @@ -0,0 +1,52 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.bukkit.inject; + +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.Singleton; +import com.plotsquared.bukkit.permissions.BukkitPermissionHandler; +import com.plotsquared.bukkit.permissions.VaultPermissionHandler; +import com.plotsquared.core.permissions.PermissionHandler; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; +import org.bukkit.plugin.RegisteredServiceProvider; + +public class PermissionModule extends AbstractModule { + + @Provides @Singleton PermissionHandler providePermissionHandler() { + try { + RegisteredServiceProvider permissionProvider = + Bukkit.getServer().getServicesManager().getRegistration(Permission.class); + if (permissionProvider != null) { + return new VaultPermissionHandler(); + } + } catch (final Exception ignored) { + } + return new BukkitPermissionHandler(); + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java new file mode 100644 index 000000000..bceecda3e --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java @@ -0,0 +1,84 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.bukkit.permissions; + +import com.plotsquared.bukkit.player.BukkitPlayer; +import com.plotsquared.core.permissions.ConsolePermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; +import com.plotsquared.core.permissions.PermissionProfile; +import com.plotsquared.core.player.ConsolePlayer; +import com.plotsquared.core.player.OfflinePlotPlayer; +import com.plotsquared.core.player.PlotPlayer; +import org.bukkit.entity.Player; + +import javax.annotation.Nonnull; +import java.lang.ref.WeakReference; +import java.util.EnumSet; +import java.util.Optional; +import java.util.Set; + +public class BukkitPermissionHandler implements PermissionHandler { + + @Override public void initialize() { + } + + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull PlotPlayer playerPlotPlayer) { + if (playerPlotPlayer instanceof BukkitPlayer) { + final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; + return Optional.of(new BukkitPermissionProfile(bukkitPlayer.getPlatformPlayer())); + } else if (playerPlotPlayer instanceof ConsolePlayer) { + return Optional.of(ConsolePermissionProfile.INSTANCE); + } + return Optional.empty(); + } + + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull OfflinePlotPlayer offlinePlotPlayer) { + return Optional.empty(); + } + + @Nonnull @Override public Set getCapabilities() { + return EnumSet.of(PermissionHandlerCapability.ONLINE_PERMISSIONS); + } + + + private static final class BukkitPermissionProfile implements PermissionProfile { + + private final WeakReference playerReference; + + private BukkitPermissionProfile(@Nonnull final Player player) { + this.playerReference = new WeakReference<>(player); + } + + @Override public boolean hasPermission(@Nonnull final String permission) { + final Player player = this.playerReference.get(); + return player != null && player.hasPermission(permission); + } + + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java new file mode 100644 index 000000000..a7978e671 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java @@ -0,0 +1,102 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.bukkit.permissions; + +import com.plotsquared.bukkit.player.BukkitOfflinePlayer; +import com.plotsquared.bukkit.player.BukkitPlayer; +import com.plotsquared.core.permissions.ConsolePermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; +import com.plotsquared.core.permissions.PermissionProfile; +import com.plotsquared.core.player.ConsolePlayer; +import com.plotsquared.core.player.OfflinePlotPlayer; +import com.plotsquared.core.player.PlotPlayer; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.plugin.RegisteredServiceProvider; + +import javax.annotation.Nonnull; +import java.util.EnumSet; +import java.util.Optional; +import java.util.Set; + +public class VaultPermissionHandler implements PermissionHandler { + + private Permission permissions; + + @Override public void initialize() { + if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { + throw new IllegalStateException("Vault is not present on the server"); + } + RegisteredServiceProvider permissionProvider = + Bukkit.getServer().getServicesManager().getRegistration(Permission.class); + if (permissionProvider != null) { + this.permissions = permissionProvider.getProvider(); + } + } + + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull PlotPlayer playerPlotPlayer) { + if (playerPlotPlayer instanceof BukkitPlayer) { + final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; + return Optional.of(new VaultPermissionProfile(bukkitPlayer.getPlatformPlayer())); + } else if (playerPlotPlayer instanceof ConsolePlayer) { + return Optional.of(ConsolePermissionProfile.INSTANCE); + } + return Optional.empty(); + } + + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull OfflinePlotPlayer offlinePlotPlayer) { + if (offlinePlotPlayer instanceof BukkitOfflinePlayer) { + return Optional.of(new VaultPermissionProfile(((BukkitOfflinePlayer) offlinePlotPlayer).player)); + } + return Optional.empty(); + } + + @Nonnull @Override public Set getCapabilities() { + return EnumSet.of(PermissionHandlerCapability.ONLINE_PERMISSIONS, PermissionHandlerCapability.OFFLINE_PERMISSIONS); + } + + + private final class VaultPermissionProfile implements PermissionProfile { + + private final OfflinePlayer offlinePlayer; + + private VaultPermissionProfile(@Nonnull final OfflinePlayer offlinePlayer) { + this.offlinePlayer = offlinePlayer; + } + + @Override public boolean hasPermission(@Nonnull final String permission) { + if (permissions == null) { + return false; + } + return permissions.playerHas(null, offlinePlayer, permission); + } + + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java index 3aa5d12c3..e9c74dfb9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java @@ -25,6 +25,9 @@ */ package com.plotsquared.bukkit.player; +import com.plotsquared.core.permissions.NullPermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; +import com.plotsquared.core.permissions.PermissionProfile; import com.plotsquared.core.player.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; import javax.annotation.Nonnull; @@ -34,6 +37,7 @@ import java.util.UUID; public class BukkitOfflinePlayer implements OfflinePlotPlayer { public final OfflinePlayer player; + private final PermissionProfile permissionProfile; /** * Please do not use this method. Instead use BukkitUtil.getPlayer(Player), @@ -41,8 +45,11 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { * * @param player */ - public BukkitOfflinePlayer(OfflinePlayer player) { + public BukkitOfflinePlayer(@Nonnull final OfflinePlayer player, @Nonnull final + PermissionHandler permissionHandler) { this.player = player; + this.permissionProfile = permissionHandler.getPermissionProfile(this) + .orElse(NullPermissionProfile.INSTANCE); } @Nonnull @Override public UUID getUUID() { @@ -60,4 +67,9 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { @Override public String getName() { return this.player.getName(); } + + @Override public boolean hasPermission(@Nonnull final String permission) { + return this.permissionProfile.hasPermission(permission); + } + } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java index 15d9bacf8..0fcc50fb0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java @@ -32,6 +32,7 @@ import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.location.Location; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.PlotWeather; import com.plotsquared.core.plot.world.PlotAreaManager; @@ -83,19 +84,21 @@ public class BukkitPlayer extends PlotPlayer { * @param player Bukkit player instance */ public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, - @Nonnull final Player player, @Nullable final EconHandler econHandler) { - this(plotAreaManager, eventDispatcher, player, false, econHandler); + @Nonnull final Player player, @Nullable final EconHandler econHandler, @Nonnull final PermissionHandler permissionHandler) { + this(plotAreaManager, eventDispatcher, player, false, econHandler, permissionHandler); } public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, - @Nonnull final Player player, final boolean offline, @Nullable final EconHandler econHandler) { - this(plotAreaManager, eventDispatcher, player, offline, true, econHandler); + @Nonnull final Player player, final boolean offline, @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { + this(plotAreaManager, eventDispatcher, player, offline, true, econHandler, permissionHandler); } public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, @Nonnull final Player player, final boolean offline, - final boolean realPlayer, @Nullable final EconHandler econHandler) { - super(plotAreaManager, eventDispatcher, econHandler); + final boolean realPlayer, @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { + super(plotAreaManager, eventDispatcher, econHandler, permissionHandler); this.player = player; this.offline = offline; this.econHandler = econHandler; @@ -161,13 +164,6 @@ public class BukkitPlayer extends PlotPlayer { } } - @Override public boolean hasPermission(final String permission) { - if (this.offline && this.econHandler != null) { - return this.econHandler.hasPermission(getName(), permission); - } - return this.player.hasPermission(permission); - } - @Override public int hasPermissionRange(final String stub, final int range) { if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { return Integer.MAX_VALUE; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java index 7238709e3..d05fafd7a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java @@ -27,6 +27,7 @@ package com.plotsquared.bukkit.player; import com.google.inject.Inject; import com.google.inject.Singleton; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EventDispatcher; @@ -46,13 +47,16 @@ import java.util.UUID; private final PlotAreaManager plotAreaManager; private final EventDispatcher eventDispatcher; private final EconHandler econHandler; + private final PermissionHandler permissionHandler; @Inject public BukkitPlayerManager(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, - @Nullable final EconHandler econHandler) { + @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { this.plotAreaManager = plotAreaManager; this.eventDispatcher = eventDispatcher; this.econHandler = econHandler; + this.permissionHandler = permissionHandler; } @Nonnull @Override public BukkitPlayer getPlayer(@Nonnull final Player object) { @@ -60,7 +64,7 @@ import java.util.UUID; return getPlayer(object.getUniqueId()); } catch (final NoSuchPlayerException exception) { return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, object, - object.isOnline(), false, this.econHandler); + object.isOnline(), false, this.econHandler, this.permissionHandler); } } @@ -69,18 +73,18 @@ import java.util.UUID; if (player == null || !player.isOnline()) { throw new NoSuchPlayerException(uuid); } - return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, player, this.econHandler); + return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, player, this.econHandler, this.permissionHandler); } @Nullable @Override public BukkitOfflinePlayer getOfflinePlayer(@Nullable final UUID uuid) { if (uuid == null) { return null; } - return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid)); + return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid), this.permissionHandler); } @Nonnull @Override public BukkitOfflinePlayer getOfflinePlayer(@Nonnull final String username) { - return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(username)); + return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(username), this.permissionHandler); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 5cbbf6cfc..1d88f9a6f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -131,7 +131,7 @@ import java.util.stream.Stream; final Player player = OfflinePlayerUtil.loadPlayer(op); player.loadData(); return new BukkitPlayer(PlotSquared.get().getPlotAreaManager(), - PlotSquared.get().getEventDispatcher(), player, true, PlotSquared.platform().getEconHandler()); + PlotSquared.get().getEventDispatcher(), player, true, PlotSquared.platform().getEconHandler(), PlotSquared.platform().getPermissionHandler()); } /** diff --git a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java index dc3136372..c84bce2b9 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java +++ b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java @@ -33,6 +33,7 @@ import com.plotsquared.core.generator.HybridUtils; import com.plotsquared.core.generator.IndependentPlotGenerator; import com.plotsquared.core.inject.annotations.DefaultGenerator; import com.plotsquared.core.location.World; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.util.ChatManager; @@ -266,4 +267,13 @@ public interface PlotPlatform

extends ILogger { return getInjector().getInstance(ChunkManager.class); } + /** + * Get the {@link PermissionHandler} implementation for the platform + * + * @return Permission handler + */ + @Nonnull default PermissionHandler getPermissionHandler() { + return getInjector().getInstance(PermissionHandler.class); + } + } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java new file mode 100644 index 000000000..09857628c --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java @@ -0,0 +1,37 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import javax.annotation.Nonnull; + +public enum ConsolePermissionProfile implements PermissionProfile { + INSTANCE; + + @Override public boolean hasPermission(@Nonnull final String permission) { + return true; + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java new file mode 100644 index 000000000..b59b5a78d --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java @@ -0,0 +1,37 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import javax.annotation.Nonnull; + +public enum NullPermissionProfile implements PermissionProfile { + INSTANCE; + + @Override public boolean hasPermission(@Nonnull final String permission) { + return false; + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java new file mode 100644 index 000000000..c88537f69 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java @@ -0,0 +1,95 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import com.plotsquared.core.player.OfflinePlotPlayer; +import com.plotsquared.core.player.PlotPlayer; + +import javax.annotation.Nonnull; +import java.util.Optional; +import java.util.Set; + +/** + * Permission handler + */ +public interface PermissionHandler { + + /** + * Initialize the permission handler + */ + void initialize(); + + /** + * Attempt to construct a permission profile for a plot player + * + * @param playerPlotPlayer Plot player + * @return Permission profile, if one was able to be constructed + */ + @Nonnull Optional getPermissionProfile( + @Nonnull PlotPlayer playerPlotPlayer); + + /** + * Attempt to construct a permission profile for an offline plot player + * + * @param offlinePlotPlayer Offline player + * @return Permission profile, if one was able to be constructed + */ + @Nonnull Optional getPermissionProfile( + @Nonnull OfflinePlotPlayer offlinePlotPlayer); + + /** + * Get all capabilities that the permission handler has + * + * @return Immutable set of capabilities + */ + @Nonnull Set getCapabilities(); + + /** + * Check whether or not the permission handler has a given capability + * + * @param capability Capability + * @return {@code true} if the handler has the capability, else {@code false} + */ + default boolean hasCapability(@Nonnull final PermissionHandlerCapability capability) { + return this.getCapabilities().contains(capability); + } + + + /** + * Permission handler capabilities + */ + enum PermissionHandlerCapability { + /** + * The ability to check for online (player) permissions + */ + ONLINE_PERMISSIONS, + /** + * The ability to check for offline (player) permissions + */ + OFFLINE_PERMISSIONS + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java new file mode 100644 index 000000000..a94bd0b39 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java @@ -0,0 +1,43 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import javax.annotation.Nonnull; + +/** + * Any object which can hold permissions + */ +public interface PermissionHolder { + + /** + * Check if the permission holder has the given permission node + * + * @param permission Permission node + * @return {@code true} if the holder has the given permission node, else {@code false} + */ + boolean hasPermission(@Nonnull String permission); + +} diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java new file mode 100644 index 000000000..912147980 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java @@ -0,0 +1,43 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import javax.annotation.Nonnull; + +/** + * A permission profile that can be used to check for permissions + */ +public interface PermissionProfile { + + /** + * Check if the owner of the profile has a given permission + * + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} + */ + boolean hasPermission(@Nonnull String permission); + +} diff --git a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java index c6efe33cd..2c1e67c8f 100644 --- a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java @@ -32,6 +32,7 @@ import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.inject.annotations.ConsoleActor; import com.plotsquared.core.location.Location; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotWeather; import com.plotsquared.core.plot.world.PlotAreaManager; @@ -42,11 +43,11 @@ import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.gamemode.GameModes; import com.sk89q.worldedit.world.item.ItemType; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.UUID; public class ConsolePlayer extends PlotPlayer { @@ -59,8 +60,9 @@ public class ConsolePlayer extends PlotPlayer { @Inject private ConsolePlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, @ConsoleActor @Nonnull final Actor actor, - @Nullable final EconHandler econHandler) { - super(plotAreaManager, eventDispatcher, econHandler); + @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { + super(plotAreaManager, eventDispatcher, econHandler, permissionHandler); this.actor = actor; final PlotArea[] areas = plotAreaManager.getAllPlotAreas(); final PlotArea area; @@ -121,10 +123,6 @@ public class ConsolePlayer extends PlotPlayer { return 0; } - @Override public boolean hasPermission(String permission) { - return true; - } - @Override public boolean isPermissionSet(String permission) { return true; } diff --git a/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java index f48079f67..92a0e6536 100644 --- a/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java @@ -25,9 +25,11 @@ */ package com.plotsquared.core.player; +import com.plotsquared.core.permissions.PermissionHolder; + import java.util.UUID; -public interface OfflinePlotPlayer { +public interface OfflinePlotPlayer extends PermissionHolder { /** * Gets the {@code UUID} of this player @@ -57,4 +59,5 @@ public interface OfflinePlotPlayer { * @return the player name */ String getName(); + } diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index 6d2428d05..d3c4fd369 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -35,6 +35,9 @@ import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.location.Location; +import com.plotsquared.core.permissions.NullPermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; +import com.plotsquared.core.permissions.PermissionProfile; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotCluster; @@ -54,11 +57,11 @@ import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.item.ItemType; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Collections; @@ -95,11 +98,15 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer private final PlotAreaManager plotAreaManager; private final EventDispatcher eventDispatcher; private final EconHandler econHandler; + private final PermissionProfile permissionProfile; - public PlotPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, @Nullable final EconHandler econHandler) { + public PlotPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { this.plotAreaManager = plotAreaManager; this.eventDispatcher = eventDispatcher; this.econHandler = econHandler; + this.permissionProfile = permissionHandler.getPermissionProfile(this).orElse( + NullPermissionProfile.INSTANCE); } public static PlotPlayer from(@Nonnull final T object) { @@ -147,6 +154,10 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return PlotSquared.platform().wrapPlayer(player); } + @Override public final boolean hasPermission(@Nonnull final String permission) { + return this.permissionProfile.hasPermission(permission); + } + public abstract Actor toActor(); public abstract P getPlatformPlayer(); diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java index 3e89c630a..6c1a1415d 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package com.plotsquared.core.util; import lombok.experimental.UtilityClass; diff --git a/Core/src/main/java/com/plotsquared/core/util/MainUtil.java b/Core/src/main/java/com/plotsquared/core/util/MainUtil.java index 2a96b7120..010622813 100644 --- a/Core/src/main/java/com/plotsquared/core/util/MainUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/MainUtil.java @@ -44,6 +44,53 @@ import javax.annotation.Nonnull; private static final Logger logger = LoggerFactory.getLogger("P2/" + MainUtil.class.getSimpleName()); + /** + * Cache of mapping x,y,z coordinates to the chunk array
+ * - Used for efficient world generation
+ */ + public static short[][] x_loc; + public static short[][] y_loc; + public static short[][] z_loc; + public static short[][][] CACHE_I = null; + public static short[][][] CACHE_J = null; + + /** + * This cache is used for world generation and just saves a bit of calculation time when checking if something is in the plot area. + */ + public static void initCache() { + if (x_loc == null) { + x_loc = new short[16][4096]; + y_loc = new short[16][4096]; + z_loc = new short[16][4096]; + for (int i = 0; i < 16; i++) { + int i4 = i << 4; + for (int j = 0; j < 4096; j++) { + int y = i4 + (j >> 8); + int a = j - ((y & 0xF) << 8); + int z1 = a >> 4; + int x1 = a - (z1 << 4); + x_loc[i][j] = (short) x1; + y_loc[i][j] = (short) y; + z_loc[i][j] = (short) z1; + } + } + } + if (CACHE_I == null) { + CACHE_I = new short[256][16][16]; + CACHE_J = new short[256][16][16]; + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = 0; y < 256; y++) { + short i = (short) (y >> 4); + short j = (short) ((y & 0xF) << 8 | z << 4 | x); + CACHE_I[y][x][z] = i; + CACHE_J[y][x][z] = j; + } + } + } + } + } + /** * Send a message to the player. * From 532f2caa37da43252a72b7c2098ce2d5ed3051cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Wed, 22 Jul 2020 12:06:56 +0200 Subject: [PATCH 02/25] Make VaultPermissionHandler extent BukkitPermissionHandler --- .../permissions/VaultPermissionHandler.java | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java index a7978e671..ec2724e6a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java @@ -26,13 +26,8 @@ package com.plotsquared.bukkit.permissions; import com.plotsquared.bukkit.player.BukkitOfflinePlayer; -import com.plotsquared.bukkit.player.BukkitPlayer; -import com.plotsquared.core.permissions.ConsolePermissionProfile; -import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.permissions.PermissionProfile; -import com.plotsquared.core.player.ConsolePlayer; import com.plotsquared.core.player.OfflinePlotPlayer; -import com.plotsquared.core.player.PlotPlayer; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; @@ -43,7 +38,7 @@ import java.util.EnumSet; import java.util.Optional; import java.util.Set; -public class VaultPermissionHandler implements PermissionHandler { +public class VaultPermissionHandler extends BukkitPermissionHandler { private Permission permissions; @@ -58,17 +53,6 @@ public class VaultPermissionHandler implements PermissionHandler { } } - @Nonnull @Override public Optional getPermissionProfile( - @Nonnull PlotPlayer playerPlotPlayer) { - if (playerPlotPlayer instanceof BukkitPlayer) { - final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; - return Optional.of(new VaultPermissionProfile(bukkitPlayer.getPlatformPlayer())); - } else if (playerPlotPlayer instanceof ConsolePlayer) { - return Optional.of(ConsolePermissionProfile.INSTANCE); - } - return Optional.empty(); - } - @Nonnull @Override public Optional getPermissionProfile( @Nonnull OfflinePlotPlayer offlinePlotPlayer) { if (offlinePlotPlayer instanceof BukkitOfflinePlayer) { From 9d6744ec152b2427ac8c981616874b4b376e5028 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Wed, 22 Jul 2020 12:35:48 +0200 Subject: [PATCH 03/25] Get rid of PermHandler --- .../plotsquared/bukkit/BukkitPlatform.java | 7 +-- .../bukkit/inject/BukkitModule.java | 25 ++------ .../bukkit/inject/PermissionModule.java | 6 +- .../permissions/BukkitPermissionHandler.java | 4 +- .../permissions/VaultPermissionHandler.java | 31 ++++++++-- .../bukkit/player/BukkitOfflinePlayer.java | 6 +- .../bukkit/player/BukkitPlayer.java | 9 ++- .../bukkit/util/BukkitEconHandler.java | 23 +------ .../bukkit/util/BukkitPermHandler.java | 60 ------------------- .../com/plotsquared/core/command/Auto.java | 9 ++- .../com/plotsquared/core/command/Command.java | 3 +- .../core/command/CommandCaller.java | 10 +--- .../permissions/ConsolePermissionProfile.java | 4 +- .../permissions/NullPermissionProfile.java | 4 +- .../core/permissions/PermissionHandler.java | 6 +- .../core/permissions/PermissionHolder.java | 59 ++++++++++++++++-- .../core/permissions/PermissionProfile.java | 16 ++++- .../core/player/ConsolePlayer.java | 4 -- .../plotsquared/core/player/PlotPlayer.java | 30 +--------- .../plotsquared/core/util/EconHandler.java | 12 ---- .../plotsquared/core/util/PermHandler.java | 37 ------------ .../plotsquared/core/util/Permissions.java | 27 +++++---- 22 files changed, 152 insertions(+), 240 deletions(-) delete mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java delete mode 100644 Core/src/main/java/com/plotsquared/core/util/PermHandler.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index d83813d14..8a9831f22 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -103,7 +103,6 @@ import com.plotsquared.core.util.ConsoleColors; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.FileUtils; -import com.plotsquared.core.util.PermHandler; import com.plotsquared.core.util.PlatformWorldManager; import com.plotsquared.core.util.PremiumVerification; import com.plotsquared.core.util.ReflectionUtils; @@ -181,7 +180,6 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; private boolean methodUnloadSetup = false; private boolean metricsStarted; private EconHandler econ; - private PermHandler perm; @Getter private Injector injector; @@ -340,10 +338,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; // Economy if (Settings.Enabled_Components.ECONOMY) { TaskManager.runTask(() -> { - final PermHandler permHandler = getInjector().getInstance(PermHandler.class); - if (permHandler != null) { - permHandler.init(); - } + this.getPermissionHandler().initialize(); final EconHandler econHandler = getInjector().getInstance(EconHandler.class); if (econHandler != null) { econHandler.init(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java index b558aee4f..7599358bd 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java @@ -29,7 +29,6 @@ import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.assistedinject.FactoryModuleBuilder; -import com.google.inject.util.Providers; import com.plotsquared.bukkit.BukkitPlatform; import com.plotsquared.bukkit.player.BukkitPlayerManager; import com.plotsquared.bukkit.queue.BukkitLocalQueue; @@ -37,12 +36,9 @@ import com.plotsquared.bukkit.schematic.BukkitSchematicHandler; import com.plotsquared.bukkit.util.BukkitChunkManager; import com.plotsquared.bukkit.util.BukkitEconHandler; import com.plotsquared.bukkit.util.BukkitInventoryUtil; -import com.plotsquared.bukkit.util.BukkitPermHandler; import com.plotsquared.bukkit.util.BukkitRegionManager; import com.plotsquared.bukkit.util.BukkitSetupUtils; import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.bukkit.util.task.PaperTimeConverter; -import com.plotsquared.bukkit.util.task.SpigotTimeConverter; import com.plotsquared.core.PlotPlatform; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.generator.HybridGen; @@ -58,7 +54,6 @@ import com.plotsquared.core.queue.QueueProvider; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.InventoryUtil; -import com.plotsquared.core.util.PermHandler; import com.plotsquared.core.util.PlayerManager; import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.SchematicHandler; @@ -70,7 +65,9 @@ import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.plugin.java.JavaPlugin; + import javax.annotation.Nonnull; +import javax.annotation.Nullable; @RequiredArgsConstructor public class BukkitModule extends AbstractModule { @@ -93,7 +90,6 @@ import javax.annotation.Nonnull; bind(ChunkManager.class).to(BukkitChunkManager.class); bind(RegionManager.class).to(BukkitRegionManager.class); bind(SchematicHandler.class).to(BukkitSchematicHandler.class); - this.setupVault(); if (Settings.Enabled_Components.WORLDS) { bind(PlotAreaManager.class).to(SinglePlotAreaManager.class); } else { @@ -102,25 +98,14 @@ import javax.annotation.Nonnull; install(new FactoryModuleBuilder().build(HybridPlotWorldFactory.class)); } - private void setupVault() { + @Provides @Singleton @Nullable EconHandler provideEconHandler() { if (Bukkit.getPluginManager().isPluginEnabled("Vault")) { - BukkitPermHandler bukkitPermHandler = null; try { - bukkitPermHandler = new BukkitPermHandler(); - bind(PermHandler.class).toInstance(bukkitPermHandler); + return new BukkitEconHandler(); } catch (final Exception ignored) { - bind(PermHandler.class).toProvider(Providers.of(null)); } - try { - final BukkitEconHandler bukkitEconHandler = new BukkitEconHandler(bukkitPermHandler); - bind(EconHandler.class).toInstance(bukkitEconHandler); - } catch (final Exception ignored) { - bind(EconHandler.class).toProvider(Providers.of(null)); - } - } else { - bind(PermHandler.class).toProvider(Providers.of(null)); - bind(EconHandler.class).toProvider(Providers.of(null)); } + return null; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java index b22cb3648..de42d884a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java @@ -31,17 +31,13 @@ import com.google.inject.Singleton; import com.plotsquared.bukkit.permissions.BukkitPermissionHandler; import com.plotsquared.bukkit.permissions.VaultPermissionHandler; import com.plotsquared.core.permissions.PermissionHandler; -import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; -import org.bukkit.plugin.RegisteredServiceProvider; public class PermissionModule extends AbstractModule { @Provides @Singleton PermissionHandler providePermissionHandler() { try { - RegisteredServiceProvider permissionProvider = - Bukkit.getServer().getServicesManager().getRegistration(Permission.class); - if (permissionProvider != null) { + if (Bukkit.getPluginManager().isPluginEnabled("Vault")) { return new VaultPermissionHandler(); } } catch (final Exception ignored) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java index bceecda3e..6aca7ea62 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java @@ -35,6 +35,7 @@ import com.plotsquared.core.player.PlotPlayer; import org.bukkit.entity.Player; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.EnumSet; import java.util.Optional; @@ -74,7 +75,8 @@ public class BukkitPermissionHandler implements PermissionHandler { this.playerReference = new WeakReference<>(player); } - @Override public boolean hasPermission(@Nonnull final String permission) { + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { final Player player = this.playerReference.get(); return player != null && player.hasPermission(permission); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java index ec2724e6a..b7b08a49f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java @@ -26,19 +26,25 @@ package com.plotsquared.bukkit.permissions; import com.plotsquared.bukkit.player.BukkitOfflinePlayer; +import com.plotsquared.bukkit.player.BukkitPlayer; +import com.plotsquared.core.permissions.ConsolePermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.permissions.PermissionProfile; +import com.plotsquared.core.player.ConsolePlayer; import com.plotsquared.core.player.OfflinePlotPlayer; +import com.plotsquared.core.player.PlotPlayer; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.plugin.RegisteredServiceProvider; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.EnumSet; import java.util.Optional; import java.util.Set; -public class VaultPermissionHandler extends BukkitPermissionHandler { +public class VaultPermissionHandler implements PermissionHandler { private Permission permissions; @@ -53,6 +59,17 @@ public class VaultPermissionHandler extends BukkitPermissionHandler { } } + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull PlotPlayer playerPlotPlayer) { + if (playerPlotPlayer instanceof BukkitPlayer) { + final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; + return Optional.of(new VaultPermissionProfile(bukkitPlayer.getPlatformPlayer())); + } else if (playerPlotPlayer instanceof ConsolePlayer) { + return Optional.of(ConsolePermissionProfile.INSTANCE); + } + return Optional.empty(); + } + @Nonnull @Override public Optional getPermissionProfile( @Nonnull OfflinePlotPlayer offlinePlotPlayer) { if (offlinePlotPlayer instanceof BukkitOfflinePlayer) { @@ -62,7 +79,9 @@ public class VaultPermissionHandler extends BukkitPermissionHandler { } @Nonnull @Override public Set getCapabilities() { - return EnumSet.of(PermissionHandlerCapability.ONLINE_PERMISSIONS, PermissionHandlerCapability.OFFLINE_PERMISSIONS); + return EnumSet.of(PermissionHandlerCapability.PER_WORLD_PERMISSIONS, + PermissionHandlerCapability.ONLINE_PERMISSIONS, + PermissionHandlerCapability.OFFLINE_PERMISSIONS); } @@ -74,11 +93,15 @@ public class VaultPermissionHandler extends BukkitPermissionHandler { this.offlinePlayer = offlinePlayer; } - @Override public boolean hasPermission(@Nonnull final String permission) { + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { if (permissions == null) { return false; } - return permissions.playerHas(null, offlinePlayer, permission); + if (world == null && offlinePlayer instanceof BukkitPlayer) { + return permissions.playerHas(((BukkitPlayer) offlinePlayer).getPlatformPlayer(), permission); + } + return permissions.playerHas(world, offlinePlayer, permission); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java index e9c74dfb9..9226c5847 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java @@ -31,6 +31,7 @@ import com.plotsquared.core.permissions.PermissionProfile; import com.plotsquared.core.player.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.UUID; @@ -68,8 +69,9 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { return this.player.getName(); } - @Override public boolean hasPermission(@Nonnull final String permission) { - return this.permissionProfile.hasPermission(permission); + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { + return this.permissionProfile.hasPermission(world, permission); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java index 0fcc50fb0..1415c2840 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java @@ -54,6 +54,8 @@ import org.bukkit.event.EventException; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.RegisteredListener; + +import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -164,7 +166,8 @@ public class BukkitPlayer extends PlotPlayer { } } - @Override public int hasPermissionRange(final String stub, final int range) { + @Override @Nonnegative public int hasPermissionRange(@Nonnull final String stub, + @Nonnegative final int range) { if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { return Integer.MAX_VALUE; } @@ -224,10 +227,6 @@ public class BukkitPlayer extends PlotPlayer { return max; } - @Override public boolean isPermissionSet(final String permission) { - return this.player.isPermissionSet(permission); - } - @Override public void sendMessage(String message) { message = message.replace('\u2010', '%').replace('\u2020', '&').replace('\u2030', '&'); if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || ( diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java index c7356c13b..470fbbfbb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java @@ -25,31 +25,21 @@ */ package com.plotsquared.bukkit.util; -import com.google.inject.Inject; import com.google.inject.Singleton; import com.plotsquared.bukkit.player.BukkitOfflinePlayer; import com.plotsquared.bukkit.player.BukkitPlayer; import com.plotsquared.core.player.OfflinePlotPlayer; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.util.EconHandler; -import com.plotsquared.core.util.PermHandler; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.plugin.RegisteredServiceProvider; -import javax.annotation.Nullable; @Singleton public class BukkitEconHandler extends EconHandler { private Economy econ; - private final PermHandler permHandler; - - @Inject public BukkitEconHandler(@Nullable final PermHandler permHandler) { - this.permHandler = permHandler; - } - - @Override - public boolean init() { + @Override public boolean init() { if (this.econ == null) { setupEconomy(); } @@ -87,17 +77,6 @@ import javax.annotation.Nullable; this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount); } - /** - * @deprecated Use {@link PermHandler#hasPermission(String, String, String)} instead - */ - @Deprecated @Override public boolean hasPermission(String world, String player, String perm) { - if (this.permHandler != null) { - return this.permHandler.hasPermission(world, player, perm); - } else { - return false; - } - } - @Override public double getBalance(PlotPlayer player) { return this.econ.getBalance(player.getName()); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java deleted file mode 100644 index 8987e3527..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.plotsquared.bukkit.util; - -import com.google.inject.Singleton; -import com.plotsquared.core.util.PermHandler; -import net.milkbowl.vault.permission.Permission; -import org.bukkit.Bukkit; -import org.bukkit.plugin.RegisteredServiceProvider; - -@Singleton public class BukkitPermHandler extends PermHandler { - - private Permission perms; - - @Override - public boolean init() { - if (this.perms == null) { - setupPermissions(); - } - return this.perms != null; - } - - private void setupPermissions() { - if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { - return; - } - RegisteredServiceProvider permissionProvider = - Bukkit.getServer().getServicesManager().getRegistration(Permission.class); - if (permissionProvider != null) { - this.perms = permissionProvider.getProvider(); - } - } - - @Override public boolean hasPermission(String world, String player, String perm) { - return this.perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm); - } -} diff --git a/Core/src/main/java/com/plotsquared/core/command/Auto.java b/Core/src/main/java/com/plotsquared/core/command/Auto.java index ea6a6cf6c..211f5f22f 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Auto.java +++ b/Core/src/main/java/com/plotsquared/core/command/Auto.java @@ -37,6 +37,7 @@ import com.plotsquared.core.events.PlayerAutoPlotEvent; import com.plotsquared.core.events.PlotAutoMergeEvent; import com.plotsquared.core.events.Result; import com.plotsquared.core.events.TeleportCause; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -175,9 +176,11 @@ public class Auto extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { PlotArea plotarea = player.getApplicablePlotArea(); if (plotarea == null) { - if (this.econHandler != null) { - for (PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - if (this.econHandler.hasPermission(area.getWorldName(), player.getName(), "plots.auto")) { + final PermissionHandler permissionHandler = PlotSquared.platform().getPermissionHandler(); + if (permissionHandler.hasCapability( + PermissionHandler.PermissionHandlerCapability.PER_WORLD_PERMISSIONS)) { + for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { + if (player.hasPermission(area.getWorldName(), "plots.auto")) { if (plotarea != null) { plotarea = null; break; diff --git a/Core/src/main/java/com/plotsquared/core/command/Command.java b/Core/src/main/java/com/plotsquared/core/command/Command.java index a0dbe9079..60512dd5a 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Command.java +++ b/Core/src/main/java/com/plotsquared/core/command/Command.java @@ -35,6 +35,7 @@ import com.plotsquared.core.util.StringComparison; import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.task.RunnableVal2; import com.plotsquared.core.util.task.RunnableVal3; +import com.plotsquared.core.permissions.PermissionHolder; import lombok.SneakyThrows; import javax.annotation.Nonnull; @@ -158,7 +159,7 @@ public abstract class Command { return this.allCommands; } - public boolean hasConfirmation(CommandCaller player) { + public boolean hasConfirmation(PermissionHolder player) { return this.confirmation && !player.hasPermission(getPermission() + ".confirm.bypass"); } diff --git a/Core/src/main/java/com/plotsquared/core/command/CommandCaller.java b/Core/src/main/java/com/plotsquared/core/command/CommandCaller.java index b26eed517..f7a6c6885 100644 --- a/Core/src/main/java/com/plotsquared/core/command/CommandCaller.java +++ b/Core/src/main/java/com/plotsquared/core/command/CommandCaller.java @@ -34,14 +34,6 @@ public interface CommandCaller { */ void sendMessage(String message); - /** - * Check the player's permissions. Will be cached if permission caching is enabled. - * - * @param permission the name of the permission - */ - boolean hasPermission(String permission); - - boolean isPermissionSet(String permission); - RequiredType getSuperCaller(); + } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java index 09857628c..783f605a7 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java @@ -26,11 +26,13 @@ package com.plotsquared.core.permissions; import javax.annotation.Nonnull; +import javax.annotation.Nullable; public enum ConsolePermissionProfile implements PermissionProfile { INSTANCE; - @Override public boolean hasPermission(@Nonnull final String permission) { + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { return true; } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java index b59b5a78d..fbf7d8a03 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java @@ -26,11 +26,13 @@ package com.plotsquared.core.permissions; import javax.annotation.Nonnull; +import javax.annotation.Nullable; public enum NullPermissionProfile implements PermissionProfile { INSTANCE; - @Override public boolean hasPermission(@Nonnull final String permission) { + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { return false; } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java index c88537f69..4a273c743 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java @@ -89,7 +89,11 @@ public interface PermissionHandler { /** * The ability to check for offline (player) permissions */ - OFFLINE_PERMISSIONS + OFFLINE_PERMISSIONS, + /** + * Per world permissions + */ + PER_WORLD_PERMISSIONS } } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java index a94bd0b39..abff13262 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java @@ -25,7 +25,12 @@ */ package com.plotsquared.core.permissions; +import com.plotsquared.core.configuration.Captions; +import com.plotsquared.core.configuration.Settings; + +import javax.annotation.Nonnegative; import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * Any object which can hold permissions @@ -33,11 +38,57 @@ import javax.annotation.Nonnull; public interface PermissionHolder { /** - * Check if the permission holder has the given permission node + * Check if the owner of the profile has a given (global) permission * - * @param permission Permission node - * @return {@code true} if the holder has the given permission node, else {@code false} + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} */ - boolean hasPermission(@Nonnull String permission); + default boolean hasPermission(@Nonnull final String permission) { + return hasPermission(null ,permission); + } + + /** + * Check the the highest permission a PlotPlayer has within a specified range.
+ * - Excessively high values will lag
+ * - The default range that is checked is {@link Settings.Limit#MAX_PLOTS}
+ * + * @param stub The permission stub to check e.g. for `plots.plot.#` the stub is `plots.plot` + * @param range The range to check + * @return The highest permission they have within that range + */ + @Nonnegative default int hasPermissionRange(@Nonnull final String stub, + @Nonnegative final int range) { + if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { + return Integer.MAX_VALUE; + } + String[] nodes = stub.split("\\."); + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < (nodes.length - 1); i++) { + builder.append(nodes[i]).append("."); + if (!stub.equals(builder + Captions.PERMISSION_STAR.getTranslated())) { + if (hasPermission(builder + Captions.PERMISSION_STAR.getTranslated())) { + return Integer.MAX_VALUE; + } + } + } + if (hasPermission(stub + ".*")) { + return Integer.MAX_VALUE; + } + for (int i = range; i > 0; i--) { + if (hasPermission(stub + "." + i)) { + return i; + } + } + return 0; + } + + /** + * Check if the owner of the profile has a given permission + * + * @param world World name + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} + */ + boolean hasPermission(@Nullable final String world, @Nonnull String permission); } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java index 912147980..b7aad8e63 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java @@ -26,6 +26,7 @@ package com.plotsquared.core.permissions; import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * A permission profile that can be used to check for permissions @@ -33,11 +34,22 @@ import javax.annotation.Nonnull; public interface PermissionProfile { /** - * Check if the owner of the profile has a given permission + * Check if the owner of the profile has a given (global) permission * * @param permission Permission * @return {@code true} if the owner has the given permission, else {@code false} */ - boolean hasPermission(@Nonnull String permission); + default boolean hasPermission(@Nonnull final String permission) { + return hasPermission(null ,permission); + } + + /** + * Check if the owner of the profile has a given permission + * + * @param world World name + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} + */ + boolean hasPermission(@Nullable final String world, @Nonnull String permission); } diff --git a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java index 2c1e67c8f..437e86491 100644 --- a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java @@ -123,10 +123,6 @@ public class ConsolePlayer extends PlotPlayer { return 0; } - @Override public boolean isPermissionSet(String permission) { - return true; - } - @Override public void sendMessage(String message) { logger.info(message); } diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index d3c4fd369..666d5be7b 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -154,8 +154,9 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return PlotSquared.platform().wrapPlayer(player); } - @Override public final boolean hasPermission(@Nonnull final String permission) { - return this.permissionProfile.hasPermission(permission); + @Override public final boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { + return this.permissionProfile.hasPermission(world, permission); } public abstract Actor toActor(); @@ -257,31 +258,6 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return Permissions.hasPermissionRange(this, "plots.cluster", Settings.Limit.MAX_PLOTS); } - public int hasPermissionRange(String stub, int range) { - if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { - return Integer.MAX_VALUE; - } - String[] nodes = stub.split("\\."); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < (nodes.length - 1); i++) { - builder.append(nodes[i]).append("."); - if (!stub.equals(builder + Captions.PERMISSION_STAR.getTranslated())) { - if (hasPermission(builder + Captions.PERMISSION_STAR.getTranslated())) { - return Integer.MAX_VALUE; - } - } - } - if (hasPermission(stub + ".*")) { - return Integer.MAX_VALUE; - } - for (int i = range; i > 0; i--) { - if (hasPermission(stub + "." + i)) { - return i; - } - } - return 0; - } - /** * Get the number of plots this player owns. * diff --git a/Core/src/main/java/com/plotsquared/core/util/EconHandler.java b/Core/src/main/java/com/plotsquared/core/util/EconHandler.java index 69363079f..508fe8f57 100644 --- a/Core/src/main/java/com/plotsquared/core/util/EconHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/EconHandler.java @@ -48,16 +48,4 @@ public abstract class EconHandler { public abstract void depositMoney(OfflinePlotPlayer player, double amount); - /** - * @deprecated Use {@link PermHandler#hasPermission(String, String, String)} instead - */ - @Deprecated public abstract boolean hasPermission(String world, String player, String perm); - - /** - * @deprecated Use {@link PermHandler#hasPermission(String, String)} instead - */ - @Deprecated public boolean hasPermission(String player, String perm) { - return hasPermission(null, player, perm); - } - } diff --git a/Core/src/main/java/com/plotsquared/core/util/PermHandler.java b/Core/src/main/java/com/plotsquared/core/util/PermHandler.java deleted file mode 100644 index 1dec45fd4..000000000 --- a/Core/src/main/java/com/plotsquared/core/util/PermHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.plotsquared.core.util; - -public abstract class PermHandler { - - public abstract boolean init(); - - public abstract boolean hasPermission(String world, String player, String perm); - - public boolean hasPermission(String player, String perm) { - return hasPermission(null, player, perm); - } -} diff --git a/Core/src/main/java/com/plotsquared/core/util/Permissions.java b/Core/src/main/java/com/plotsquared/core/util/Permissions.java index 34754e7c8..7e3b4622f 100644 --- a/Core/src/main/java/com/plotsquared/core/util/Permissions.java +++ b/Core/src/main/java/com/plotsquared/core/util/Permissions.java @@ -29,6 +29,7 @@ import com.plotsquared.core.command.CommandCaller; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.player.PlotPlayer; +import com.plotsquared.core.permissions.PermissionHolder; import java.util.HashMap; @@ -39,7 +40,7 @@ import java.util.HashMap; */ public class Permissions { - public static boolean hasPermission(PlotPlayer player, Captions caption, boolean notify) { + public static boolean hasPermission(PlotPlayer player, Captions caption, boolean notify) { return hasPermission(player, caption.getTranslated(), notify); } @@ -50,7 +51,7 @@ public class Permissions { * @param caption * @return */ - public static boolean hasPermission(PlotPlayer player, Captions caption) { + public static boolean hasPermission(PlotPlayer player, Captions caption) { return hasPermission(player, caption.getTranslated()); } @@ -63,7 +64,7 @@ public class Permissions { */ public static boolean hasPermission(PlotPlayer player, String permission) { if (!Settings.Enabled_Components.PERMISSION_CACHE) { - return hasPermission((CommandCaller) player, permission); + return hasPermission((PermissionHolder) player, permission); } HashMap map = player.getMeta("perm"); if (map != null) { @@ -75,7 +76,7 @@ public class Permissions { map = new HashMap<>(); player.setMeta("perm", map); } - boolean result = hasPermission((CommandCaller) player, permission); + boolean result = hasPermission((PermissionHolder) player, permission); map.put(permission, result); return result; } @@ -87,12 +88,12 @@ public class Permissions { * @param permission * @return */ - public static boolean hasPermission(CommandCaller caller, String permission) { + public static boolean hasPermission(PermissionHolder caller, String permission) { if (caller.hasPermission(permission)) { return true; - } else if (caller.isPermissionSet(permission)) { + }/* TODO: DECIDE WHAT TO DO HERE; else if (caller.isPermissionSet(permission)) { return false; - } + }*/ if (caller.hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { return true; } @@ -105,9 +106,9 @@ public class Permissions { if (!permission.equals(combined)) { if (caller.hasPermission(combined)) { return true; - } else if (caller.isPermissionSet(combined)) { + }/* TODO: DECIDE WHAT TO DO HERE; else if (caller.isPermissionSet(combined)) { return false; - } + }*/ } } return false; @@ -121,7 +122,7 @@ public class Permissions { * @param notify * @return */ - public static boolean hasPermission(PlotPlayer player, String permission, boolean notify) { + public static boolean hasPermission(PlotPlayer player, String permission, boolean notify) { if (!hasPermission(player, permission)) { if (notify) { MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, permission); @@ -131,7 +132,7 @@ public class Permissions { return true; } - public static int hasPermissionRange(PlotPlayer player, Captions perm, int range) { + public static int hasPermissionRange(PlotPlayer player, Captions perm, int range) { return hasPermissionRange(player, perm.getTranslated(), range); } @@ -140,12 +141,12 @@ public class Permissions { * - Excessively high values will lag
* - The default range that is checked is {@link Settings.Limit#MAX_PLOTS}
* - * @param player + * @param player Player to check for * @param stub The permission stub to check e.g. for `plots.plot.#` the stub is `plots.plot` * @param range The range to check * @return The highest permission they have within that range */ - public static int hasPermissionRange(PlotPlayer player, String stub, int range) { + public static int hasPermissionRange(PlotPlayer player, String stub, int range) { return player.hasPermissionRange(stub, range); } } From 7fc8238fb0bed84cdcab625d2f0ca35e9e5d8b77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 12:47:00 +0200 Subject: [PATCH 04/25] Remove construction of fake player entities for offline players. --- .../plotsquared/bukkit/BukkitPlatform.java | 36 +---- .../bukkit/player/BukkitOfflinePlayer.java | 12 +- .../bukkit/player/BukkitPlayer.java | 19 +-- .../bukkit/player/BukkitPlayerManager.java | 6 +- .../plotsquared/bukkit/util/BukkitUtil.java | 32 ----- .../bukkit/util/OfflinePlayerUtil.java | 133 ------------------ .../java/com/plotsquared/core/PlotAPI.java | 12 +- .../com/plotsquared/core/PlotPlatform.java | 11 +- .../com/plotsquared/core/command/Buy.java | 2 +- .../core/listener/PlotListener.java | 4 +- .../core/listener/WESubscriber.java | 3 +- .../core/player/ConsolePlayer.java | 6 +- .../core/player/OfflinePlotPlayer.java | 11 +- .../plotsquared/core/player/PlotPlayer.java | 14 -- .../java/com/plotsquared/core/plot/Plot.java | 13 +- .../core/plot/expiration/ExpireManager.java | 4 +- .../com/plotsquared/core/util/WorldUtil.java | 8 -- 17 files changed, 40 insertions(+), 286 deletions(-) delete mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index 8a9831f22..684c3f438 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -570,7 +570,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } final Plot plot = area.getOwnedPlot(id); if (plot != null) { - if (!plot.getFlag(ServerPlotFlag.class) || PlotPlayer.wrap(plot.getOwner()) == null) { + if (!plot.getFlag(ServerPlotFlag.class) || PlotSquared.platform().getPlayerManager() + .getPlayerIfExists(plot.getOwner()) == null) { if (world.getKeepSpawnInMemory()) { world.setKeepSpawnInMemory(false); return; @@ -1078,39 +1079,6 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } } - /** - * Attempt to retrieve a {@link PlotPlayer} from a player identifier. - * This method accepts: - * - {@link Player} objects, - * - {@link OfflinePlayer} objects, - * - {@link String} usernames for online players, and - * - {@link UUID} UUIDs for online players - *

- * In the case of offline players, a fake {@link Player} instance will be created. - * This is a rather expensive operation, and should be avoided if possible. - * - * @param player The player to convert to a PlotPlayer - * @return The plot player instance that corresponds to the identifier, or null - * if no such player object could be created - */ - @Override @Nullable public PlotPlayer wrapPlayer(final Object player) { - if (player instanceof Player) { - return BukkitUtil.adapt((Player) player); - } - if (player instanceof OfflinePlayer) { - return BukkitUtil.adapt((OfflinePlayer) player); - } - if (player instanceof String) { - return (PlotPlayer) PlotSquared.platform().getPlayerManager() - .getPlayerIfExists((String) player); - } - if (player instanceof UUID) { - return (PlotPlayer) PlotSquared.platform().getPlayerManager() - .getPlayerIfExists((UUID) player); - } - return null; - } - @Override public String getNMSPackage() { final String name = Bukkit.getServer().getClass().getPackage().getName(); return name.substring(name.lastIndexOf('.') + 1); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java index 9226c5847..799fbf2b1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java @@ -30,6 +30,8 @@ import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.permissions.PermissionProfile; import com.plotsquared.core.player.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; + +import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -43,8 +45,6 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { /** * Please do not use this method. Instead use BukkitUtil.getPlayer(Player), * as it caches player objects. - * - * @param player */ public BukkitOfflinePlayer(@Nonnull final OfflinePlayer player, @Nonnull final PermissionHandler permissionHandler) { @@ -57,12 +57,8 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { return this.player.getUniqueId(); } - @Override public long getLastPlayed() { - return this.player.getLastPlayed(); - } - - @Override public boolean isOnline() { - return this.player.isOnline(); + @Override @Nonnegative public long getLastPlayed() { + return this.player.getLastSeen(); } @Override public String getName() { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java index 1415c2840..b66eed10f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java @@ -75,10 +75,8 @@ public class BukkitPlayer extends PlotPlayer { private final EconHandler econHandler; public final Player player; - private boolean offline; private String name; - /** *

Please do not use this method. Instead use * BukkitUtil.getPlayer(Player), as it caches player objects.

@@ -90,19 +88,12 @@ public class BukkitPlayer extends PlotPlayer { this(plotAreaManager, eventDispatcher, player, false, econHandler, permissionHandler); } - public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, - @Nonnull final Player player, final boolean offline, @Nullable final EconHandler econHandler, - @Nonnull final PermissionHandler permissionHandler) { - this(plotAreaManager, eventDispatcher, player, offline, true, econHandler, permissionHandler); - } - public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final - EventDispatcher eventDispatcher, @Nonnull final Player player, final boolean offline, + EventDispatcher eventDispatcher, @Nonnull final Player player, final boolean realPlayer, @Nullable final EconHandler econHandler, @Nonnull final PermissionHandler permissionHandler) { super(plotAreaManager, eventDispatcher, econHandler, permissionHandler); this.player = player; - this.offline = offline; this.econHandler = econHandler; if (realPlayer) { super.populatePersistentMetaMap(); @@ -130,8 +121,8 @@ public class BukkitPlayer extends PlotPlayer { return player.getUniqueId(); } - @Override public long getLastPlayed() { - return this.player.getLastPlayed(); + @Override @Nonnegative public long getLastPlayed() { + return this.player.getLastSeen(); } @Override public boolean canTeleport(@Nonnull final Location location) { @@ -255,10 +246,6 @@ public class BukkitPlayer extends PlotPlayer { return this.name; } - @Override public boolean isOnline() { - return !this.offline && this.player.isOnline(); - } - @Override public void setCompassTarget(Location location) { this.player.setCompassTarget( new org.bukkit.Location(BukkitUtil.getWorld(location.getWorldName()), location.getX(), diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java index d05fafd7a..78af765a2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java @@ -60,11 +60,13 @@ import java.util.UUID; } @Nonnull @Override public BukkitPlayer getPlayer(@Nonnull final Player object) { + if (!object.isOnline()) { + throw new NoSuchPlayerException(object.getUniqueId()); + } try { return getPlayer(object.getUniqueId()); } catch (final NoSuchPlayerException exception) { - return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, object, - object.isOnline(), false, this.econHandler, this.permissionHandler); + return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, object, false, this.econHandler, this.permissionHandler); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 1d88f9a6f..3537c25a2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -53,7 +53,6 @@ import io.papermc.lib.PaperLib; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; -import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; @@ -101,7 +100,6 @@ import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; -import java.util.UUID; import java.util.function.Consumer; import java.util.function.IntConsumer; import java.util.stream.Stream; @@ -116,24 +114,6 @@ import java.util.stream.Stream; super(regionManager); } - /** - * Get a {@link PlotPlayer} from an {@link OfflinePlayer}. If the player is - * online, it returns a complete player. If the player is offline, it creates - * a fake player - * - * @param op Offline player - * @return Plot player instance - */ - @Nonnull public static PlotPlayer adapt(@Nonnull final OfflinePlayer op) { - if (op.isOnline()) { - return adapt(Objects.requireNonNull(op.getPlayer())); - } - final Player player = OfflinePlayerUtil.loadPlayer(op); - player.loadData(); - return new BukkitPlayer(PlotSquared.get().getPlotAreaManager(), - PlotSquared.get().getEventDispatcher(), player, true, PlotSquared.platform().getEconHandler(), PlotSquared.platform().getPermissionHandler()); - } - /** * Turn a Bukkit {@link Player} into a PlotSquared {@link PlotPlayer} * @@ -214,18 +194,6 @@ import java.util.stream.Stream; } } - /** - * Gets the PlotPlayer for a UUID. The PlotPlayer is usually cached and - * will provide useful functions relating to players. - * - * @param uuid the uuid to wrap - * @return a {@code PlotPlayer} - * @see PlotPlayer#wrap(Object) - */ - @Override @Nonnull public PlotPlayer getPlayer(@Nonnull final UUID uuid) { - return PlotPlayer.wrap(Bukkit.getOfflinePlayer(uuid)); - } - @Override public boolean isBlockSame(@Nonnull final BlockState block1, @Nonnull final BlockState block2) { if (block1.equals(block2)) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java deleted file mode 100644 index 41ae4dedd..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.plotsquared.bukkit.util; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.UUID; - -import static com.plotsquared.core.util.ReflectionUtils.callConstructor; -import static com.plotsquared.core.util.ReflectionUtils.callMethod; -import static com.plotsquared.core.util.ReflectionUtils.getCbClass; -import static com.plotsquared.core.util.ReflectionUtils.getField; -import static com.plotsquared.core.util.ReflectionUtils.getNmsClass; -import static com.plotsquared.core.util.ReflectionUtils.getUtilClass; -import static com.plotsquared.core.util.ReflectionUtils.makeConstructor; -import static com.plotsquared.core.util.ReflectionUtils.makeField; -import static com.plotsquared.core.util.ReflectionUtils.makeMethod; - -public class OfflinePlayerUtil { - - public static Player loadPlayer(OfflinePlayer player) { - if (player == null) { - return null; - } - if (player instanceof Player) { - return (Player) player; - } - return loadPlayer(player.getUniqueId(), player.getName()); - } - - private static Player loadPlayer(UUID id, String name) { - Object server = getMinecraftServer(); - Object interactManager = newPlayerInteractManager(); - Object worldServer = getWorldServer(); - Object profile = newGameProfile(id, name); - Class entityPlayerClass = getNmsClass("EntityPlayer"); - Constructor entityPlayerConstructor = - makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), - getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"), - getNmsClass("PlayerInteractManager")); - Object entityPlayer = - callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); - return (Player) getBukkitEntity(entityPlayer); - } - - private static Object newGameProfile(UUID id, String name) { - Class gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile"); - if (gameProfileClass == null) { //Before uuids - return name; - } - Constructor gameProfileConstructor = - makeConstructor(gameProfileClass, UUID.class, String.class); - if (gameProfileConstructor == null) { //Version has string constructor - gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class); - return callConstructor(gameProfileConstructor, id.toString(), name); - } else { //Version has uuid constructor - return callConstructor(gameProfileConstructor, id, name); - } - } - - private static Object newPlayerInteractManager() { - Object worldServer = getWorldServer(); - Class playerInteractClass = getNmsClass("PlayerInteractManager"); - Class worldClass = getNmsClass("World"); - Constructor c = makeConstructor(playerInteractClass, worldClass); - if (c == null) { - c = makeConstructor(playerInteractClass, getNmsClass("WorldServer")); - } - return callConstructor(c, worldServer); - } - - public static Object getWorldServerNew() { - Object server = getMinecraftServer(); - Class minecraftServerClass = getNmsClass("MinecraftServer"); - Class dimensionManager = getNmsClass("DimensionManager"); - Object overworld = getField(makeField(dimensionManager, "OVERWORLD"), null); - Method getWorldServer = - makeMethod(minecraftServerClass, "getWorldServer", dimensionManager); - return callMethod(getWorldServer, server, overworld); - } - - private static Object getWorldServer() { - Object server = getMinecraftServer(); - Class minecraftServerClass = getNmsClass("MinecraftServer"); - Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class); - Object o; - try { - o = callMethod(getWorldServer, server, 0); - } catch (final RuntimeException e) { - o = getWorldServerNew(); - } - return o; - } - - //NMS Utils - - private static Object getMinecraftServer() { - return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer()); - } - - private static Entity getBukkitEntity(Object o) { - Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity"); - return callMethod(getBukkitEntity, o); - } -} diff --git a/Core/src/main/java/com/plotsquared/core/PlotAPI.java b/Core/src/main/java/com/plotsquared/core/PlotAPI.java index 9a83aae5e..1450a3f4e 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotAPI.java +++ b/Core/src/main/java/com/plotsquared/core/PlotAPI.java @@ -39,6 +39,8 @@ import com.plotsquared.core.util.SchematicHandler; import com.plotsquared.core.util.query.PlotQuery; import lombok.NoArgsConstructor; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Collections; import java.util.Set; import java.util.UUID; @@ -178,10 +180,9 @@ import java.util.UUID; * * @param uuid the uuid of the player to wrap * @return a {@code PlotPlayer} - * @see PlotPlayer#wrap(Object) */ - public PlotPlayer wrapPlayer(UUID uuid) { - return PlotPlayer.wrap(uuid); + @Nullable public PlotPlayer wrapPlayer(@Nonnull final UUID uuid) { + return PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); } /** @@ -189,10 +190,9 @@ import java.util.UUID; * * @param player the player to wrap * @return a {@code PlotPlayer} - * @see PlotPlayer#wrap(Object) */ - public PlotPlayer wrapPlayer(String player) { - return PlotPlayer.wrap(player); + @Nullable public PlotPlayer wrapPlayer(@Nonnull final String player) { + return PlotSquared.platform().getPlayerManager().getPlayerIfExists(player); } /** diff --git a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java index c84bce2b9..51f5ff6e1 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java +++ b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java @@ -27,6 +27,7 @@ package com.plotsquared.core; import com.google.inject.Injector; import com.google.inject.Key; +import com.google.inject.TypeLiteral; import com.plotsquared.core.backup.BackupManager; import com.plotsquared.core.generator.GeneratorWrapper; import com.plotsquared.core.generator.HybridUtils; @@ -80,14 +81,6 @@ public interface PlotPlatform

extends ILogger { */ File getWorldContainer(); - /** - * Wraps a player into a PlotPlayer object. - * - * @param player The player to convert to a PlotPlayer - * @return A PlotPlayer - */ - @Nullable PlotPlayer

wrapPlayer(Object player); - /** * Completely shuts down the plugin. */ @@ -186,7 +179,7 @@ public interface PlotPlatform

extends ILogger { * @return Player manager */ @Nonnull default PlayerManager, ? extends P> getPlayerManager() { - return getInjector().getInstance(PlayerManager.class); + return getInjector().getInstance(Key.get(new TypeLiteral, ? extends P>>() {})); } /** diff --git a/Core/src/main/java/com/plotsquared/core/command/Buy.java b/Core/src/main/java/com/plotsquared/core/command/Buy.java index 88f4dd4af..8fe688834 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Buy.java +++ b/Core/src/main/java/com/plotsquared/core/command/Buy.java @@ -93,7 +93,7 @@ public class Buy extends Command { this.econHandler.depositMoney(PlotSquared.platform().getPlayerManager().getOfflinePlayer(plot.getOwnerAbs()), price); - PlotPlayer owner = PlotSquared.platform().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs()); + PlotPlayer owner = PlotSquared.platform().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs()); if (owner != null) { Captions.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price); } diff --git a/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java b/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java index 2579976a4..c9fe94e41 100644 --- a/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java +++ b/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java @@ -94,7 +94,7 @@ public class PlotListener { ++value.count; if (value.count == value.interval) { value.count = 0; - PlotPlayer player = PlotPlayer.wrap(entry.getKey()); + final PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(entry.getKey()); if (player == null) { iterator.remove(); continue; @@ -114,7 +114,7 @@ public class PlotListener { ++value.count; if (value.count == value.interval) { value.count = 0; - PlotPlayer player = PlotSquared.platform().getWorldUtil().getPlayer(entry.getKey()); + final PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(entry.getKey()); if (player == null) { iterator.remove(); continue; diff --git a/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java b/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java index 4ae1c5c1f..7cfbd2751 100644 --- a/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java +++ b/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java @@ -26,6 +26,7 @@ package com.plotsquared.core.listener; import com.google.inject.Inject; +import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.player.PlotPlayer; @@ -72,7 +73,7 @@ public class WESubscriber { Actor actor = event.getActor(); if (actor != null && actor.isPlayer()) { String name = actor.getName(); - PlotPlayer plotPlayer = PlotPlayer.wrap(name); + final PlotPlayer plotPlayer = PlotSquared.platform().getPlayerManager().getPlayerIfExists(name); Set mask; if (plotPlayer == null) { Player player = (Player) actor; diff --git a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java index 437e86491..60fbf7415 100644 --- a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java @@ -120,7 +120,7 @@ public class ConsolePlayer extends PlotPlayer { } @Override public long getLastPlayed() { - return 0; + return System.currentTimeMillis(); } @Override public void sendMessage(String message) { @@ -132,10 +132,6 @@ public class ConsolePlayer extends PlotPlayer { setMeta(META_LOCATION, location); } - @Override public boolean isOnline() { - return true; - } - @Override public String getName() { return "*"; } diff --git a/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java index 92a0e6536..24d83514a 100644 --- a/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java @@ -27,6 +27,7 @@ package com.plotsquared.core.player; import com.plotsquared.core.permissions.PermissionHolder; +import javax.annotation.Nonnegative; import java.util.UUID; public interface OfflinePlotPlayer extends PermissionHolder { @@ -42,16 +43,8 @@ public interface OfflinePlotPlayer extends PermissionHolder { * Gets the time in milliseconds when the player was last seen online. * * @return the time in milliseconds when last online - * @deprecated This method may be inconsistent across platforms. The javadoc may be wrong depending on which platform is used. */ - @SuppressWarnings("DeprecatedIsStillUsed") @Deprecated long getLastPlayed(); - - /** - * Checks if this player is online. - * - * @return {@code true} if this player is online - */ - boolean isOnline(); + @Nonnegative long getLastPlayed(); /** * Gets the name of this player. diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index 666d5be7b..27680b26a 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -140,20 +140,6 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return players; } - /** - * Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's already cached)
- * - Accepts sponge/bukkit Player (online) - * - Accepts player name (online) - * - Accepts UUID - * - Accepts bukkit OfflinePlayer (offline) - * - * @param player Player object to wrap - * @return Wrapped player - */ - public static PlotPlayer wrap(Object player) { - return PlotSquared.platform().wrapPlayer(player); - } - @Override public final boolean hasPermission(@Nullable final String world, @Nonnull final String permission) { return this.permissionProfile.hasPermission(world, permission); diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index 918388008..d4fe6ba6b 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -1926,11 +1926,16 @@ public class Plot { DBFunc.createPlotAndSettings(this, () -> { PlotArea plotworld = Plot.this.area; if (notify && plotworld.isAutoMerge()) { - PlotPlayer player = this.worldUtil.getPlayer(uuid); + final PlotPlayer player = PlotSquared.platform().getPlayerManager() + .getPlayerIfExists(uuid); + PlotMergeEvent event = this.eventDispatcher .callMerge(this, Direction.ALL, Integer.MAX_VALUE, player); + if (event.getEventResult() == Result.DENY) { - sendMessage(player, Captions.EVENT_DENIED, "Auto merge on claim"); + if (player != null) { + sendMessage(player, Captions.EVENT_DENIED, "Auto merge on claim"); + } return; } Plot.this.autoMerge(event.getDir(), event.getMax(), uuid, true); @@ -3083,10 +3088,10 @@ public class Plot { if (!TaskManager.removeFromTeleportQueue(name)) { return; } - if (player.isOnline()) { + try { MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT); player.teleport(location, cause); - } + } catch (final Exception ignored) {} }, TaskTime.seconds(Settings.Teleport.DELAY)); resultConsumer.accept(true); }; diff --git a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java index 2a3514540..1171bef87 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java @@ -418,13 +418,13 @@ public class ExpireManager { } } for (UUID helper : plot.getTrusted()) { - PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(helper); + PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(helper); if (player != null) { MainUtil.sendMessage(player, Captions.PLOT_REMOVED_USER, plot.toString()); } } for (UUID helper : plot.getMembers()) { - PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(helper); + PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(helper); if (player != null) { MainUtil.sendMessage(player, Captions.PLOT_REMOVED_USER, plot.toString()); } diff --git a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java index 81d5e2f11..e478bfdb8 100644 --- a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java @@ -328,14 +328,6 @@ public abstract class WorldUtil { */ public abstract boolean isBlockSame(@Nonnull BlockState block1, @Nonnull BlockState block2); - /** - * Get a player object for the player with the given UUID - * - * @param uuid Player UUID - * @return Player object - */ - @Nonnull public abstract PlotPlayer getPlayer(@Nonnull UUID uuid); - /** * Get the player health * From b3a63123fda4a4041dd788c3023c3281a2950574 Mon Sep 17 00:00:00 2001 From: N0tMyFaultOG Date: Thu, 23 Jul 2020 14:03:56 +0200 Subject: [PATCH 05/25] Fix dependencies --- Bukkit/build.gradle | 2 ++ Bukkit/pom.xml | 2 +- Core/build.gradle | 2 ++ Core/pom.xml | 12 ++++++++++++ 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index 8e32904c5..3bb9f863e 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -106,6 +106,8 @@ shadowJar { include(dependency("javax.annotation:javax-annotation-api")) include(dependency('org.apache.logging.log4j:log4j-slf4j-impl')) include(dependency('org.slf4j:slf4j-api')) + include(dependency('javax.inject:javax.inject:1')) + include(dependency('aopalliance:aopalliance:1.0')) } relocate('net.kyori.text', 'com.plotsquared.formatting.text') diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index d4848ae84..b9e6fbb23 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -51,7 +51,7 @@ io.papermc paperlib - 1.0.2 + 1.0.4 compile diff --git a/Core/build.gradle b/Core/build.gradle index 9743bc080..bd0fa55f0 100644 --- a/Core/build.gradle +++ b/Core/build.gradle @@ -20,6 +20,8 @@ dependencies { compile("com.google.inject:guice:4.2.3") compile("com.google.inject.extensions:guice-assistedinject:4.2.3") compile group: 'com.google.code.findbugs', name: 'annotations', version: '3.0.1' + compile group: 'javax.inject', name: 'javax.inject', version: '1' + compile group: 'aopalliance', name: 'aopalliance', version: '1.0' // logging implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.8.1") } diff --git a/Core/pom.xml b/Core/pom.xml index ac6a4ef60..05142d3a8 100644 --- a/Core/pom.xml +++ b/Core/pom.xml @@ -36,6 +36,18 @@ 3.0.1 compile + + javax.inject + javax.inject + 1 + compile + + + aopalliance + aopalliance + 1.0 + compile + org.projectlombok lombok From cfd71457d28217ca8c1d034adf81f36b45d46b93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Sun, 19 Jul 2020 14:49:26 +0200 Subject: [PATCH 06/25] Clean up BlockUtil --- .../com/plotsquared/core/util/BlockUtil.java | 58 ++++++++++++++++--- 1 file changed, 49 insertions(+), 9 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/util/BlockUtil.java b/Core/src/main/java/com/plotsquared/core/util/BlockUtil.java index a0f4e4f50..6d4c4079a 100644 --- a/Core/src/main/java/com/plotsquared/core/util/BlockUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/BlockUtil.java @@ -35,13 +35,20 @@ import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.FuzzyBlockState; import com.sk89q.worldedit.world.registry.LegacyMapper; + +import javax.annotation.Nonnegative; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Map; +/** + * {@link BlockState} related utility methods + */ public final class BlockUtil { - private static ParserContext PARSER_CONTEXT = new ParserContext(); - private static InputParser PARSER; + + private static final ParserContext PARSER_CONTEXT = new ParserContext(); + private static final InputParser PARSER; static { PARSER_CONTEXT.setRestricted(false); @@ -53,15 +60,35 @@ public final class BlockUtil { private BlockUtil() { } - public static BlockState get(int id) { + /** + * Get a {@link BlockState} from a legacy id + * + * @param id Legacy ID + * @return Block state, or {@code null} + */ + @Nullable public static BlockState get(@Nonnegative final int id) { return LegacyMapper.getInstance().getBlockFromLegacy(id); } - public static BlockState get(int id, int data) { + /** + * Get a {@link BlockState} from a legacy id-data pair + * + * @param id Legacy ID + * @param data Legacy data + * @return Block state, or {@code null} + */ + @Nullable public static BlockState get(@Nonnegative final int id, final int data) { return LegacyMapper.getInstance().getBlockFromLegacy(id, data); } - public static BlockState get(String id) { + /** + * Get a {@link BlockState} from its ID + * + * @param id String or integer ID + * @return Parsed block state, or {@code null} if none + * could be parsed + */ + @Nullable public static BlockState get(@Nonnull String id) { if (id.length() == 1 && id.charAt(0) == '*') { return FuzzyBlockState.builder().type(BlockTypes.AIR).build(); } @@ -90,16 +117,29 @@ public final class BlockUtil { } } - public static BlockState[] parse(String commaDelimited) { - String[] split = commaDelimited.split(",(?![^\\(\\[]*[\\]\\)])"); - BlockState[] result = new BlockState[split.length]; + /** + * Parse a comma delimited list of block states + * + * @param commaDelimited List of block states + * @return Parsed block states + */ + @Nonnull public static BlockState[] parse(@Nonnull final String commaDelimited) { + final String[] split = commaDelimited.split(",(?![^\\(\\[]*[\\]\\)])"); + final BlockState[] result = new BlockState[split.length]; for (int i = 0; i < split.length; i++) { result[i] = get(split[i]); } return result; } - public static BlockState deserialize(@Nonnull final Map map) { + /** + * Deserialize a serialized {@link BlockState} + * + * @param map Serialized block state + * @return Deserialized block state, or {@code null} if the map is + * not a properly serialized block state + */ + @Nullable public static BlockState deserialize(@Nonnull final Map map) { if (map.containsKey("material")) { final Object object = map.get("material"); return get(object.toString()); From 17d358f8fe432bb9866bd3b83deae8a49d3e4c3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 14:11:34 +0200 Subject: [PATCH 07/25] Fix plot ID issues --- .../com/plotsquared/core/plot/PlotId.java | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotId.java b/Core/src/main/java/com/plotsquared/core/plot/PlotId.java index 27004ba3c..d74d7aeec 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotId.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotId.java @@ -36,7 +36,7 @@ import java.util.Iterator; * Plot (X,Y) tuples for plot locations * within a plot area */ -public class PlotId { +public final class PlotId { private final int x; private final int y; @@ -48,7 +48,7 @@ public class PlotId { * @param x The plot x coordinate * @param y The plot y coordinate */ - private PlotId(int x, int y) { + private PlotId(final int x, final int y) { this.x = x; this.y = y; this.hash = (this.getX() << 16) | (this.getY() & 0xFFFF); @@ -61,20 +61,21 @@ public class PlotId { * @param y The plot y coordinate */ @Nonnull public static PlotId of(final int x, final int y) { - return PlotId.of(x, y); + return new PlotId(x, y); } /** * Get a Plot Id based on a string * * @param string to create id from - * @return the PlotId representation of the arguement + * @return the PlotId representation of the argument * @throws IllegalArgumentException if the string does not contain a valid PlotId */ - @Nonnull public static PlotId fromString(@Nonnull String string) { - PlotId plot = fromStringOrNull(string); - if (plot == null) + @Nonnull public static PlotId fromString(@Nonnull final String string) { + final PlotId plot = fromStringOrNull(string); + if (plot == null) { throw new IllegalArgumentException("Cannot create PlotID. String invalid."); + } return plot; } @@ -84,8 +85,8 @@ public class PlotId { * @param string ID string * @return Plot ID, or {@code null} if none could be parsed */ - @Nullable public static PlotId fromStringOrNull(@Nonnull String string) { - String[] parts = string.split("[;,.]"); + @Nullable public static PlotId fromStringOrNull(@Nonnull final String string) { + final String[] parts = string.split("[;,.]"); if (parts.length < 2) { return null; } @@ -94,7 +95,7 @@ public class PlotId { try { x = Integer.parseInt(parts[0]); y = Integer.parseInt(parts[1]); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { return null; } return of(x, y); @@ -126,7 +127,7 @@ public class PlotId { * @return X component */ public int getX() { - return this.getX(); + return this.x; } /** @@ -135,7 +136,7 @@ public class PlotId { * @return Y component */ public int getY() { - return this.getY(); + return this.y; } /** @@ -144,8 +145,8 @@ public class PlotId { * @return Next plot ID */ @Nonnull public PlotId getNextId() { - int absX = Math.abs(x); - int absY = Math.abs(y); + final int absX = Math.abs(x); + final int absY = Math.abs(y); if (absX > absY) { if (x > 0) { return PlotId.of(x, y + 1); From b9a8846ee9ab61036e848cbc21680be97142cbea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 14:56:06 +0200 Subject: [PATCH 08/25] Fix WorldManager injection --- .../src/main/java/com/plotsquared/bukkit/BukkitPlatform.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index 684c3f438..defd335e3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -30,6 +30,7 @@ import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Stage; +import com.google.inject.TypeLiteral; import com.plotsquared.bukkit.generator.BukkitPlotGenerator; import com.plotsquared.bukkit.inject.BackupModule; import com.plotsquared.bukkit.inject.BukkitModule; @@ -1111,4 +1112,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; return BukkitWorld.of(worldName); } + @Override @Nonnull public PlatformWorldManager getWorldManager() { + return getInjector().getInstance(Key.get(new TypeLiteral>() {})); + } + } From bfbb81030fa4483ac4223d5ab32028e4212d6408 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Tue, 21 Jul 2020 14:28:54 +0200 Subject: [PATCH 09/25] Start working on the new permission system --- .../plotsquared/bukkit/BukkitPlatform.java | 8 +- .../bukkit/inject/PermissionModule.java | 52 +++++++++ .../permissions/BukkitPermissionHandler.java | 84 +++++++++++++++ .../permissions/VaultPermissionHandler.java | 102 ++++++++++++++++++ .../bukkit/player/BukkitOfflinePlayer.java | 14 ++- .../bukkit/player/BukkitPlayer.java | 22 ++-- .../bukkit/player/BukkitPlayerManager.java | 14 ++- .../plotsquared/bukkit/util/BukkitUtil.java | 2 +- .../com/plotsquared/core/PlotPlatform.java | 10 ++ .../permissions/ConsolePermissionProfile.java | 37 +++++++ .../permissions/NullPermissionProfile.java | 37 +++++++ .../core/permissions/PermissionHandler.java | 95 ++++++++++++++++ .../core/permissions/PermissionHolder.java | 43 ++++++++ .../core/permissions/PermissionProfile.java | 43 ++++++++ .../core/player/ConsolePlayer.java | 14 ++- .../core/player/OfflinePlotPlayer.java | 5 +- .../plotsquared/core/player/PlotPlayer.java | 17 ++- .../com/plotsquared/core/util/ChunkUtil.java | 25 +++++ .../com/plotsquared/core/util/MainUtil.java | 47 ++++++++ 19 files changed, 637 insertions(+), 34 deletions(-) create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java create mode 100644 Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index bb27113c5..030e30ce1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -34,6 +34,7 @@ import com.google.inject.TypeLiteral; import com.plotsquared.bukkit.generator.BukkitPlotGenerator; import com.plotsquared.bukkit.inject.BackupModule; import com.plotsquared.bukkit.inject.BukkitModule; +import com.plotsquared.bukkit.inject.PermissionModule; import com.plotsquared.bukkit.inject.WorldManagerModule; import com.plotsquared.bukkit.listener.ChunkListener; import com.plotsquared.bukkit.listener.EntitySpawnListener; @@ -248,8 +249,11 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; // We create the injector after PlotSquared has been initialized, so that we have access // to generated instances and settings - this.injector = Guice.createInjector(Stage.PRODUCTION, new WorldManagerModule(), new PlotSquaredModule(), - new BukkitModule(this), new BackupModule()); + this.injector = Guice.createInjector(Stage.PRODUCTION, new PermissionModule(), + new WorldManagerModule(), + new PlotSquaredModule(), + new BukkitModule(this), + new BackupModule()); this.injector.injectMembers(this); if (PremiumVerification.isPremium() && Settings.Enabled_Components.UPDATE_NOTIFICATIONS) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java new file mode 100644 index 000000000..b22cb3648 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java @@ -0,0 +1,52 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.bukkit.inject; + +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.Singleton; +import com.plotsquared.bukkit.permissions.BukkitPermissionHandler; +import com.plotsquared.bukkit.permissions.VaultPermissionHandler; +import com.plotsquared.core.permissions.PermissionHandler; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; +import org.bukkit.plugin.RegisteredServiceProvider; + +public class PermissionModule extends AbstractModule { + + @Provides @Singleton PermissionHandler providePermissionHandler() { + try { + RegisteredServiceProvider permissionProvider = + Bukkit.getServer().getServicesManager().getRegistration(Permission.class); + if (permissionProvider != null) { + return new VaultPermissionHandler(); + } + } catch (final Exception ignored) { + } + return new BukkitPermissionHandler(); + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java new file mode 100644 index 000000000..bceecda3e --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java @@ -0,0 +1,84 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.bukkit.permissions; + +import com.plotsquared.bukkit.player.BukkitPlayer; +import com.plotsquared.core.permissions.ConsolePermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; +import com.plotsquared.core.permissions.PermissionProfile; +import com.plotsquared.core.player.ConsolePlayer; +import com.plotsquared.core.player.OfflinePlotPlayer; +import com.plotsquared.core.player.PlotPlayer; +import org.bukkit.entity.Player; + +import javax.annotation.Nonnull; +import java.lang.ref.WeakReference; +import java.util.EnumSet; +import java.util.Optional; +import java.util.Set; + +public class BukkitPermissionHandler implements PermissionHandler { + + @Override public void initialize() { + } + + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull PlotPlayer playerPlotPlayer) { + if (playerPlotPlayer instanceof BukkitPlayer) { + final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; + return Optional.of(new BukkitPermissionProfile(bukkitPlayer.getPlatformPlayer())); + } else if (playerPlotPlayer instanceof ConsolePlayer) { + return Optional.of(ConsolePermissionProfile.INSTANCE); + } + return Optional.empty(); + } + + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull OfflinePlotPlayer offlinePlotPlayer) { + return Optional.empty(); + } + + @Nonnull @Override public Set getCapabilities() { + return EnumSet.of(PermissionHandlerCapability.ONLINE_PERMISSIONS); + } + + + private static final class BukkitPermissionProfile implements PermissionProfile { + + private final WeakReference playerReference; + + private BukkitPermissionProfile(@Nonnull final Player player) { + this.playerReference = new WeakReference<>(player); + } + + @Override public boolean hasPermission(@Nonnull final String permission) { + final Player player = this.playerReference.get(); + return player != null && player.hasPermission(permission); + } + + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java new file mode 100644 index 000000000..a7978e671 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java @@ -0,0 +1,102 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.bukkit.permissions; + +import com.plotsquared.bukkit.player.BukkitOfflinePlayer; +import com.plotsquared.bukkit.player.BukkitPlayer; +import com.plotsquared.core.permissions.ConsolePermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; +import com.plotsquared.core.permissions.PermissionProfile; +import com.plotsquared.core.player.ConsolePlayer; +import com.plotsquared.core.player.OfflinePlotPlayer; +import com.plotsquared.core.player.PlotPlayer; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.plugin.RegisteredServiceProvider; + +import javax.annotation.Nonnull; +import java.util.EnumSet; +import java.util.Optional; +import java.util.Set; + +public class VaultPermissionHandler implements PermissionHandler { + + private Permission permissions; + + @Override public void initialize() { + if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { + throw new IllegalStateException("Vault is not present on the server"); + } + RegisteredServiceProvider permissionProvider = + Bukkit.getServer().getServicesManager().getRegistration(Permission.class); + if (permissionProvider != null) { + this.permissions = permissionProvider.getProvider(); + } + } + + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull PlotPlayer playerPlotPlayer) { + if (playerPlotPlayer instanceof BukkitPlayer) { + final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; + return Optional.of(new VaultPermissionProfile(bukkitPlayer.getPlatformPlayer())); + } else if (playerPlotPlayer instanceof ConsolePlayer) { + return Optional.of(ConsolePermissionProfile.INSTANCE); + } + return Optional.empty(); + } + + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull OfflinePlotPlayer offlinePlotPlayer) { + if (offlinePlotPlayer instanceof BukkitOfflinePlayer) { + return Optional.of(new VaultPermissionProfile(((BukkitOfflinePlayer) offlinePlotPlayer).player)); + } + return Optional.empty(); + } + + @Nonnull @Override public Set getCapabilities() { + return EnumSet.of(PermissionHandlerCapability.ONLINE_PERMISSIONS, PermissionHandlerCapability.OFFLINE_PERMISSIONS); + } + + + private final class VaultPermissionProfile implements PermissionProfile { + + private final OfflinePlayer offlinePlayer; + + private VaultPermissionProfile(@Nonnull final OfflinePlayer offlinePlayer) { + this.offlinePlayer = offlinePlayer; + } + + @Override public boolean hasPermission(@Nonnull final String permission) { + if (permissions == null) { + return false; + } + return permissions.playerHas(null, offlinePlayer, permission); + } + + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java index 3aa5d12c3..e9c74dfb9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java @@ -25,6 +25,9 @@ */ package com.plotsquared.bukkit.player; +import com.plotsquared.core.permissions.NullPermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; +import com.plotsquared.core.permissions.PermissionProfile; import com.plotsquared.core.player.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; import javax.annotation.Nonnull; @@ -34,6 +37,7 @@ import java.util.UUID; public class BukkitOfflinePlayer implements OfflinePlotPlayer { public final OfflinePlayer player; + private final PermissionProfile permissionProfile; /** * Please do not use this method. Instead use BukkitUtil.getPlayer(Player), @@ -41,8 +45,11 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { * * @param player */ - public BukkitOfflinePlayer(OfflinePlayer player) { + public BukkitOfflinePlayer(@Nonnull final OfflinePlayer player, @Nonnull final + PermissionHandler permissionHandler) { this.player = player; + this.permissionProfile = permissionHandler.getPermissionProfile(this) + .orElse(NullPermissionProfile.INSTANCE); } @Nonnull @Override public UUID getUUID() { @@ -60,4 +67,9 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { @Override public String getName() { return this.player.getName(); } + + @Override public boolean hasPermission(@Nonnull final String permission) { + return this.permissionProfile.hasPermission(permission); + } + } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java index 15d9bacf8..0fcc50fb0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java @@ -32,6 +32,7 @@ import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.location.Location; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.PlotWeather; import com.plotsquared.core.plot.world.PlotAreaManager; @@ -83,19 +84,21 @@ public class BukkitPlayer extends PlotPlayer { * @param player Bukkit player instance */ public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, - @Nonnull final Player player, @Nullable final EconHandler econHandler) { - this(plotAreaManager, eventDispatcher, player, false, econHandler); + @Nonnull final Player player, @Nullable final EconHandler econHandler, @Nonnull final PermissionHandler permissionHandler) { + this(plotAreaManager, eventDispatcher, player, false, econHandler, permissionHandler); } public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, - @Nonnull final Player player, final boolean offline, @Nullable final EconHandler econHandler) { - this(plotAreaManager, eventDispatcher, player, offline, true, econHandler); + @Nonnull final Player player, final boolean offline, @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { + this(plotAreaManager, eventDispatcher, player, offline, true, econHandler, permissionHandler); } public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, @Nonnull final Player player, final boolean offline, - final boolean realPlayer, @Nullable final EconHandler econHandler) { - super(plotAreaManager, eventDispatcher, econHandler); + final boolean realPlayer, @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { + super(plotAreaManager, eventDispatcher, econHandler, permissionHandler); this.player = player; this.offline = offline; this.econHandler = econHandler; @@ -161,13 +164,6 @@ public class BukkitPlayer extends PlotPlayer { } } - @Override public boolean hasPermission(final String permission) { - if (this.offline && this.econHandler != null) { - return this.econHandler.hasPermission(getName(), permission); - } - return this.player.hasPermission(permission); - } - @Override public int hasPermissionRange(final String stub, final int range) { if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { return Integer.MAX_VALUE; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java index 7238709e3..d05fafd7a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java @@ -27,6 +27,7 @@ package com.plotsquared.bukkit.player; import com.google.inject.Inject; import com.google.inject.Singleton; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EventDispatcher; @@ -46,13 +47,16 @@ import java.util.UUID; private final PlotAreaManager plotAreaManager; private final EventDispatcher eventDispatcher; private final EconHandler econHandler; + private final PermissionHandler permissionHandler; @Inject public BukkitPlayerManager(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, - @Nullable final EconHandler econHandler) { + @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { this.plotAreaManager = plotAreaManager; this.eventDispatcher = eventDispatcher; this.econHandler = econHandler; + this.permissionHandler = permissionHandler; } @Nonnull @Override public BukkitPlayer getPlayer(@Nonnull final Player object) { @@ -60,7 +64,7 @@ import java.util.UUID; return getPlayer(object.getUniqueId()); } catch (final NoSuchPlayerException exception) { return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, object, - object.isOnline(), false, this.econHandler); + object.isOnline(), false, this.econHandler, this.permissionHandler); } } @@ -69,18 +73,18 @@ import java.util.UUID; if (player == null || !player.isOnline()) { throw new NoSuchPlayerException(uuid); } - return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, player, this.econHandler); + return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, player, this.econHandler, this.permissionHandler); } @Nullable @Override public BukkitOfflinePlayer getOfflinePlayer(@Nullable final UUID uuid) { if (uuid == null) { return null; } - return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid)); + return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid), this.permissionHandler); } @Nonnull @Override public BukkitOfflinePlayer getOfflinePlayer(@Nonnull final String username) { - return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(username)); + return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(username), this.permissionHandler); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 5cbbf6cfc..1d88f9a6f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -131,7 +131,7 @@ import java.util.stream.Stream; final Player player = OfflinePlayerUtil.loadPlayer(op); player.loadData(); return new BukkitPlayer(PlotSquared.get().getPlotAreaManager(), - PlotSquared.get().getEventDispatcher(), player, true, PlotSquared.platform().getEconHandler()); + PlotSquared.get().getEventDispatcher(), player, true, PlotSquared.platform().getEconHandler(), PlotSquared.platform().getPermissionHandler()); } /** diff --git a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java index dc3136372..c84bce2b9 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java +++ b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java @@ -33,6 +33,7 @@ import com.plotsquared.core.generator.HybridUtils; import com.plotsquared.core.generator.IndependentPlotGenerator; import com.plotsquared.core.inject.annotations.DefaultGenerator; import com.plotsquared.core.location.World; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.util.ChatManager; @@ -266,4 +267,13 @@ public interface PlotPlatform

extends ILogger { return getInjector().getInstance(ChunkManager.class); } + /** + * Get the {@link PermissionHandler} implementation for the platform + * + * @return Permission handler + */ + @Nonnull default PermissionHandler getPermissionHandler() { + return getInjector().getInstance(PermissionHandler.class); + } + } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java new file mode 100644 index 000000000..09857628c --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java @@ -0,0 +1,37 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import javax.annotation.Nonnull; + +public enum ConsolePermissionProfile implements PermissionProfile { + INSTANCE; + + @Override public boolean hasPermission(@Nonnull final String permission) { + return true; + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java new file mode 100644 index 000000000..b59b5a78d --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java @@ -0,0 +1,37 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import javax.annotation.Nonnull; + +public enum NullPermissionProfile implements PermissionProfile { + INSTANCE; + + @Override public boolean hasPermission(@Nonnull final String permission) { + return false; + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java new file mode 100644 index 000000000..c88537f69 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java @@ -0,0 +1,95 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import com.plotsquared.core.player.OfflinePlotPlayer; +import com.plotsquared.core.player.PlotPlayer; + +import javax.annotation.Nonnull; +import java.util.Optional; +import java.util.Set; + +/** + * Permission handler + */ +public interface PermissionHandler { + + /** + * Initialize the permission handler + */ + void initialize(); + + /** + * Attempt to construct a permission profile for a plot player + * + * @param playerPlotPlayer Plot player + * @return Permission profile, if one was able to be constructed + */ + @Nonnull Optional getPermissionProfile( + @Nonnull PlotPlayer playerPlotPlayer); + + /** + * Attempt to construct a permission profile for an offline plot player + * + * @param offlinePlotPlayer Offline player + * @return Permission profile, if one was able to be constructed + */ + @Nonnull Optional getPermissionProfile( + @Nonnull OfflinePlotPlayer offlinePlotPlayer); + + /** + * Get all capabilities that the permission handler has + * + * @return Immutable set of capabilities + */ + @Nonnull Set getCapabilities(); + + /** + * Check whether or not the permission handler has a given capability + * + * @param capability Capability + * @return {@code true} if the handler has the capability, else {@code false} + */ + default boolean hasCapability(@Nonnull final PermissionHandlerCapability capability) { + return this.getCapabilities().contains(capability); + } + + + /** + * Permission handler capabilities + */ + enum PermissionHandlerCapability { + /** + * The ability to check for online (player) permissions + */ + ONLINE_PERMISSIONS, + /** + * The ability to check for offline (player) permissions + */ + OFFLINE_PERMISSIONS + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java new file mode 100644 index 000000000..a94bd0b39 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java @@ -0,0 +1,43 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import javax.annotation.Nonnull; + +/** + * Any object which can hold permissions + */ +public interface PermissionHolder { + + /** + * Check if the permission holder has the given permission node + * + * @param permission Permission node + * @return {@code true} if the holder has the given permission node, else {@code false} + */ + boolean hasPermission(@Nonnull String permission); + +} diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java new file mode 100644 index 000000000..912147980 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java @@ -0,0 +1,43 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.permissions; + +import javax.annotation.Nonnull; + +/** + * A permission profile that can be used to check for permissions + */ +public interface PermissionProfile { + + /** + * Check if the owner of the profile has a given permission + * + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} + */ + boolean hasPermission(@Nonnull String permission); + +} diff --git a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java index c6efe33cd..2c1e67c8f 100644 --- a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java @@ -32,6 +32,7 @@ import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.inject.annotations.ConsoleActor; import com.plotsquared.core.location.Location; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotWeather; import com.plotsquared.core.plot.world.PlotAreaManager; @@ -42,11 +43,11 @@ import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.gamemode.GameModes; import com.sk89q.worldedit.world.item.ItemType; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.UUID; public class ConsolePlayer extends PlotPlayer { @@ -59,8 +60,9 @@ public class ConsolePlayer extends PlotPlayer { @Inject private ConsolePlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, @ConsoleActor @Nonnull final Actor actor, - @Nullable final EconHandler econHandler) { - super(plotAreaManager, eventDispatcher, econHandler); + @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { + super(plotAreaManager, eventDispatcher, econHandler, permissionHandler); this.actor = actor; final PlotArea[] areas = plotAreaManager.getAllPlotAreas(); final PlotArea area; @@ -121,10 +123,6 @@ public class ConsolePlayer extends PlotPlayer { return 0; } - @Override public boolean hasPermission(String permission) { - return true; - } - @Override public boolean isPermissionSet(String permission) { return true; } diff --git a/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java index f48079f67..92a0e6536 100644 --- a/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java @@ -25,9 +25,11 @@ */ package com.plotsquared.core.player; +import com.plotsquared.core.permissions.PermissionHolder; + import java.util.UUID; -public interface OfflinePlotPlayer { +public interface OfflinePlotPlayer extends PermissionHolder { /** * Gets the {@code UUID} of this player @@ -57,4 +59,5 @@ public interface OfflinePlotPlayer { * @return the player name */ String getName(); + } diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index 6d2428d05..d3c4fd369 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -35,6 +35,9 @@ import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.location.Location; +import com.plotsquared.core.permissions.NullPermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; +import com.plotsquared.core.permissions.PermissionProfile; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotCluster; @@ -54,11 +57,11 @@ import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.item.ItemType; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Collections; @@ -95,11 +98,15 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer private final PlotAreaManager plotAreaManager; private final EventDispatcher eventDispatcher; private final EconHandler econHandler; + private final PermissionProfile permissionProfile; - public PlotPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, @Nullable final EconHandler econHandler) { + public PlotPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, @Nullable final EconHandler econHandler, + @Nonnull final PermissionHandler permissionHandler) { this.plotAreaManager = plotAreaManager; this.eventDispatcher = eventDispatcher; this.econHandler = econHandler; + this.permissionProfile = permissionHandler.getPermissionProfile(this).orElse( + NullPermissionProfile.INSTANCE); } public static PlotPlayer from(@Nonnull final T object) { @@ -147,6 +154,10 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return PlotSquared.platform().wrapPlayer(player); } + @Override public final boolean hasPermission(@Nonnull final String permission) { + return this.permissionProfile.hasPermission(permission); + } + public abstract Actor toActor(); public abstract P getPlatformPlayer(); diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java index 3e89c630a..6c1a1415d 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package com.plotsquared.core.util; import lombok.experimental.UtilityClass; diff --git a/Core/src/main/java/com/plotsquared/core/util/MainUtil.java b/Core/src/main/java/com/plotsquared/core/util/MainUtil.java index 2a96b7120..010622813 100644 --- a/Core/src/main/java/com/plotsquared/core/util/MainUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/MainUtil.java @@ -44,6 +44,53 @@ import javax.annotation.Nonnull; private static final Logger logger = LoggerFactory.getLogger("P2/" + MainUtil.class.getSimpleName()); + /** + * Cache of mapping x,y,z coordinates to the chunk array
+ * - Used for efficient world generation
+ */ + public static short[][] x_loc; + public static short[][] y_loc; + public static short[][] z_loc; + public static short[][][] CACHE_I = null; + public static short[][][] CACHE_J = null; + + /** + * This cache is used for world generation and just saves a bit of calculation time when checking if something is in the plot area. + */ + public static void initCache() { + if (x_loc == null) { + x_loc = new short[16][4096]; + y_loc = new short[16][4096]; + z_loc = new short[16][4096]; + for (int i = 0; i < 16; i++) { + int i4 = i << 4; + for (int j = 0; j < 4096; j++) { + int y = i4 + (j >> 8); + int a = j - ((y & 0xF) << 8); + int z1 = a >> 4; + int x1 = a - (z1 << 4); + x_loc[i][j] = (short) x1; + y_loc[i][j] = (short) y; + z_loc[i][j] = (short) z1; + } + } + } + if (CACHE_I == null) { + CACHE_I = new short[256][16][16]; + CACHE_J = new short[256][16][16]; + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = 0; y < 256; y++) { + short i = (short) (y >> 4); + short j = (short) ((y & 0xF) << 8 | z << 4 | x); + CACHE_I[y][x][z] = i; + CACHE_J[y][x][z] = j; + } + } + } + } + } + /** * Send a message to the player. * From b302bb93798493317442dcd6fca6a38e0692258a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Wed, 22 Jul 2020 12:06:56 +0200 Subject: [PATCH 10/25] Make VaultPermissionHandler extent BukkitPermissionHandler --- .../permissions/VaultPermissionHandler.java | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java index a7978e671..ec2724e6a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java @@ -26,13 +26,8 @@ package com.plotsquared.bukkit.permissions; import com.plotsquared.bukkit.player.BukkitOfflinePlayer; -import com.plotsquared.bukkit.player.BukkitPlayer; -import com.plotsquared.core.permissions.ConsolePermissionProfile; -import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.permissions.PermissionProfile; -import com.plotsquared.core.player.ConsolePlayer; import com.plotsquared.core.player.OfflinePlotPlayer; -import com.plotsquared.core.player.PlotPlayer; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; @@ -43,7 +38,7 @@ import java.util.EnumSet; import java.util.Optional; import java.util.Set; -public class VaultPermissionHandler implements PermissionHandler { +public class VaultPermissionHandler extends BukkitPermissionHandler { private Permission permissions; @@ -58,17 +53,6 @@ public class VaultPermissionHandler implements PermissionHandler { } } - @Nonnull @Override public Optional getPermissionProfile( - @Nonnull PlotPlayer playerPlotPlayer) { - if (playerPlotPlayer instanceof BukkitPlayer) { - final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; - return Optional.of(new VaultPermissionProfile(bukkitPlayer.getPlatformPlayer())); - } else if (playerPlotPlayer instanceof ConsolePlayer) { - return Optional.of(ConsolePermissionProfile.INSTANCE); - } - return Optional.empty(); - } - @Nonnull @Override public Optional getPermissionProfile( @Nonnull OfflinePlotPlayer offlinePlotPlayer) { if (offlinePlotPlayer instanceof BukkitOfflinePlayer) { From 5fda3e976581a9a8db9b973fdfa2247896ec256d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Wed, 22 Jul 2020 12:35:48 +0200 Subject: [PATCH 11/25] Get rid of PermHandler --- .../plotsquared/bukkit/BukkitPlatform.java | 7 +-- .../bukkit/inject/BukkitModule.java | 25 ++------ .../bukkit/inject/PermissionModule.java | 6 +- .../permissions/BukkitPermissionHandler.java | 4 +- .../permissions/VaultPermissionHandler.java | 31 ++++++++-- .../bukkit/player/BukkitOfflinePlayer.java | 6 +- .../bukkit/player/BukkitPlayer.java | 9 ++- .../bukkit/util/BukkitEconHandler.java | 23 +------ .../bukkit/util/BukkitPermHandler.java | 60 ------------------- .../com/plotsquared/core/command/Auto.java | 9 ++- .../com/plotsquared/core/command/Command.java | 3 +- .../core/command/CommandCaller.java | 10 +--- .../permissions/ConsolePermissionProfile.java | 4 +- .../permissions/NullPermissionProfile.java | 4 +- .../core/permissions/PermissionHandler.java | 6 +- .../core/permissions/PermissionHolder.java | 59 ++++++++++++++++-- .../core/permissions/PermissionProfile.java | 16 ++++- .../core/player/ConsolePlayer.java | 4 -- .../plotsquared/core/player/PlotPlayer.java | 30 +--------- .../plotsquared/core/util/EconHandler.java | 12 ---- .../plotsquared/core/util/PermHandler.java | 37 ------------ .../plotsquared/core/util/Permissions.java | 27 +++++---- 22 files changed, 152 insertions(+), 240 deletions(-) delete mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java delete mode 100644 Core/src/main/java/com/plotsquared/core/util/PermHandler.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index 030e30ce1..a31faeb2b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -105,7 +105,6 @@ import com.plotsquared.core.util.ConsoleColors; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.FileUtils; -import com.plotsquared.core.util.PermHandler; import com.plotsquared.core.util.PlatformWorldManager; import com.plotsquared.core.util.PlayerManager; import com.plotsquared.core.util.PremiumVerification; @@ -184,7 +183,6 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; private boolean methodUnloadSetup = false; private boolean metricsStarted; private EconHandler econ; - private PermHandler perm; @Getter private Injector injector; @@ -343,10 +341,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; // Economy if (Settings.Enabled_Components.ECONOMY) { TaskManager.runTask(() -> { - final PermHandler permHandler = getInjector().getInstance(PermHandler.class); - if (permHandler != null) { - permHandler.init(); - } + this.getPermissionHandler().initialize(); final EconHandler econHandler = getInjector().getInstance(EconHandler.class); if (econHandler != null) { econHandler.init(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java index b558aee4f..7599358bd 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java @@ -29,7 +29,6 @@ import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.assistedinject.FactoryModuleBuilder; -import com.google.inject.util.Providers; import com.plotsquared.bukkit.BukkitPlatform; import com.plotsquared.bukkit.player.BukkitPlayerManager; import com.plotsquared.bukkit.queue.BukkitLocalQueue; @@ -37,12 +36,9 @@ import com.plotsquared.bukkit.schematic.BukkitSchematicHandler; import com.plotsquared.bukkit.util.BukkitChunkManager; import com.plotsquared.bukkit.util.BukkitEconHandler; import com.plotsquared.bukkit.util.BukkitInventoryUtil; -import com.plotsquared.bukkit.util.BukkitPermHandler; import com.plotsquared.bukkit.util.BukkitRegionManager; import com.plotsquared.bukkit.util.BukkitSetupUtils; import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.bukkit.util.task.PaperTimeConverter; -import com.plotsquared.bukkit.util.task.SpigotTimeConverter; import com.plotsquared.core.PlotPlatform; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.generator.HybridGen; @@ -58,7 +54,6 @@ import com.plotsquared.core.queue.QueueProvider; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.InventoryUtil; -import com.plotsquared.core.util.PermHandler; import com.plotsquared.core.util.PlayerManager; import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.SchematicHandler; @@ -70,7 +65,9 @@ import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.plugin.java.JavaPlugin; + import javax.annotation.Nonnull; +import javax.annotation.Nullable; @RequiredArgsConstructor public class BukkitModule extends AbstractModule { @@ -93,7 +90,6 @@ import javax.annotation.Nonnull; bind(ChunkManager.class).to(BukkitChunkManager.class); bind(RegionManager.class).to(BukkitRegionManager.class); bind(SchematicHandler.class).to(BukkitSchematicHandler.class); - this.setupVault(); if (Settings.Enabled_Components.WORLDS) { bind(PlotAreaManager.class).to(SinglePlotAreaManager.class); } else { @@ -102,25 +98,14 @@ import javax.annotation.Nonnull; install(new FactoryModuleBuilder().build(HybridPlotWorldFactory.class)); } - private void setupVault() { + @Provides @Singleton @Nullable EconHandler provideEconHandler() { if (Bukkit.getPluginManager().isPluginEnabled("Vault")) { - BukkitPermHandler bukkitPermHandler = null; try { - bukkitPermHandler = new BukkitPermHandler(); - bind(PermHandler.class).toInstance(bukkitPermHandler); + return new BukkitEconHandler(); } catch (final Exception ignored) { - bind(PermHandler.class).toProvider(Providers.of(null)); } - try { - final BukkitEconHandler bukkitEconHandler = new BukkitEconHandler(bukkitPermHandler); - bind(EconHandler.class).toInstance(bukkitEconHandler); - } catch (final Exception ignored) { - bind(EconHandler.class).toProvider(Providers.of(null)); - } - } else { - bind(PermHandler.class).toProvider(Providers.of(null)); - bind(EconHandler.class).toProvider(Providers.of(null)); } + return null; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java index b22cb3648..de42d884a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/PermissionModule.java @@ -31,17 +31,13 @@ import com.google.inject.Singleton; import com.plotsquared.bukkit.permissions.BukkitPermissionHandler; import com.plotsquared.bukkit.permissions.VaultPermissionHandler; import com.plotsquared.core.permissions.PermissionHandler; -import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; -import org.bukkit.plugin.RegisteredServiceProvider; public class PermissionModule extends AbstractModule { @Provides @Singleton PermissionHandler providePermissionHandler() { try { - RegisteredServiceProvider permissionProvider = - Bukkit.getServer().getServicesManager().getRegistration(Permission.class); - if (permissionProvider != null) { + if (Bukkit.getPluginManager().isPluginEnabled("Vault")) { return new VaultPermissionHandler(); } } catch (final Exception ignored) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java index bceecda3e..6aca7ea62 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java @@ -35,6 +35,7 @@ import com.plotsquared.core.player.PlotPlayer; import org.bukkit.entity.Player; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.EnumSet; import java.util.Optional; @@ -74,7 +75,8 @@ public class BukkitPermissionHandler implements PermissionHandler { this.playerReference = new WeakReference<>(player); } - @Override public boolean hasPermission(@Nonnull final String permission) { + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { final Player player = this.playerReference.get(); return player != null && player.hasPermission(permission); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java index ec2724e6a..b7b08a49f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java @@ -26,19 +26,25 @@ package com.plotsquared.bukkit.permissions; import com.plotsquared.bukkit.player.BukkitOfflinePlayer; +import com.plotsquared.bukkit.player.BukkitPlayer; +import com.plotsquared.core.permissions.ConsolePermissionProfile; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.permissions.PermissionProfile; +import com.plotsquared.core.player.ConsolePlayer; import com.plotsquared.core.player.OfflinePlotPlayer; +import com.plotsquared.core.player.PlotPlayer; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.plugin.RegisteredServiceProvider; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.EnumSet; import java.util.Optional; import java.util.Set; -public class VaultPermissionHandler extends BukkitPermissionHandler { +public class VaultPermissionHandler implements PermissionHandler { private Permission permissions; @@ -53,6 +59,17 @@ public class VaultPermissionHandler extends BukkitPermissionHandler { } } + @Nonnull @Override public Optional getPermissionProfile( + @Nonnull PlotPlayer playerPlotPlayer) { + if (playerPlotPlayer instanceof BukkitPlayer) { + final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; + return Optional.of(new VaultPermissionProfile(bukkitPlayer.getPlatformPlayer())); + } else if (playerPlotPlayer instanceof ConsolePlayer) { + return Optional.of(ConsolePermissionProfile.INSTANCE); + } + return Optional.empty(); + } + @Nonnull @Override public Optional getPermissionProfile( @Nonnull OfflinePlotPlayer offlinePlotPlayer) { if (offlinePlotPlayer instanceof BukkitOfflinePlayer) { @@ -62,7 +79,9 @@ public class VaultPermissionHandler extends BukkitPermissionHandler { } @Nonnull @Override public Set getCapabilities() { - return EnumSet.of(PermissionHandlerCapability.ONLINE_PERMISSIONS, PermissionHandlerCapability.OFFLINE_PERMISSIONS); + return EnumSet.of(PermissionHandlerCapability.PER_WORLD_PERMISSIONS, + PermissionHandlerCapability.ONLINE_PERMISSIONS, + PermissionHandlerCapability.OFFLINE_PERMISSIONS); } @@ -74,11 +93,15 @@ public class VaultPermissionHandler extends BukkitPermissionHandler { this.offlinePlayer = offlinePlayer; } - @Override public boolean hasPermission(@Nonnull final String permission) { + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { if (permissions == null) { return false; } - return permissions.playerHas(null, offlinePlayer, permission); + if (world == null && offlinePlayer instanceof BukkitPlayer) { + return permissions.playerHas(((BukkitPlayer) offlinePlayer).getPlatformPlayer(), permission); + } + return permissions.playerHas(world, offlinePlayer, permission); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java index e9c74dfb9..9226c5847 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java @@ -31,6 +31,7 @@ import com.plotsquared.core.permissions.PermissionProfile; import com.plotsquared.core.player.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.UUID; @@ -68,8 +69,9 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { return this.player.getName(); } - @Override public boolean hasPermission(@Nonnull final String permission) { - return this.permissionProfile.hasPermission(permission); + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { + return this.permissionProfile.hasPermission(world, permission); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java index 0fcc50fb0..1415c2840 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java @@ -54,6 +54,8 @@ import org.bukkit.event.EventException; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.RegisteredListener; + +import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -164,7 +166,8 @@ public class BukkitPlayer extends PlotPlayer { } } - @Override public int hasPermissionRange(final String stub, final int range) { + @Override @Nonnegative public int hasPermissionRange(@Nonnull final String stub, + @Nonnegative final int range) { if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { return Integer.MAX_VALUE; } @@ -224,10 +227,6 @@ public class BukkitPlayer extends PlotPlayer { return max; } - @Override public boolean isPermissionSet(final String permission) { - return this.player.isPermissionSet(permission); - } - @Override public void sendMessage(String message) { message = message.replace('\u2010', '%').replace('\u2020', '&').replace('\u2030', '&'); if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || ( diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java index c7356c13b..470fbbfbb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java @@ -25,31 +25,21 @@ */ package com.plotsquared.bukkit.util; -import com.google.inject.Inject; import com.google.inject.Singleton; import com.plotsquared.bukkit.player.BukkitOfflinePlayer; import com.plotsquared.bukkit.player.BukkitPlayer; import com.plotsquared.core.player.OfflinePlotPlayer; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.util.EconHandler; -import com.plotsquared.core.util.PermHandler; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.plugin.RegisteredServiceProvider; -import javax.annotation.Nullable; @Singleton public class BukkitEconHandler extends EconHandler { private Economy econ; - private final PermHandler permHandler; - - @Inject public BukkitEconHandler(@Nullable final PermHandler permHandler) { - this.permHandler = permHandler; - } - - @Override - public boolean init() { + @Override public boolean init() { if (this.econ == null) { setupEconomy(); } @@ -87,17 +77,6 @@ import javax.annotation.Nullable; this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount); } - /** - * @deprecated Use {@link PermHandler#hasPermission(String, String, String)} instead - */ - @Deprecated @Override public boolean hasPermission(String world, String player, String perm) { - if (this.permHandler != null) { - return this.permHandler.hasPermission(world, player, perm); - } else { - return false; - } - } - @Override public double getBalance(PlotPlayer player) { return this.econ.getBalance(player.getName()); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java deleted file mode 100644 index 8987e3527..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.plotsquared.bukkit.util; - -import com.google.inject.Singleton; -import com.plotsquared.core.util.PermHandler; -import net.milkbowl.vault.permission.Permission; -import org.bukkit.Bukkit; -import org.bukkit.plugin.RegisteredServiceProvider; - -@Singleton public class BukkitPermHandler extends PermHandler { - - private Permission perms; - - @Override - public boolean init() { - if (this.perms == null) { - setupPermissions(); - } - return this.perms != null; - } - - private void setupPermissions() { - if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { - return; - } - RegisteredServiceProvider permissionProvider = - Bukkit.getServer().getServicesManager().getRegistration(Permission.class); - if (permissionProvider != null) { - this.perms = permissionProvider.getProvider(); - } - } - - @Override public boolean hasPermission(String world, String player, String perm) { - return this.perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm); - } -} diff --git a/Core/src/main/java/com/plotsquared/core/command/Auto.java b/Core/src/main/java/com/plotsquared/core/command/Auto.java index ea6a6cf6c..211f5f22f 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Auto.java +++ b/Core/src/main/java/com/plotsquared/core/command/Auto.java @@ -37,6 +37,7 @@ import com.plotsquared.core.events.PlayerAutoPlotEvent; import com.plotsquared.core.events.PlotAutoMergeEvent; import com.plotsquared.core.events.Result; import com.plotsquared.core.events.TeleportCause; +import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -175,9 +176,11 @@ public class Auto extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { PlotArea plotarea = player.getApplicablePlotArea(); if (plotarea == null) { - if (this.econHandler != null) { - for (PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - if (this.econHandler.hasPermission(area.getWorldName(), player.getName(), "plots.auto")) { + final PermissionHandler permissionHandler = PlotSquared.platform().getPermissionHandler(); + if (permissionHandler.hasCapability( + PermissionHandler.PermissionHandlerCapability.PER_WORLD_PERMISSIONS)) { + for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { + if (player.hasPermission(area.getWorldName(), "plots.auto")) { if (plotarea != null) { plotarea = null; break; diff --git a/Core/src/main/java/com/plotsquared/core/command/Command.java b/Core/src/main/java/com/plotsquared/core/command/Command.java index a0dbe9079..60512dd5a 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Command.java +++ b/Core/src/main/java/com/plotsquared/core/command/Command.java @@ -35,6 +35,7 @@ import com.plotsquared.core.util.StringComparison; import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.task.RunnableVal2; import com.plotsquared.core.util.task.RunnableVal3; +import com.plotsquared.core.permissions.PermissionHolder; import lombok.SneakyThrows; import javax.annotation.Nonnull; @@ -158,7 +159,7 @@ public abstract class Command { return this.allCommands; } - public boolean hasConfirmation(CommandCaller player) { + public boolean hasConfirmation(PermissionHolder player) { return this.confirmation && !player.hasPermission(getPermission() + ".confirm.bypass"); } diff --git a/Core/src/main/java/com/plotsquared/core/command/CommandCaller.java b/Core/src/main/java/com/plotsquared/core/command/CommandCaller.java index b26eed517..f7a6c6885 100644 --- a/Core/src/main/java/com/plotsquared/core/command/CommandCaller.java +++ b/Core/src/main/java/com/plotsquared/core/command/CommandCaller.java @@ -34,14 +34,6 @@ public interface CommandCaller { */ void sendMessage(String message); - /** - * Check the player's permissions. Will be cached if permission caching is enabled. - * - * @param permission the name of the permission - */ - boolean hasPermission(String permission); - - boolean isPermissionSet(String permission); - RequiredType getSuperCaller(); + } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java index 09857628c..783f605a7 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/ConsolePermissionProfile.java @@ -26,11 +26,13 @@ package com.plotsquared.core.permissions; import javax.annotation.Nonnull; +import javax.annotation.Nullable; public enum ConsolePermissionProfile implements PermissionProfile { INSTANCE; - @Override public boolean hasPermission(@Nonnull final String permission) { + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { return true; } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java index b59b5a78d..fbf7d8a03 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/NullPermissionProfile.java @@ -26,11 +26,13 @@ package com.plotsquared.core.permissions; import javax.annotation.Nonnull; +import javax.annotation.Nullable; public enum NullPermissionProfile implements PermissionProfile { INSTANCE; - @Override public boolean hasPermission(@Nonnull final String permission) { + @Override public boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { return false; } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java index c88537f69..4a273c743 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHandler.java @@ -89,7 +89,11 @@ public interface PermissionHandler { /** * The ability to check for offline (player) permissions */ - OFFLINE_PERMISSIONS + OFFLINE_PERMISSIONS, + /** + * Per world permissions + */ + PER_WORLD_PERMISSIONS } } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java index a94bd0b39..abff13262 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java @@ -25,7 +25,12 @@ */ package com.plotsquared.core.permissions; +import com.plotsquared.core.configuration.Captions; +import com.plotsquared.core.configuration.Settings; + +import javax.annotation.Nonnegative; import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * Any object which can hold permissions @@ -33,11 +38,57 @@ import javax.annotation.Nonnull; public interface PermissionHolder { /** - * Check if the permission holder has the given permission node + * Check if the owner of the profile has a given (global) permission * - * @param permission Permission node - * @return {@code true} if the holder has the given permission node, else {@code false} + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} */ - boolean hasPermission(@Nonnull String permission); + default boolean hasPermission(@Nonnull final String permission) { + return hasPermission(null ,permission); + } + + /** + * Check the the highest permission a PlotPlayer has within a specified range.
+ * - Excessively high values will lag
+ * - The default range that is checked is {@link Settings.Limit#MAX_PLOTS}
+ * + * @param stub The permission stub to check e.g. for `plots.plot.#` the stub is `plots.plot` + * @param range The range to check + * @return The highest permission they have within that range + */ + @Nonnegative default int hasPermissionRange(@Nonnull final String stub, + @Nonnegative final int range) { + if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { + return Integer.MAX_VALUE; + } + String[] nodes = stub.split("\\."); + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < (nodes.length - 1); i++) { + builder.append(nodes[i]).append("."); + if (!stub.equals(builder + Captions.PERMISSION_STAR.getTranslated())) { + if (hasPermission(builder + Captions.PERMISSION_STAR.getTranslated())) { + return Integer.MAX_VALUE; + } + } + } + if (hasPermission(stub + ".*")) { + return Integer.MAX_VALUE; + } + for (int i = range; i > 0; i--) { + if (hasPermission(stub + "." + i)) { + return i; + } + } + return 0; + } + + /** + * Check if the owner of the profile has a given permission + * + * @param world World name + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} + */ + boolean hasPermission(@Nullable final String world, @Nonnull String permission); } diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java index 912147980..b7aad8e63 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionProfile.java @@ -26,6 +26,7 @@ package com.plotsquared.core.permissions; import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * A permission profile that can be used to check for permissions @@ -33,11 +34,22 @@ import javax.annotation.Nonnull; public interface PermissionProfile { /** - * Check if the owner of the profile has a given permission + * Check if the owner of the profile has a given (global) permission * * @param permission Permission * @return {@code true} if the owner has the given permission, else {@code false} */ - boolean hasPermission(@Nonnull String permission); + default boolean hasPermission(@Nonnull final String permission) { + return hasPermission(null ,permission); + } + + /** + * Check if the owner of the profile has a given permission + * + * @param world World name + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} + */ + boolean hasPermission(@Nullable final String world, @Nonnull String permission); } diff --git a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java index 2c1e67c8f..437e86491 100644 --- a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java @@ -123,10 +123,6 @@ public class ConsolePlayer extends PlotPlayer { return 0; } - @Override public boolean isPermissionSet(String permission) { - return true; - } - @Override public void sendMessage(String message) { logger.info(message); } diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index d3c4fd369..666d5be7b 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -154,8 +154,9 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return PlotSquared.platform().wrapPlayer(player); } - @Override public final boolean hasPermission(@Nonnull final String permission) { - return this.permissionProfile.hasPermission(permission); + @Override public final boolean hasPermission(@Nullable final String world, + @Nonnull final String permission) { + return this.permissionProfile.hasPermission(world, permission); } public abstract Actor toActor(); @@ -257,31 +258,6 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return Permissions.hasPermissionRange(this, "plots.cluster", Settings.Limit.MAX_PLOTS); } - public int hasPermissionRange(String stub, int range) { - if (hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { - return Integer.MAX_VALUE; - } - String[] nodes = stub.split("\\."); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < (nodes.length - 1); i++) { - builder.append(nodes[i]).append("."); - if (!stub.equals(builder + Captions.PERMISSION_STAR.getTranslated())) { - if (hasPermission(builder + Captions.PERMISSION_STAR.getTranslated())) { - return Integer.MAX_VALUE; - } - } - } - if (hasPermission(stub + ".*")) { - return Integer.MAX_VALUE; - } - for (int i = range; i > 0; i--) { - if (hasPermission(stub + "." + i)) { - return i; - } - } - return 0; - } - /** * Get the number of plots this player owns. * diff --git a/Core/src/main/java/com/plotsquared/core/util/EconHandler.java b/Core/src/main/java/com/plotsquared/core/util/EconHandler.java index 69363079f..508fe8f57 100644 --- a/Core/src/main/java/com/plotsquared/core/util/EconHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/EconHandler.java @@ -48,16 +48,4 @@ public abstract class EconHandler { public abstract void depositMoney(OfflinePlotPlayer player, double amount); - /** - * @deprecated Use {@link PermHandler#hasPermission(String, String, String)} instead - */ - @Deprecated public abstract boolean hasPermission(String world, String player, String perm); - - /** - * @deprecated Use {@link PermHandler#hasPermission(String, String)} instead - */ - @Deprecated public boolean hasPermission(String player, String perm) { - return hasPermission(null, player, perm); - } - } diff --git a/Core/src/main/java/com/plotsquared/core/util/PermHandler.java b/Core/src/main/java/com/plotsquared/core/util/PermHandler.java deleted file mode 100644 index 1dec45fd4..000000000 --- a/Core/src/main/java/com/plotsquared/core/util/PermHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.plotsquared.core.util; - -public abstract class PermHandler { - - public abstract boolean init(); - - public abstract boolean hasPermission(String world, String player, String perm); - - public boolean hasPermission(String player, String perm) { - return hasPermission(null, player, perm); - } -} diff --git a/Core/src/main/java/com/plotsquared/core/util/Permissions.java b/Core/src/main/java/com/plotsquared/core/util/Permissions.java index 34754e7c8..7e3b4622f 100644 --- a/Core/src/main/java/com/plotsquared/core/util/Permissions.java +++ b/Core/src/main/java/com/plotsquared/core/util/Permissions.java @@ -29,6 +29,7 @@ import com.plotsquared.core.command.CommandCaller; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.player.PlotPlayer; +import com.plotsquared.core.permissions.PermissionHolder; import java.util.HashMap; @@ -39,7 +40,7 @@ import java.util.HashMap; */ public class Permissions { - public static boolean hasPermission(PlotPlayer player, Captions caption, boolean notify) { + public static boolean hasPermission(PlotPlayer player, Captions caption, boolean notify) { return hasPermission(player, caption.getTranslated(), notify); } @@ -50,7 +51,7 @@ public class Permissions { * @param caption * @return */ - public static boolean hasPermission(PlotPlayer player, Captions caption) { + public static boolean hasPermission(PlotPlayer player, Captions caption) { return hasPermission(player, caption.getTranslated()); } @@ -63,7 +64,7 @@ public class Permissions { */ public static boolean hasPermission(PlotPlayer player, String permission) { if (!Settings.Enabled_Components.PERMISSION_CACHE) { - return hasPermission((CommandCaller) player, permission); + return hasPermission((PermissionHolder) player, permission); } HashMap map = player.getMeta("perm"); if (map != null) { @@ -75,7 +76,7 @@ public class Permissions { map = new HashMap<>(); player.setMeta("perm", map); } - boolean result = hasPermission((CommandCaller) player, permission); + boolean result = hasPermission((PermissionHolder) player, permission); map.put(permission, result); return result; } @@ -87,12 +88,12 @@ public class Permissions { * @param permission * @return */ - public static boolean hasPermission(CommandCaller caller, String permission) { + public static boolean hasPermission(PermissionHolder caller, String permission) { if (caller.hasPermission(permission)) { return true; - } else if (caller.isPermissionSet(permission)) { + }/* TODO: DECIDE WHAT TO DO HERE; else if (caller.isPermissionSet(permission)) { return false; - } + }*/ if (caller.hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { return true; } @@ -105,9 +106,9 @@ public class Permissions { if (!permission.equals(combined)) { if (caller.hasPermission(combined)) { return true; - } else if (caller.isPermissionSet(combined)) { + }/* TODO: DECIDE WHAT TO DO HERE; else if (caller.isPermissionSet(combined)) { return false; - } + }*/ } } return false; @@ -121,7 +122,7 @@ public class Permissions { * @param notify * @return */ - public static boolean hasPermission(PlotPlayer player, String permission, boolean notify) { + public static boolean hasPermission(PlotPlayer player, String permission, boolean notify) { if (!hasPermission(player, permission)) { if (notify) { MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, permission); @@ -131,7 +132,7 @@ public class Permissions { return true; } - public static int hasPermissionRange(PlotPlayer player, Captions perm, int range) { + public static int hasPermissionRange(PlotPlayer player, Captions perm, int range) { return hasPermissionRange(player, perm.getTranslated(), range); } @@ -140,12 +141,12 @@ public class Permissions { * - Excessively high values will lag
* - The default range that is checked is {@link Settings.Limit#MAX_PLOTS}
* - * @param player + * @param player Player to check for * @param stub The permission stub to check e.g. for `plots.plot.#` the stub is `plots.plot` * @param range The range to check * @return The highest permission they have within that range */ - public static int hasPermissionRange(PlotPlayer player, String stub, int range) { + public static int hasPermissionRange(PlotPlayer player, String stub, int range) { return player.hasPermissionRange(stub, range); } } From 2154e237ff9f221ca02588de285050767956fec5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 12:47:00 +0200 Subject: [PATCH 12/25] Remove construction of fake player entities for offline players. --- .../plotsquared/bukkit/BukkitPlatform.java | 36 +---- .../bukkit/player/BukkitOfflinePlayer.java | 12 +- .../bukkit/player/BukkitPlayer.java | 19 +-- .../bukkit/player/BukkitPlayerManager.java | 6 +- .../plotsquared/bukkit/util/BukkitUtil.java | 32 ----- .../bukkit/util/OfflinePlayerUtil.java | 133 ------------------ .../java/com/plotsquared/core/PlotAPI.java | 12 +- .../com/plotsquared/core/PlotPlatform.java | 11 +- .../com/plotsquared/core/command/Buy.java | 2 +- .../core/listener/PlotListener.java | 4 +- .../core/listener/WESubscriber.java | 3 +- .../core/player/ConsolePlayer.java | 6 +- .../core/player/OfflinePlotPlayer.java | 11 +- .../plotsquared/core/player/PlotPlayer.java | 14 -- .../java/com/plotsquared/core/plot/Plot.java | 13 +- .../core/plot/expiration/ExpireManager.java | 4 +- .../com/plotsquared/core/util/WorldUtil.java | 8 -- 17 files changed, 40 insertions(+), 286 deletions(-) delete mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index a31faeb2b..3c39850e7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -573,7 +573,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } final Plot plot = area.getOwnedPlot(id); if (plot != null) { - if (!plot.getFlag(ServerPlotFlag.class) || PlotPlayer.wrap(plot.getOwner()) == null) { + if (!plot.getFlag(ServerPlotFlag.class) || PlotSquared.platform().getPlayerManager() + .getPlayerIfExists(plot.getOwner()) == null) { if (world.getKeepSpawnInMemory()) { world.setKeepSpawnInMemory(false); return; @@ -1081,39 +1082,6 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } } - /** - * Attempt to retrieve a {@link PlotPlayer} from a player identifier. - * This method accepts: - * - {@link Player} objects, - * - {@link OfflinePlayer} objects, - * - {@link String} usernames for online players, and - * - {@link UUID} UUIDs for online players - *

- * In the case of offline players, a fake {@link Player} instance will be created. - * This is a rather expensive operation, and should be avoided if possible. - * - * @param player The player to convert to a PlotPlayer - * @return The plot player instance that corresponds to the identifier, or null - * if no such player object could be created - */ - @Override @Nullable public PlotPlayer wrapPlayer(final Object player) { - if (player instanceof Player) { - return BukkitUtil.adapt((Player) player); - } - if (player instanceof OfflinePlayer) { - return BukkitUtil.adapt((OfflinePlayer) player); - } - if (player instanceof String) { - return (PlotPlayer) PlotSquared.platform().getPlayerManager() - .getPlayerIfExists((String) player); - } - if (player instanceof UUID) { - return (PlotPlayer) PlotSquared.platform().getPlayerManager() - .getPlayerIfExists((UUID) player); - } - return null; - } - @Override public String getNMSPackage() { final String name = Bukkit.getServer().getClass().getPackage().getName(); return name.substring(name.lastIndexOf('.') + 1); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java index 9226c5847..799fbf2b1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java @@ -30,6 +30,8 @@ import com.plotsquared.core.permissions.PermissionHandler; import com.plotsquared.core.permissions.PermissionProfile; import com.plotsquared.core.player.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; + +import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -43,8 +45,6 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { /** * Please do not use this method. Instead use BukkitUtil.getPlayer(Player), * as it caches player objects. - * - * @param player */ public BukkitOfflinePlayer(@Nonnull final OfflinePlayer player, @Nonnull final PermissionHandler permissionHandler) { @@ -57,12 +57,8 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { return this.player.getUniqueId(); } - @Override public long getLastPlayed() { - return this.player.getLastPlayed(); - } - - @Override public boolean isOnline() { - return this.player.isOnline(); + @Override @Nonnegative public long getLastPlayed() { + return this.player.getLastSeen(); } @Override public String getName() { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java index 1415c2840..b66eed10f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java @@ -75,10 +75,8 @@ public class BukkitPlayer extends PlotPlayer { private final EconHandler econHandler; public final Player player; - private boolean offline; private String name; - /** *

Please do not use this method. Instead use * BukkitUtil.getPlayer(Player), as it caches player objects.

@@ -90,19 +88,12 @@ public class BukkitPlayer extends PlotPlayer { this(plotAreaManager, eventDispatcher, player, false, econHandler, permissionHandler); } - public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher, - @Nonnull final Player player, final boolean offline, @Nullable final EconHandler econHandler, - @Nonnull final PermissionHandler permissionHandler) { - this(plotAreaManager, eventDispatcher, player, offline, true, econHandler, permissionHandler); - } - public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final - EventDispatcher eventDispatcher, @Nonnull final Player player, final boolean offline, + EventDispatcher eventDispatcher, @Nonnull final Player player, final boolean realPlayer, @Nullable final EconHandler econHandler, @Nonnull final PermissionHandler permissionHandler) { super(plotAreaManager, eventDispatcher, econHandler, permissionHandler); this.player = player; - this.offline = offline; this.econHandler = econHandler; if (realPlayer) { super.populatePersistentMetaMap(); @@ -130,8 +121,8 @@ public class BukkitPlayer extends PlotPlayer { return player.getUniqueId(); } - @Override public long getLastPlayed() { - return this.player.getLastPlayed(); + @Override @Nonnegative public long getLastPlayed() { + return this.player.getLastSeen(); } @Override public boolean canTeleport(@Nonnull final Location location) { @@ -255,10 +246,6 @@ public class BukkitPlayer extends PlotPlayer { return this.name; } - @Override public boolean isOnline() { - return !this.offline && this.player.isOnline(); - } - @Override public void setCompassTarget(Location location) { this.player.setCompassTarget( new org.bukkit.Location(BukkitUtil.getWorld(location.getWorldName()), location.getX(), diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java index d05fafd7a..78af765a2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java @@ -60,11 +60,13 @@ import java.util.UUID; } @Nonnull @Override public BukkitPlayer getPlayer(@Nonnull final Player object) { + if (!object.isOnline()) { + throw new NoSuchPlayerException(object.getUniqueId()); + } try { return getPlayer(object.getUniqueId()); } catch (final NoSuchPlayerException exception) { - return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, object, - object.isOnline(), false, this.econHandler, this.permissionHandler); + return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, object, false, this.econHandler, this.permissionHandler); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 1d88f9a6f..3537c25a2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -53,7 +53,6 @@ import io.papermc.lib.PaperLib; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; -import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; @@ -101,7 +100,6 @@ import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; -import java.util.UUID; import java.util.function.Consumer; import java.util.function.IntConsumer; import java.util.stream.Stream; @@ -116,24 +114,6 @@ import java.util.stream.Stream; super(regionManager); } - /** - * Get a {@link PlotPlayer} from an {@link OfflinePlayer}. If the player is - * online, it returns a complete player. If the player is offline, it creates - * a fake player - * - * @param op Offline player - * @return Plot player instance - */ - @Nonnull public static PlotPlayer adapt(@Nonnull final OfflinePlayer op) { - if (op.isOnline()) { - return adapt(Objects.requireNonNull(op.getPlayer())); - } - final Player player = OfflinePlayerUtil.loadPlayer(op); - player.loadData(); - return new BukkitPlayer(PlotSquared.get().getPlotAreaManager(), - PlotSquared.get().getEventDispatcher(), player, true, PlotSquared.platform().getEconHandler(), PlotSquared.platform().getPermissionHandler()); - } - /** * Turn a Bukkit {@link Player} into a PlotSquared {@link PlotPlayer} * @@ -214,18 +194,6 @@ import java.util.stream.Stream; } } - /** - * Gets the PlotPlayer for a UUID. The PlotPlayer is usually cached and - * will provide useful functions relating to players. - * - * @param uuid the uuid to wrap - * @return a {@code PlotPlayer} - * @see PlotPlayer#wrap(Object) - */ - @Override @Nonnull public PlotPlayer getPlayer(@Nonnull final UUID uuid) { - return PlotPlayer.wrap(Bukkit.getOfflinePlayer(uuid)); - } - @Override public boolean isBlockSame(@Nonnull final BlockState block1, @Nonnull final BlockState block2) { if (block1.equals(block2)) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java deleted file mode 100644 index 41ae4dedd..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.plotsquared.bukkit.util; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.UUID; - -import static com.plotsquared.core.util.ReflectionUtils.callConstructor; -import static com.plotsquared.core.util.ReflectionUtils.callMethod; -import static com.plotsquared.core.util.ReflectionUtils.getCbClass; -import static com.plotsquared.core.util.ReflectionUtils.getField; -import static com.plotsquared.core.util.ReflectionUtils.getNmsClass; -import static com.plotsquared.core.util.ReflectionUtils.getUtilClass; -import static com.plotsquared.core.util.ReflectionUtils.makeConstructor; -import static com.plotsquared.core.util.ReflectionUtils.makeField; -import static com.plotsquared.core.util.ReflectionUtils.makeMethod; - -public class OfflinePlayerUtil { - - public static Player loadPlayer(OfflinePlayer player) { - if (player == null) { - return null; - } - if (player instanceof Player) { - return (Player) player; - } - return loadPlayer(player.getUniqueId(), player.getName()); - } - - private static Player loadPlayer(UUID id, String name) { - Object server = getMinecraftServer(); - Object interactManager = newPlayerInteractManager(); - Object worldServer = getWorldServer(); - Object profile = newGameProfile(id, name); - Class entityPlayerClass = getNmsClass("EntityPlayer"); - Constructor entityPlayerConstructor = - makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), - getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"), - getNmsClass("PlayerInteractManager")); - Object entityPlayer = - callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); - return (Player) getBukkitEntity(entityPlayer); - } - - private static Object newGameProfile(UUID id, String name) { - Class gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile"); - if (gameProfileClass == null) { //Before uuids - return name; - } - Constructor gameProfileConstructor = - makeConstructor(gameProfileClass, UUID.class, String.class); - if (gameProfileConstructor == null) { //Version has string constructor - gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class); - return callConstructor(gameProfileConstructor, id.toString(), name); - } else { //Version has uuid constructor - return callConstructor(gameProfileConstructor, id, name); - } - } - - private static Object newPlayerInteractManager() { - Object worldServer = getWorldServer(); - Class playerInteractClass = getNmsClass("PlayerInteractManager"); - Class worldClass = getNmsClass("World"); - Constructor c = makeConstructor(playerInteractClass, worldClass); - if (c == null) { - c = makeConstructor(playerInteractClass, getNmsClass("WorldServer")); - } - return callConstructor(c, worldServer); - } - - public static Object getWorldServerNew() { - Object server = getMinecraftServer(); - Class minecraftServerClass = getNmsClass("MinecraftServer"); - Class dimensionManager = getNmsClass("DimensionManager"); - Object overworld = getField(makeField(dimensionManager, "OVERWORLD"), null); - Method getWorldServer = - makeMethod(minecraftServerClass, "getWorldServer", dimensionManager); - return callMethod(getWorldServer, server, overworld); - } - - private static Object getWorldServer() { - Object server = getMinecraftServer(); - Class minecraftServerClass = getNmsClass("MinecraftServer"); - Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class); - Object o; - try { - o = callMethod(getWorldServer, server, 0); - } catch (final RuntimeException e) { - o = getWorldServerNew(); - } - return o; - } - - //NMS Utils - - private static Object getMinecraftServer() { - return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer()); - } - - private static Entity getBukkitEntity(Object o) { - Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity"); - return callMethod(getBukkitEntity, o); - } -} diff --git a/Core/src/main/java/com/plotsquared/core/PlotAPI.java b/Core/src/main/java/com/plotsquared/core/PlotAPI.java index 9a83aae5e..1450a3f4e 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotAPI.java +++ b/Core/src/main/java/com/plotsquared/core/PlotAPI.java @@ -39,6 +39,8 @@ import com.plotsquared.core.util.SchematicHandler; import com.plotsquared.core.util.query.PlotQuery; import lombok.NoArgsConstructor; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Collections; import java.util.Set; import java.util.UUID; @@ -178,10 +180,9 @@ import java.util.UUID; * * @param uuid the uuid of the player to wrap * @return a {@code PlotPlayer} - * @see PlotPlayer#wrap(Object) */ - public PlotPlayer wrapPlayer(UUID uuid) { - return PlotPlayer.wrap(uuid); + @Nullable public PlotPlayer wrapPlayer(@Nonnull final UUID uuid) { + return PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); } /** @@ -189,10 +190,9 @@ import java.util.UUID; * * @param player the player to wrap * @return a {@code PlotPlayer} - * @see PlotPlayer#wrap(Object) */ - public PlotPlayer wrapPlayer(String player) { - return PlotPlayer.wrap(player); + @Nullable public PlotPlayer wrapPlayer(@Nonnull final String player) { + return PlotSquared.platform().getPlayerManager().getPlayerIfExists(player); } /** diff --git a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java index c84bce2b9..51f5ff6e1 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java +++ b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java @@ -27,6 +27,7 @@ package com.plotsquared.core; import com.google.inject.Injector; import com.google.inject.Key; +import com.google.inject.TypeLiteral; import com.plotsquared.core.backup.BackupManager; import com.plotsquared.core.generator.GeneratorWrapper; import com.plotsquared.core.generator.HybridUtils; @@ -80,14 +81,6 @@ public interface PlotPlatform

extends ILogger { */ File getWorldContainer(); - /** - * Wraps a player into a PlotPlayer object. - * - * @param player The player to convert to a PlotPlayer - * @return A PlotPlayer - */ - @Nullable PlotPlayer

wrapPlayer(Object player); - /** * Completely shuts down the plugin. */ @@ -186,7 +179,7 @@ public interface PlotPlatform

extends ILogger { * @return Player manager */ @Nonnull default PlayerManager, ? extends P> getPlayerManager() { - return getInjector().getInstance(PlayerManager.class); + return getInjector().getInstance(Key.get(new TypeLiteral, ? extends P>>() {})); } /** diff --git a/Core/src/main/java/com/plotsquared/core/command/Buy.java b/Core/src/main/java/com/plotsquared/core/command/Buy.java index 88f4dd4af..8fe688834 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Buy.java +++ b/Core/src/main/java/com/plotsquared/core/command/Buy.java @@ -93,7 +93,7 @@ public class Buy extends Command { this.econHandler.depositMoney(PlotSquared.platform().getPlayerManager().getOfflinePlayer(plot.getOwnerAbs()), price); - PlotPlayer owner = PlotSquared.platform().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs()); + PlotPlayer owner = PlotSquared.platform().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs()); if (owner != null) { Captions.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price); } diff --git a/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java b/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java index 2579976a4..c9fe94e41 100644 --- a/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java +++ b/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java @@ -94,7 +94,7 @@ public class PlotListener { ++value.count; if (value.count == value.interval) { value.count = 0; - PlotPlayer player = PlotPlayer.wrap(entry.getKey()); + final PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(entry.getKey()); if (player == null) { iterator.remove(); continue; @@ -114,7 +114,7 @@ public class PlotListener { ++value.count; if (value.count == value.interval) { value.count = 0; - PlotPlayer player = PlotSquared.platform().getWorldUtil().getPlayer(entry.getKey()); + final PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(entry.getKey()); if (player == null) { iterator.remove(); continue; diff --git a/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java b/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java index 4ae1c5c1f..7cfbd2751 100644 --- a/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java +++ b/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java @@ -26,6 +26,7 @@ package com.plotsquared.core.listener; import com.google.inject.Inject; +import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.player.PlotPlayer; @@ -72,7 +73,7 @@ public class WESubscriber { Actor actor = event.getActor(); if (actor != null && actor.isPlayer()) { String name = actor.getName(); - PlotPlayer plotPlayer = PlotPlayer.wrap(name); + final PlotPlayer plotPlayer = PlotSquared.platform().getPlayerManager().getPlayerIfExists(name); Set mask; if (plotPlayer == null) { Player player = (Player) actor; diff --git a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java index 437e86491..60fbf7415 100644 --- a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java @@ -120,7 +120,7 @@ public class ConsolePlayer extends PlotPlayer { } @Override public long getLastPlayed() { - return 0; + return System.currentTimeMillis(); } @Override public void sendMessage(String message) { @@ -132,10 +132,6 @@ public class ConsolePlayer extends PlotPlayer { setMeta(META_LOCATION, location); } - @Override public boolean isOnline() { - return true; - } - @Override public String getName() { return "*"; } diff --git a/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java index 92a0e6536..24d83514a 100644 --- a/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/OfflinePlotPlayer.java @@ -27,6 +27,7 @@ package com.plotsquared.core.player; import com.plotsquared.core.permissions.PermissionHolder; +import javax.annotation.Nonnegative; import java.util.UUID; public interface OfflinePlotPlayer extends PermissionHolder { @@ -42,16 +43,8 @@ public interface OfflinePlotPlayer extends PermissionHolder { * Gets the time in milliseconds when the player was last seen online. * * @return the time in milliseconds when last online - * @deprecated This method may be inconsistent across platforms. The javadoc may be wrong depending on which platform is used. */ - @SuppressWarnings("DeprecatedIsStillUsed") @Deprecated long getLastPlayed(); - - /** - * Checks if this player is online. - * - * @return {@code true} if this player is online - */ - boolean isOnline(); + @Nonnegative long getLastPlayed(); /** * Gets the name of this player. diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index 666d5be7b..27680b26a 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -140,20 +140,6 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return players; } - /** - * Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's already cached)
- * - Accepts sponge/bukkit Player (online) - * - Accepts player name (online) - * - Accepts UUID - * - Accepts bukkit OfflinePlayer (offline) - * - * @param player Player object to wrap - * @return Wrapped player - */ - public static PlotPlayer wrap(Object player) { - return PlotSquared.platform().wrapPlayer(player); - } - @Override public final boolean hasPermission(@Nullable final String world, @Nonnull final String permission) { return this.permissionProfile.hasPermission(world, permission); diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index 918388008..d4fe6ba6b 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -1926,11 +1926,16 @@ public class Plot { DBFunc.createPlotAndSettings(this, () -> { PlotArea plotworld = Plot.this.area; if (notify && plotworld.isAutoMerge()) { - PlotPlayer player = this.worldUtil.getPlayer(uuid); + final PlotPlayer player = PlotSquared.platform().getPlayerManager() + .getPlayerIfExists(uuid); + PlotMergeEvent event = this.eventDispatcher .callMerge(this, Direction.ALL, Integer.MAX_VALUE, player); + if (event.getEventResult() == Result.DENY) { - sendMessage(player, Captions.EVENT_DENIED, "Auto merge on claim"); + if (player != null) { + sendMessage(player, Captions.EVENT_DENIED, "Auto merge on claim"); + } return; } Plot.this.autoMerge(event.getDir(), event.getMax(), uuid, true); @@ -3083,10 +3088,10 @@ public class Plot { if (!TaskManager.removeFromTeleportQueue(name)) { return; } - if (player.isOnline()) { + try { MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT); player.teleport(location, cause); - } + } catch (final Exception ignored) {} }, TaskTime.seconds(Settings.Teleport.DELAY)); resultConsumer.accept(true); }; diff --git a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java index 2a3514540..1171bef87 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java @@ -418,13 +418,13 @@ public class ExpireManager { } } for (UUID helper : plot.getTrusted()) { - PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(helper); + PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(helper); if (player != null) { MainUtil.sendMessage(player, Captions.PLOT_REMOVED_USER, plot.toString()); } } for (UUID helper : plot.getMembers()) { - PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(helper); + PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(helper); if (player != null) { MainUtil.sendMessage(player, Captions.PLOT_REMOVED_USER, plot.toString()); } diff --git a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java index 81d5e2f11..e478bfdb8 100644 --- a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java @@ -328,14 +328,6 @@ public abstract class WorldUtil { */ public abstract boolean isBlockSame(@Nonnull BlockState block1, @Nonnull BlockState block2); - /** - * Get a player object for the player with the given UUID - * - * @param uuid Player UUID - * @return Player object - */ - @Nonnull public abstract PlotPlayer getPlayer(@Nonnull UUID uuid); - /** * Get the player health * From a7de76d15001ccee5828cc76d29c0595e5dc0d32 Mon Sep 17 00:00:00 2001 From: N0tMyFaultOG Date: Thu, 23 Jul 2020 14:03:56 +0200 Subject: [PATCH 13/25] Fix dependencies --- Bukkit/build.gradle | 2 ++ Bukkit/pom.xml | 2 +- Core/build.gradle | 2 ++ Core/pom.xml | 12 ++++++++++++ 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index 8e32904c5..3bb9f863e 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -106,6 +106,8 @@ shadowJar { include(dependency("javax.annotation:javax-annotation-api")) include(dependency('org.apache.logging.log4j:log4j-slf4j-impl')) include(dependency('org.slf4j:slf4j-api')) + include(dependency('javax.inject:javax.inject:1')) + include(dependency('aopalliance:aopalliance:1.0')) } relocate('net.kyori.text', 'com.plotsquared.formatting.text') diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index d4848ae84..b9e6fbb23 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -51,7 +51,7 @@ io.papermc paperlib - 1.0.2 + 1.0.4 compile diff --git a/Core/build.gradle b/Core/build.gradle index 9743bc080..bd0fa55f0 100644 --- a/Core/build.gradle +++ b/Core/build.gradle @@ -20,6 +20,8 @@ dependencies { compile("com.google.inject:guice:4.2.3") compile("com.google.inject.extensions:guice-assistedinject:4.2.3") compile group: 'com.google.code.findbugs', name: 'annotations', version: '3.0.1' + compile group: 'javax.inject', name: 'javax.inject', version: '1' + compile group: 'aopalliance', name: 'aopalliance', version: '1.0' // logging implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.8.1") } diff --git a/Core/pom.xml b/Core/pom.xml index ac6a4ef60..05142d3a8 100644 --- a/Core/pom.xml +++ b/Core/pom.xml @@ -36,6 +36,18 @@ 3.0.1 compile + + javax.inject + javax.inject + 1 + compile + + + aopalliance + aopalliance + 1.0 + compile + org.projectlombok lombok From d8e80daa9349ca3ff11130e8f4c586f0f43816a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 15:40:43 +0200 Subject: [PATCH 14/25] Fix annoying guice injection issue --- .../main/java/com/plotsquared/bukkit/BukkitPlatform.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index 3c39850e7..7af971ea7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -124,7 +124,6 @@ import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; -import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Entity; @@ -1118,8 +1117,9 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; return getInjector().getInstance(Key.get(new TypeLiteral>() {})); } - @Override @Nonnull public PlayerManager, ? extends Player> getPlayerManager() { - return getInjector().getInstance(Key.get(new TypeLiteral>() {})); + @Override @Nonnull @SuppressWarnings("ALL") + public PlayerManager, ? extends Player> getPlayerManager() { + return (PlayerManager) getInjector().getInstance(PlayerManager.class); } } From a1da452c415963222e3cca7904c7d079220171e1 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Thu, 23 Jul 2020 18:09:37 +0100 Subject: [PATCH 15/25] Fix build properly --- .../core/queue/BasicLocalBlockQueue.java | 6 ++--- .../com/plotsquared/core/util/ChunkUtil.java | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicLocalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/BasicLocalBlockQueue.java index 03aa8b437..487cfaf7a 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicLocalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicLocalBlockQueue.java @@ -25,7 +25,7 @@ */ package com.plotsquared.core.queue; -import com.plotsquared.core.util.MainUtil; +import com.plotsquared.core.util.ChunkUtil; import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.PatternUtil; import com.plotsquared.core.util.task.TaskManager; @@ -262,8 +262,8 @@ public abstract class BasicLocalBlockQueue extends LocalBlockQueue { } private void setInternal(final int x, final int y, final int z, final BaseBlock baseBlock) { - final int i = MainUtil.CACHE_I[y][x][z]; - final int j = MainUtil.CACHE_J[y][x][z]; + final int i = y >> 4; + final int j = ChunkUtil.getJ(x, y, z); BaseBlock[] array = baseblocks[i]; if (array == null) { array = (baseblocks[i] = new BaseBlock[4096]); diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java index 3e89c630a..6c1a1415d 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package com.plotsquared.core.util; import lombok.experimental.UtilityClass; From 2575787bd08c683186ae92426d431440e0ef3991 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 18:30:50 +0200 Subject: [PATCH 16/25] Add LockRepository --- .../core/synchronization/LockKey.java | 92 ++++++++++++++ .../core/synchronization/LockRepository.java | 116 ++++++++++++++++++ 2 files changed, 208 insertions(+) create mode 100644 Core/src/main/java/com/plotsquared/core/synchronization/LockKey.java create mode 100644 Core/src/main/java/com/plotsquared/core/synchronization/LockRepository.java diff --git a/Core/src/main/java/com/plotsquared/core/synchronization/LockKey.java b/Core/src/main/java/com/plotsquared/core/synchronization/LockKey.java new file mode 100644 index 000000000..0062d4da6 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/synchronization/LockKey.java @@ -0,0 +1,92 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.synchronization; + +import com.google.common.base.Objects; +import com.google.common.base.Preconditions; + +import javax.annotation.Nonnull; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Key used to access {@link java.util.concurrent.locks.Lock locks} + * from a {@link LockRepository} + */ +public final class LockKey { + + private static final Map keyMap = new HashMap<>(); + private static final Object keyLock = new Object(); + + private final String key; + + private LockKey(@Nonnull final String key) { + this.key = Preconditions.checkNotNull(key, "Key may not be null"); + } + + /** + * Get a new named lock key + * + * @param key Key name + * @return Lock key instance + */ + @Nonnull public static LockKey of(@Nonnull final String key) { + synchronized (keyLock) { + return keyMap.computeIfAbsent(key, LockKey::new); + } + } + + /** + * Get all currently recognized lock keys + * + * @return Currently recognized lock keys + */ + @Nonnull static Collection recognizedKeys() { + return Collections.unmodifiableCollection(keyMap.values()); + } + + @Override public String toString() { + return "LockKey{" + "key='" + key + '\'' + '}'; + } + + @Override public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final LockKey lockKey = (LockKey) o; + return Objects.equal(this.key, lockKey.key); + } + + @Override public int hashCode() { + return Objects.hashCode(this.key); + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/synchronization/LockRepository.java b/Core/src/main/java/com/plotsquared/core/synchronization/LockRepository.java new file mode 100644 index 000000000..373f3694c --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/synchronization/LockRepository.java @@ -0,0 +1,116 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.synchronization; + +import com.google.common.util.concurrent.Striped; + +import javax.annotation.Nonnull; +import java.util.concurrent.locks.Lock; +import java.util.function.Consumer; + +/** + * A repository for keyed {@link java.util.concurrent.locks.Lock locks} + */ +public final class LockRepository { + + private final Striped striped; + + public LockRepository() { + this.striped = Striped.lock(LockKey.recognizedKeys().size()); + } + + /** + * Get the lock corresponding to the given lock key + * + * @param key Lock key + * @return Lock + */ + @Nonnull public Lock getLock(@Nonnull final LockKey key) { + return this.striped.get(key); + } + + /** + * Consume a lock + * + * @param key Lock key + * @param consumer Lock consumer + */ + public void useLock(@Nonnull final LockKey key, @Nonnull final Consumer consumer) { + consumer.accept(this.getLock(key)); + } + + /** + * Wait for the lock to become available, and run + * the given runnable, then unlock the lock. This is + * a blocking method. + * + * @param key Lock key + * @param runnable Action to run when the lock is available + */ + public void useLock(@Nonnull final LockKey key, @Nonnull final Runnable runnable) { + this.useLock(key, lock -> { + lock.lock(); + runnable.run(); + lock.unlock(); + }); + } + + /** + * Wait for a lock to be available, lock it and return + * an {@link AutoCloseable} instance that locks the key. + *

+ * This is meant to be used with try-with-resources, like such: + *

{@code
+     * try (final LockAccess lockAccess = lockRepository.lock(LockKey.of("your.key"))) {
+     *      // use lock
+     * }
+     * }
+ * + * @param key Lock key + * @return Lock access. Must be closed. + */ + @Nonnull public LockAccess lock(@Nonnull final LockKey key) { + final Lock lock = this.getLock(key); + lock.lock(); + return new LockAccess(lock); + } + + + public static class LockAccess implements AutoCloseable { + + private final Lock lock; + + private LockAccess(@Nonnull final Lock lock) { + this.lock = lock; + } + + @Override public void close() { + this.lock.unlock(); + } + + } + +} From 555860cf838b6e0747fc879b33c7ba14d751c6d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 19:18:21 +0200 Subject: [PATCH 17/25] Add managed persistent meta data access --- .../com/plotsquared/core/command/Auto.java | 41 +++---- .../com/plotsquared/core/command/Claim.java | 86 +++++++------- .../com/plotsquared/core/command/Grant.java | 62 +++++----- .../core/listener/PlotListener.java | 31 ++--- .../core/player/MetaDataAccess.java | 101 +++++++++++++++++ .../plotsquared/core/player/MetaDataKey.java | 107 ++++++++++++++++++ .../core/player/PersistentMetaDataAccess.java | 57 ++++++++++ .../core/player/PlayerMetaDataKeys.java | 36 ++++++ .../plotsquared/core/player/PlotPlayer.java | 63 ++++++++++- 9 files changed, 474 insertions(+), 110 deletions(-) create mode 100644 Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java create mode 100644 Core/src/main/java/com/plotsquared/core/player/MetaDataKey.java create mode 100644 Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java create mode 100644 Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java diff --git a/Core/src/main/java/com/plotsquared/core/command/Auto.java b/Core/src/main/java/com/plotsquared/core/command/Auto.java index ea6a6cf6c..46be2c3e5 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Auto.java +++ b/Core/src/main/java/com/plotsquared/core/command/Auto.java @@ -26,7 +26,6 @@ package com.plotsquared.core.command; import com.google.common.collect.Lists; -import com.google.common.primitives.Ints; import com.google.inject.Inject; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.CaptionUtility; @@ -37,6 +36,8 @@ import com.plotsquared.core.events.PlayerAutoPlotEvent; import com.plotsquared.core.events.PlotAutoMergeEvent; import com.plotsquared.core.events.Result; import com.plotsquared.core.events.TeleportCause; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -91,27 +92,29 @@ public class Auto extends SubCommand { } int diff = allowedPlots - currentPlots; if (diff - sizeX * sizeZ < 0) { - if (player.hasPersistentMeta("grantedPlots")) { - int grantedPlots = Ints.fromByteArray(player.getPersistentMeta("grantedPlots")); - if (diff < 0 && grantedPlots < sizeX * sizeZ) { - MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); - return false; - } else if (diff >= 0 && grantedPlots + diff < sizeX * sizeZ) { - MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); - return false; - } else { - int left = grantedPlots + diff < 0 ? 0 : diff - sizeX * sizeZ; - if (left == 0) { - player.removePersistentMeta("grantedPlots"); + try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData( + PlayerMetaDataKeys.GRANTED_PLOTS)) { + if (metaDataAccess.has()) { + int grantedPlots = metaDataAccess.get().orElse(0); + if (diff < 0 && grantedPlots < sizeX * sizeZ) { + MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); + return false; + } else if (diff >= 0 && grantedPlots + diff < sizeX * sizeZ) { + MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); + return false; } else { - player.setPersistentMeta("grantedPlots", Ints.toByteArray(left)); + int left = grantedPlots + diff < 0 ? 0 : diff - sizeX * sizeZ; + if (left == 0) { + metaDataAccess.remove(); + } else { + metaDataAccess.set(left); + } + MainUtil.sendMessage(player, Captions.REMOVED_GRANTED_PLOT, "" + (grantedPlots - left), "" + left); } - MainUtil.sendMessage(player, Captions.REMOVED_GRANTED_PLOT, - "" + (grantedPlots - left), "" + left); + } else { + MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); + return false; } - } else { - MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); - return false; } } return true; diff --git a/Core/src/main/java/com/plotsquared/core/command/Claim.java b/Core/src/main/java/com/plotsquared/core/command/Claim.java index bb3ae02c3..c9bfb4c8f 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Claim.java +++ b/Core/src/main/java/com/plotsquared/core/command/Claim.java @@ -25,7 +25,6 @@ */ package com.plotsquared.core.command; -import com.google.common.primitives.Ints; import com.google.inject.Inject; import com.plotsquared.core.configuration.CaptionUtility; import com.plotsquared.core.configuration.Captions; @@ -36,6 +35,8 @@ import com.plotsquared.core.events.PlotMergeEvent; import com.plotsquared.core.events.Result; import com.plotsquared.core.location.Direction; import com.plotsquared.core.location.Location; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -85,54 +86,57 @@ public class Claim extends SubCommand { int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(location.getWorldName()); - int grants = 0; - if (currentPlots >= player.getAllowedPlots() && !force) { - if (player.hasPersistentMeta("grantedPlots")) { - grants = Ints.fromByteArray(player.getPersistentMeta("grantedPlots")); - if (grants <= 0) { - player.removePersistentMeta("grantedPlots"); + + final PlotArea area = plot.getArea(); + + try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData(PlayerMetaDataKeys.GRANTED_PLOTS)) { + int grants = 0; + if (currentPlots >= player.getAllowedPlots() && !force) { + if (metaDataAccess.has()) { + grants = metaDataAccess.get().orElse(0); + if (grants <= 0) { + metaDataAccess.remove(); + return sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); + } + } else { return sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); } - } else { - return sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); } - } - if (!plot.canClaim(player)) { - return sendMessage(player, Captions.PLOT_IS_CLAIMED); - } - final PlotArea area = plot.getArea(); - if (schematic != null && !schematic.isEmpty()) { - if (area.isSchematicClaimSpecify()) { - if (!area.hasSchematic(schematic)) { - return sendMessage(player, Captions.SCHEMATIC_INVALID, - "non-existent: " + schematic); - } - if (!Permissions.hasPermission(player, CaptionUtility - .format(player, Captions.PERMISSION_CLAIM_SCHEMATIC.getTranslated(), schematic)) - && !Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC) && !force) { - return sendMessage(player, Captions.NO_SCHEMATIC_PERMISSION, schematic); + + if (!plot.canClaim(player)) { + return sendMessage(player, Captions.PLOT_IS_CLAIMED); + } + if (schematic != null && !schematic.isEmpty()) { + if (area.isSchematicClaimSpecify()) { + if (!area.hasSchematic(schematic)) { + return sendMessage(player, Captions.SCHEMATIC_INVALID, "non-existent: " + schematic); + } + if (!Permissions.hasPermission(player, CaptionUtility.format(player, Captions.PERMISSION_CLAIM_SCHEMATIC.getTranslated(), + schematic)) && !Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC) + && !force) { + return sendMessage(player, Captions.NO_SCHEMATIC_PERMISSION, schematic); + } } } - } - if ((this.econHandler != null) && area.useEconomy() && !force) { - Expression costExr = area.getPrices().get("claim"); - double cost = costExr.evaluate((double) currentPlots); - if (cost > 0d) { - if (this.econHandler.getMoney(player) < cost) { - return sendMessage(player, Captions.CANNOT_AFFORD_PLOT, "" + cost); + if ((this.econHandler != null) && area.useEconomy() && !force) { + Expression costExr = area.getPrices().get("claim"); + double cost = costExr.evaluate((double) currentPlots); + if (cost > 0d) { + if (this.econHandler.getMoney(player) < cost) { + return sendMessage(player, Captions.CANNOT_AFFORD_PLOT, "" + cost); + } + this.econHandler.withdrawMoney(player, cost); + sendMessage(player, Captions.REMOVED_BALANCE, cost + ""); } - this.econHandler.withdrawMoney(player, cost); - sendMessage(player, Captions.REMOVED_BALANCE, cost + ""); } - } - if (grants > 0) { - if (grants == 1) { - player.removePersistentMeta("grantedPlots"); - } else { - player.setPersistentMeta("grantedPlots", Ints.toByteArray(grants - 1)); + if (grants > 0) { + if (grants == 1) { + metaDataAccess.remove(); + } else { + metaDataAccess.set(grants - 1); + } + sendMessage(player, Captions.REMOVED_GRANTED_PLOT, "1", (grants - 1)); } - sendMessage(player, Captions.REMOVED_GRANTED_PLOT, "1", (grants - 1)); } int border = area.getBorder(); if (border != Integer.MAX_VALUE && plot.getDistanceFromOrigin() > border && !force) { diff --git a/Core/src/main/java/com/plotsquared/core/command/Grant.java b/Core/src/main/java/com/plotsquared/core/command/Grant.java index ab1ef00d4..429e97168 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Grant.java +++ b/Core/src/main/java/com/plotsquared/core/command/Grant.java @@ -30,6 +30,8 @@ import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.CaptionUtility; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.database.DBFunc; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.Permissions; @@ -42,7 +44,6 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeoutException; -import java.util.function.Consumer; @CommandDeclaration(command = "grant", category = CommandCategory.CLAIMING, @@ -80,41 +81,40 @@ public class Grant extends Command { MainUtil.sendMessage(player, Captions.INVALID_PLAYER); } else { final UUID uuid = uuids.toArray(new UUID[0])[0]; - final Consumer result = array -> { - if (arg0.equals("check")) { // check - int granted; - if (array == null) { - granted = 0; - } else { - granted = Ints.fromByteArray(array); - } - Captions.GRANTED_PLOTS.send(player, granted); - } else { // add - int amount; - if (array == null) { - amount = 1; - } else { - amount = 1 + Ints.fromByteArray(array); - } - boolean replace = array != null; - String key = "grantedPlots"; - byte[] rawData = Ints.toByteArray(amount); - - PlotPlayer online = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); - if (online != null) { - online.setPersistentMeta(key, rawData); - } else { - DBFunc.addPersistentMeta(uuid, key, rawData, replace); - } - } - }; PlotPlayer pp = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); if (pp != null) { - result.accept(player.getPersistentMeta("grantedPlots")); + try (final MetaDataAccess access = player.accessPersistentMetaData( + PlayerMetaDataKeys.GRANTED_PLOTS)) { + if (args[0].equalsIgnoreCase("check")) { + Captions.GRANTED_PLOTS.send(player, access.get().orElse(0)); + } else { + access.set(access.get().orElse(0) + 1); + } + } } else { DBFunc.getPersistentMeta(uuid, new RunnableVal>() { @Override public void run(Map value) { - result.accept(value.get("grantedPlots")); + final byte[] array = value.get("grantedPlots"); + if (arg0.equals("check")) { // check + int granted; + if (array == null) { + granted = 0; + } else { + granted = Ints.fromByteArray(array); + } + Captions.GRANTED_PLOTS.send(player, granted); + } else { // add + int amount; + if (array == null) { + amount = 1; + } else { + amount = 1 + Ints.fromByteArray(array); + } + boolean replace = array != null; + String key = "grantedPlots"; + byte[] rawData = Ints.toByteArray(amount); + DBFunc.addPersistentMeta(uuid, key, rawData, replace); + } } }); } diff --git a/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java b/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java index 2579976a4..9fcaad2de 100644 --- a/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java +++ b/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java @@ -26,12 +26,13 @@ package com.plotsquared.core.listener; import com.plotsquared.core.PlotSquared; -import com.plotsquared.core.collection.ByteArrayUtilities; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.events.PlotFlagRemoveEvent; import com.plotsquared.core.events.Result; import com.plotsquared.core.location.Location; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -71,6 +72,7 @@ import javax.annotation.Nullable; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.Optional; import java.util.UUID; public class PlotListener { @@ -177,8 +179,9 @@ public class PlotListener { boolean flight = player.getFlight(); GameMode gamemode = player.getGameMode(); if (flight != (gamemode == GameModes.CREATIVE || gamemode == GameModes.SPECTATOR)) { - player.setPersistentMeta("flight", - ByteArrayUtilities.booleanToBytes(player.getFlight())); + try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData(PlayerMetaDataKeys.PERSISTENT_FLIGHT)) { + metaDataAccess.set(player.getFlight()); + } } player.setFlight(flyStatus == FlyFlag.FlyStatus.ENABLED); } @@ -346,16 +349,18 @@ public class PlotListener { final FlyFlag.FlyStatus flyStatus = plot.getFlag(FlyFlag.class); if (flyStatus != FlyFlag.FlyStatus.DEFAULT) { - if (player.hasPersistentMeta("flight")) { - player.setFlight( - ByteArrayUtilities.bytesToBoolean(player.getPersistentMeta("flight"))); - player.removePersistentMeta("flight"); - } else { - GameMode gameMode = player.getGameMode(); - if (gameMode == GameModes.SURVIVAL || gameMode == GameModes.ADVENTURE) { - player.setFlight(false); - } else if (!player.getFlight()) { - player.setFlight(true); + try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData(PlayerMetaDataKeys.PERSISTENT_FLIGHT)) { + final Optional value = metaDataAccess.get(); + if (value.isPresent()) { + player.setFlight(value.get()); + metaDataAccess.remove(); + } else { + GameMode gameMode = player.getGameMode(); + if (gameMode == GameModes.SURVIVAL || gameMode == GameModes.ADVENTURE) { + player.setFlight(false); + } else if (!player.getFlight()) { + player.setFlight(true); + } } } } diff --git a/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java b/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java new file mode 100644 index 000000000..b4f494edf --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java @@ -0,0 +1,101 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.player; + +import com.plotsquared.core.synchronization.LockRepository; + +import javax.annotation.Nonnull; +import java.util.Optional; + +/** + * Access to player meta data + * + * @param

Player type + * @param Meta data type + */ +public abstract class MetaDataAccess implements AutoCloseable { + + private final PlotPlayer player; + private final MetaDataKey metaDataKey; + private final LockRepository.LockAccess lockAccess; + + MetaDataAccess(@Nonnull final PlotPlayer player, @Nonnull final MetaDataKey metaDataKey, + @Nonnull final LockRepository.LockAccess lockAccess) { + this.player = player; + this.metaDataKey = metaDataKey; + this.lockAccess = lockAccess; + } + + /** + * Check if the player has meta data stored with the given key + * + * @return {@code true} if player has meta data with this key, or + * {@code false} + */ + public abstract boolean has(); + + /** + * Remove the stored value meta data + */ + public abstract void remove(); + + /** + * Set the meta data value + * + * @param value New value + */ + public abstract void set(@Nonnull final T value); + + /** + * Get the stored meta data value + * + * @return Stored value, or {@link Optional#empty()} + */ + @Nonnull public abstract Optional get(); + + @Override public final void close() { + this.lockAccess.close(); + } + + /** + * Get the owner of the meta data + * + * @return Player + */ + @Nonnull public PlotPlayer getPlayer() { + return this.player; + } + + /** + * Get the meta data key + * + * @return Meta data key + */ + @Nonnull public MetaDataKey getMetaDataKey() { + return this.metaDataKey; + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/player/MetaDataKey.java b/Core/src/main/java/com/plotsquared/core/player/MetaDataKey.java new file mode 100644 index 000000000..4b51ca12a --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/player/MetaDataKey.java @@ -0,0 +1,107 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.player; + +import com.google.common.base.Objects; +import com.google.common.base.Preconditions; +import com.plotsquared.core.synchronization.LockKey; + +import javax.annotation.Nonnull; +import java.util.HashMap; +import java.util.Map; + +/** + * Key used to access meta data + * + * @param Meta data type + */ +public final class MetaDataKey { + + private static final Map keyMap = new HashMap<>(); + private static final Object keyMetaData = new Object(); + + private final String key; + private final Class type; + private final LockKey lockKey; + + private MetaDataKey(@Nonnull final String key, @Nonnull final Class type) { + this.key = Preconditions.checkNotNull(key, "Key may not be null"); + this.type = Preconditions.checkNotNull(type, "Type may not be null"); + this.lockKey = LockKey.of(this.key); + } + + /** + * Get a new named lock key + * + * @param key Key name + * @param Type + * @return MetaData key instance + */ + @Nonnull public static MetaDataKey of(@Nonnull final String key, @Nonnull final Class type) { + synchronized (keyMetaData) { + return (MetaDataKey) + keyMap.computeIfAbsent(key, missingKey -> new MetaDataKey<>(missingKey, type)); + } + } + + @Override public String toString() { + return this.key; + } + + @Override public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final MetaDataKey lockKey = (MetaDataKey) o; + return Objects.equal(this.key, lockKey.key); + } + + @Override public int hashCode() { + return Objects.hashCode(this.key); + } + + /** + * Get the {@link LockKey} associated with this key + * + * @return Lock key + */ + @Nonnull public LockKey getLockKey() { + return this.lockKey; + } + + /** + * Get the meta data type + * + * @return Meta data type + */ + @Nonnull public Class getType() { + return this.type; + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java b/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java new file mode 100644 index 000000000..c0380b233 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java @@ -0,0 +1,57 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.player; + +import com.plotsquared.core.synchronization.LockRepository; + +import javax.annotation.Nonnull; +import java.util.Optional; + +public final class PersistentMetaDataAccess extends MetaDataAccess { + + PersistentMetaDataAccess(@Nonnull final PlotPlayer player, + @Nonnull final MetaDataKey metaDataKey, + @Nonnull final LockRepository.LockAccess lockAccess) { + super(player, metaDataKey, lockAccess); + } + + @Override public boolean has() { + return this.getPlayer().hasPersistentMeta(getMetaDataKey().toString()); + } + + @Override public void remove() { + this.getPlayer().removePersistentMeta(this.getMetaDataKey().toString()); + } + + @Override public void set(@Nonnull T value) { + this.getPlayer().setPersistentMeta(this.getMetaDataKey(), value); + } + + @Nonnull @Override public Optional get() { + return Optional.ofNullable(this.getPlayer().getPersistentMeta(this.getMetaDataKey())); + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java b/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java new file mode 100644 index 000000000..5140c4b5c --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java @@ -0,0 +1,36 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.player; + +public final class PlayerMetaDataKeys { + + public static final MetaDataKey PERSISTENT_FLIGHT = MetaDataKey.of("flight", Boolean.class); + public static final MetaDataKey GRANTED_PLOTS = MetaDataKey.of("grantedPlots", Integer.class); + + private PlayerMetaDataKeys() { + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index 6d2428d05..61a41a672 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -26,7 +26,9 @@ package com.plotsquared.core.player; import com.google.common.base.Preconditions; +import com.google.common.primitives.Ints; import com.plotsquared.core.PlotSquared; +import com.plotsquared.core.collection.ByteArrayUtilities; import com.plotsquared.core.command.CommandCaller; import com.plotsquared.core.command.RequiredType; import com.plotsquared.core.configuration.CaptionUtility; @@ -45,6 +47,7 @@ import com.plotsquared.core.plot.flag.implementations.DoneFlag; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.SinglePlotArea; import com.plotsquared.core.plot.world.SinglePlotAreaManager; +import com.plotsquared.core.synchronization.LockRepository; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.Permissions; @@ -54,11 +57,11 @@ import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.item.ItemType; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Collections; @@ -92,6 +95,8 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer private ConcurrentHashMap meta; private int hash; + private final LockRepository lockRepository = new LockRepository(); + private final PlotAreaManager plotAreaManager; private final EventDispatcher eventDispatcher; private final EconHandler econHandler; @@ -721,18 +726,64 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer } } - public byte[] getPersistentMeta(String key) { + byte[] getPersistentMeta(String key) { return this.metaMap.get(key); } - public void removePersistentMeta(String key) { + void removePersistentMeta(String key) { this.metaMap.remove(key); if (Settings.Enabled_Components.PERSISTENT_META) { DBFunc.removePersistentMeta(getUUID(), key); } } - public void setPersistentMeta(String key, byte[] value) { + /** + * Access keyed persistent meta data for this player. This returns a meta data + * access instance, that MUST be closed. It is meant to be used with try-with-resources, + * like such: + *

{@code
+     * try (final MetaDataAccess access = player.accessPersistentMetaData(PlayerMetaKeys.GRANTS)) {
+     *     int grants = access.get();
+     *     access.set(grants + 1);
+     * }
+     * }
+ * + * @param key Meta data key + * @param Meta data type + * @return Meta data access. MUST be closed after being used + */ + @Nonnull public MetaDataAccess accessPersistentMetaData(@Nonnull final MetaDataKey key) { + return new PersistentMetaDataAccess<>(this, key, this.lockRepository.lock(key.getLockKey())); + } + + void setPersistentMeta(@Nonnull final MetaDataKey key, + @Nonnull final T value) { + if (key.getType().equals(Integer.class)) { + this.setPersistentMeta(key.toString(), Ints.toByteArray((int) value)); + } else if (key.getType().equals(Boolean.class)) { + this.setPersistentMeta(key.toString(), ByteArrayUtilities.booleanToBytes((boolean) value)); + } else { + throw new IllegalArgumentException(String.format("Unknown meta data type '%s'", key.getType().getSimpleName())); + } + } + + @Nullable T getPersistentMeta(@Nonnull final MetaDataKey key) { + final byte[] value = this.getPersistentMeta(key.toString()); + if (value == null) { + return null; + } + final Object returnValue; + if (key.getType().equals(Integer.class)) { + returnValue = Ints.fromByteArray(value); + } else if (key.getType().equals(Boolean.class)) { + returnValue = ByteArrayUtilities.bytesToBoolean(value); + } else { + throw new IllegalArgumentException(String.format("Unknown meta data type '%s'", key.getType().getSimpleName())); + } + return (T) returnValue; + } + + void setPersistentMeta(String key, byte[] value) { boolean delete = hasPersistentMeta(key); this.metaMap.put(key, value); if (Settings.Enabled_Components.PERSISTENT_META) { @@ -740,7 +791,7 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer } } - public boolean hasPersistentMeta(String key) { + boolean hasPersistentMeta(String key) { return this.metaMap.containsKey(key); } From 05ce67fbfebbfca7530905035c53b56b07164158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 19:19:48 +0200 Subject: [PATCH 18/25] Trick the compiler --- .../main/java/com/plotsquared/core/player/PlotPlayer.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index 61a41a672..434d4477e 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -758,10 +758,11 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer void setPersistentMeta(@Nonnull final MetaDataKey key, @Nonnull final T value) { + final Object rawValue = value; if (key.getType().equals(Integer.class)) { - this.setPersistentMeta(key.toString(), Ints.toByteArray((int) value)); + this.setPersistentMeta(key.toString(), Ints.toByteArray((int) rawValue)); } else if (key.getType().equals(Boolean.class)) { - this.setPersistentMeta(key.toString(), ByteArrayUtilities.booleanToBytes((boolean) value)); + this.setPersistentMeta(key.toString(), ByteArrayUtilities.booleanToBytes((boolean) rawValue)); } else { throw new IllegalArgumentException(String.format("Unknown meta data type '%s'", key.getType().getSimpleName())); } From ad40ab7e1edb1d1dcac7ac50cd4bee6cfcc336a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 19:26:29 +0200 Subject: [PATCH 19/25] Grant plots to the correct player --- Core/src/main/java/com/plotsquared/core/command/Grant.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Core/src/main/java/com/plotsquared/core/command/Grant.java b/Core/src/main/java/com/plotsquared/core/command/Grant.java index 429e97168..ad9d09b42 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Grant.java +++ b/Core/src/main/java/com/plotsquared/core/command/Grant.java @@ -83,7 +83,7 @@ public class Grant extends Command { final UUID uuid = uuids.toArray(new UUID[0])[0]; PlotPlayer pp = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); if (pp != null) { - try (final MetaDataAccess access = player.accessPersistentMetaData( + try (final MetaDataAccess access = pp.accessPersistentMetaData( PlayerMetaDataKeys.GRANTED_PLOTS)) { if (args[0].equalsIgnoreCase("check")) { Captions.GRANTED_PLOTS.send(player, access.get().orElse(0)); From 6a63e5bb51285cae5a6b7dc7f136f161ffac1bde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 19:30:52 +0200 Subject: [PATCH 20/25] Expose the player's lock repository --- .../java/com/plotsquared/core/player/PlotPlayer.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index 434d4477e..8907a2069 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -836,6 +836,15 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer } } + /** + * Get this player's {@link LockRepository} + * + * @return Lock repository instance + */ + @Nonnull public LockRepository getLockRepository() { + return this.lockRepository; + } + @FunctionalInterface public interface PlotPlayerConverter { PlotPlayer convert(BaseObject object); From d2f40612f41a55acfa74528713ff087d9fc4c12a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Thu, 23 Jul 2020 20:52:32 +0200 Subject: [PATCH 21/25] Switch from Class to TypeLiteral, and implement managed meta access for temporary meta --- .../bukkit/listener/PlayerEvents.java | 157 ++++++++----- .../bukkit/player/BukkitPlayer.java | 14 +- .../com/plotsquared/core/command/Area.java | 24 +- .../com/plotsquared/core/command/Auto.java | 16 +- .../com/plotsquared/core/command/Claim.java | 2 +- .../plotsquared/core/command/CmdConfirm.java | 21 +- .../plotsquared/core/command/DebugExec.java | 40 ---- .../com/plotsquared/core/command/Grant.java | 2 +- .../com/plotsquared/core/command/Inbox.java | 8 +- .../com/plotsquared/core/command/Load.java | 166 +++++++------- .../plotsquared/core/command/MainCommand.java | 46 ++-- .../com/plotsquared/core/command/Save.java | 8 +- .../com/plotsquared/core/command/Setup.java | 66 +++--- .../core/listener/PlotListener.java | 216 ++++++++++-------- .../core/player/ConsolePlayer.java | 13 +- .../core/player/MetaDataAccess.java | 5 +- .../plotsquared/core/player/MetaDataKey.java | 9 +- .../core/player/PersistentMetaDataAccess.java | 11 +- .../core/player/PlayerMetaDataKeys.java | 30 ++- .../plotsquared/core/player/PlotPlayer.java | 57 +++-- .../core/player/TemporaryMetaDataAccess.java | 62 +++++ .../com/plotsquared/core/plot/PlotArea.java | 16 +- .../plotsquared/core/plot/PlotInventory.java | 22 +- .../core/plot/comment/CommentManager.java | 8 +- .../core/plot/expiration/ExpireManager.java | 74 +++--- .../core/setup/CommonSetupSteps.java | 7 +- .../plotsquared/core/util/Permissions.java | 27 ++- .../com/plotsquared/core/util/WEManager.java | 29 ++- .../core/util/task/AutoClaimFinishTask.java | 7 +- 29 files changed, 709 insertions(+), 454 deletions(-) create mode 100644 Core/src/main/java/com/plotsquared/core/player/TemporaryMetaDataAccess.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java index f334e055b..e07a1ce28 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java @@ -38,6 +38,8 @@ import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.listener.PlayerBlockEventType; import com.plotsquared.core.listener.PlotListener; import com.plotsquared.core.location.Location; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -216,13 +218,14 @@ import org.bukkit.plugin.Plugin; import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.projectiles.ProjectileSource; import org.bukkit.util.Vector; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; @@ -731,32 +734,36 @@ import java.util.regex.Pattern; public void onTeleport(PlayerTeleportEvent event) { Player player = event.getPlayer(); BukkitPlayer pp = BukkitUtil.adapt(player); - Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); - org.bukkit.Location to = event.getTo(); - //noinspection ConstantConditions - if (to != null) { - Location location = BukkitUtil.adapt(to); - PlotArea area = location.getPlotArea(); - if (area == null) { - if (lastPlot != null) { - plotExit(pp, lastPlot); - pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + try (final MetaDataAccess lastPlotAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + Plot lastPlot = lastPlotAccess.get().orElse(null); + org.bukkit.Location to = event.getTo(); + //noinspection ConstantConditions + if (to != null) { + Location location = BukkitUtil.adapt(to); + PlotArea area = location.getPlotArea(); + if (area == null) { + if (lastPlot != null) { + plotExit(pp, lastPlot); + lastPlotAccess.remove(); + } + try (final MetaDataAccess lastLocationAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + lastLocationAccess.remove(); + } + return; } - pp.deleteMeta(PlotPlayer.META_LOCATION); - return; - } - Plot plot = area.getPlot(location); - if (plot != null) { - final boolean result = DenyTeleportFlag.allowsTeleport(pp, plot); - // there is one possibility to still allow teleportation: - // to is identical to the plot's home location, and untrusted-visit is true - // i.e. untrusted-visit can override deny-teleport - // this is acceptable, because otherwise it wouldn't make sense to have both flags set - if (!result && !(plot.getFlag(UntrustedVisitFlag.class) && plot.getHomeSynchronous() - .equals(BukkitUtil.adaptComplete(to)))) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_ENTRY_DENIED); - event.setCancelled(true); + Plot plot = area.getPlot(location); + if (plot != null) { + final boolean result = DenyTeleportFlag.allowsTeleport(pp, plot); + // there is one possibility to still allow teleportation: + // to is identical to the plot's home location, and untrusted-visit is true + // i.e. untrusted-visit can override deny-teleport + // this is acceptable, because otherwise it wouldn't make sense to have both flags set + if (!result && !(plot.getFlag(UntrustedVisitFlag.class) && plot.getHomeSynchronous().equals(BukkitUtil.adaptComplete(to)))) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_ENTRY_DENIED); + event.setCancelled(true); + } } } } @@ -847,28 +854,39 @@ import java.util.regex.Pattern; } // Set last location Location location = BukkitUtil.adapt(to); - pp.setMeta(PlotPlayer.META_LOCATION, location); + try (final MetaDataAccess lastLocationAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + lastLocationAccess.remove(); + } PlotArea area = location.getPlotArea(); if (area == null) { - pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + try (final MetaDataAccess lastPlotAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + lastPlotAccess.remove(); + } return; } Plot now = area.getPlot(location); - Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); + Plot lastPlot; + try (final MetaDataAccess lastPlotAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + lastPlot = lastPlotAccess.get().orElse(null); + } if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp - .getMeta("kick", false)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_EXIT_DENIED); - this.tmpTeleport = false; - if (lastPlot.equals(BukkitUtil.adapt(from).getPlot())) { - player.teleport(from); - } else { - player.teleport(player.getWorld().getSpawnLocation()); + try (final MetaDataAccess kickAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_KICK)) { + if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !kickAccess.get().orElse(false)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_EXIT_DENIED); + this.tmpTeleport = false; + if (lastPlot.equals(BukkitUtil.adapt(from).getPlot())) { + player.teleport(from); + } else { + player.teleport(player.getWorld().getSpawnLocation()); + } + this.tmpTeleport = true; + event.setCancelled(true); + return; } - this.tmpTeleport = true; - event.setCancelled(true); - return; } } else if (now.equals(lastPlot)) { ForceFieldListener.handleForcefield(player, pp, now); @@ -909,28 +927,39 @@ import java.util.regex.Pattern; } // Set last location Location location = BukkitUtil.adapt(to); - pp.setMeta(PlotPlayer.META_LOCATION, location); + try (final MetaDataAccess lastLocationAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + lastLocationAccess.set(location); + } PlotArea area = location.getPlotArea(); if (area == null) { - pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + try (final MetaDataAccess lastPlotAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + lastPlotAccess.remove(); + } return; } Plot now = area.getPlot(location); - Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); + Plot lastPlot; + try (final MetaDataAccess lastPlotAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + lastPlot = lastPlotAccess.get().orElse(null); + } if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp - .getMeta("kick", false)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_EXIT_DENIED); - this.tmpTeleport = false; - if (lastPlot.equals(BukkitUtil.adapt(from).getPlot())) { - player.teleport(from); - } else { - player.teleport(player.getWorld().getSpawnLocation()); + try (final MetaDataAccess kickAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_KICK)) { + if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !kickAccess.get().orElse(false)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_EXIT_DENIED); + this.tmpTeleport = false; + if (lastPlot.equals(BukkitUtil.adapt(from).getPlot())) { + player.teleport(from); + } else { + player.teleport(player.getWorld().getSpawnLocation()); + } + this.tmpTeleport = true; + event.setCancelled(true); + return; } - this.tmpTeleport = true; - event.setCancelled(true); - return; } } else if (now.equals(lastPlot)) { ForceFieldListener.handleForcefield(player, pp, now); @@ -1155,8 +1184,15 @@ import java.util.regex.Pattern; Player player = event.getPlayer(); BukkitPlayer pp = BukkitUtil.adapt(player); // Delete last location - Plot plot = (Plot) pp.deleteMeta(PlotPlayer.META_LAST_PLOT); - pp.deleteMeta(PlotPlayer.META_LOCATION); + Plot plot; + try (final MetaDataAccess lastPlotAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + plot = lastPlotAccess.remove(); + } + try (final MetaDataAccess lastLocationAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + lastLocationAccess.remove(); + } if (plot != null) { plotExit(pp, plot); } @@ -1168,7 +1204,10 @@ import java.util.regex.Pattern; } } if (Settings.Enabled_Components.PERMISSION_CACHE) { - pp.deleteMeta("perm"); + try (final MetaDataAccess> metaDataAccess = + pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_PERMISSIONS)) { + metaDataAccess.remove(); + } } Location location = pp.getLocation(); PlotArea area = location.getPlotArea(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java index 15d9bacf8..b3db26369 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java @@ -69,12 +69,12 @@ import static com.sk89q.worldedit.world.gamemode.GameModes.SURVIVAL; public class BukkitPlayer extends PlotPlayer { private static boolean CHECK_EFFECTIVE = true; - - private final EconHandler econHandler; public final Player player; + private final EconHandler econHandler; private boolean offline; private String name; - + private String lastMessage = ""; + private long lastMessageTime = 0L; /** *

Please do not use this method. Instead use @@ -234,10 +234,10 @@ public class BukkitPlayer extends PlotPlayer { @Override public void sendMessage(String message) { message = message.replace('\u2010', '%').replace('\u2020', '&').replace('\u2030', '&'); - if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || ( - System.currentTimeMillis() - this.getMeta("lastMessageTime") > 5000)) { - setMeta("lastMessage", message); - setMeta("lastMessageTime", System.currentTimeMillis()); + if (!StringMan.isEqual(this.lastMessage, message) || ( + System.currentTimeMillis() - this.lastMessageTime > 5000)) { + this.lastMessage = message; + this.lastMessageTime = System.currentTimeMillis(); this.player.sendMessage(message); } } diff --git a/Core/src/main/java/com/plotsquared/core/command/Area.java b/Core/src/main/java/com/plotsquared/core/command/Area.java index aad920373..931a86be1 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Area.java +++ b/Core/src/main/java/com/plotsquared/core/command/Area.java @@ -27,8 +27,6 @@ package com.plotsquared.core.command; import com.google.inject.Inject; import com.plotsquared.core.PlotSquared; -import com.plotsquared.core.inject.annotations.WorldConfig; -import com.plotsquared.core.inject.annotations.WorldFile; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationUtil; @@ -36,6 +34,8 @@ import com.plotsquared.core.configuration.file.YamlConfiguration; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.generator.AugmentedUtils; import com.plotsquared.core.generator.HybridPlotWorld; +import com.plotsquared.core.inject.annotations.WorldConfig; +import com.plotsquared.core.inject.annotations.WorldFile; import com.plotsquared.core.inject.factory.HybridPlotWorldFactory; import com.plotsquared.core.location.Location; import com.plotsquared.core.player.ConsolePlayer; @@ -72,16 +72,19 @@ import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.UUID; @CommandDeclaration(command = "area", permission = "plots.area", @@ -101,6 +104,8 @@ public class Area extends SubCommand { private final WorldUtil worldUtil; private final RegionManager regionManager; + private final Map> metaData = new HashMap<>(); + @Inject public Area(@Nonnull final PlotAreaManager plotAreaManager, @WorldConfig @Nonnull final YamlConfiguration worldConfiguration, @WorldFile @Nonnull final File worldFile, @@ -264,14 +269,16 @@ public class Area extends SubCommand { case 2: switch (args[1].toLowerCase()) { case "pos1": { // Set position 1 - HybridPlotWorld area = player.getMeta("area_create_area"); + HybridPlotWorld area = (HybridPlotWorld) metaData.computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()) + .get("area_create_area"); if (area == null) { Captions.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); return false; } Location location = player.getLocation(); - player.setMeta("area_pos1", location); + metaData.computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()) + .put("area_pos1", location); Captions.SET_ATTRIBUTE.send(player, "area_pos1", location.getX() + "," + location.getZ()); MainUtil.sendMessage(player, @@ -280,14 +287,15 @@ public class Area extends SubCommand { return true; } case "pos2": // Set position 2 and finish creation for type=2 (partial) - final HybridPlotWorld area = player.getMeta("area_create_area"); + final HybridPlotWorld area = (HybridPlotWorld) metaData + .computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()).get("area_create_area"); if (area == null) { Captions.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); return false; } Location pos1 = player.getLocation(); - Location pos2 = player.getMeta("area_pos1"); + Location pos2 = (Location) metaData.computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()).get("area_pos1"); int dx = Math.abs(pos1.getX() - pos2.getX()); int dz = Math.abs(pos1.getZ() - pos2.getZ()); int numX = Math.max(1, @@ -500,7 +508,7 @@ public class Area extends SubCommand { player.teleport(this.worldUtil.getSpawn(pa.getWorldName()), TeleportCause.COMMAND); } - player.setMeta("area_create_area", pa); + metaData.computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()).put("area_create_area", pa); MainUtil.sendMessage(player, "$1Go to the first corner and use: $2 " + getCommandString() + " create pos1"); diff --git a/Core/src/main/java/com/plotsquared/core/command/Auto.java b/Core/src/main/java/com/plotsquared/core/command/Auto.java index 46be2c3e5..2cd105ffa 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Auto.java +++ b/Core/src/main/java/com/plotsquared/core/command/Auto.java @@ -93,7 +93,7 @@ public class Auto extends SubCommand { int diff = allowedPlots - currentPlots; if (diff - sizeX * sizeZ < 0) { try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData( - PlayerMetaDataKeys.GRANTED_PLOTS)) { + PlayerMetaDataKeys.PERSISTENT_GRANTED_PLOTS)) { if (metaDataAccess.has()) { int grantedPlots = metaDataAccess.get().orElse(0); if (diff < 0 && grantedPlots < sizeX * sizeZ) { @@ -149,7 +149,10 @@ public class Auto extends SubCommand { */ public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, final String schematic) { - player.setMeta(Auto.class.getName(), true); + try (final MetaDataAccess metaDataAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_AUTO)) { + metaDataAccess.set(true); + } autoClaimFromDatabase(player, area, start, new RunnableVal() { @Override public void run(final Plot plot) { try { @@ -253,9 +256,12 @@ public class Auto extends SubCommand { return false; } final int allowed_plots = player.getAllowedPlots(); - if (!force && (player.getMeta(Auto.class.getName(), false) || !checkAllowedPlots(player, - plotarea, allowed_plots, size_x, size_z))) { - return false; + try (final MetaDataAccess metaDataAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_AUTO)) { + if (!force && (metaDataAccess.get().orElse(false) || !checkAllowedPlots(player, + plotarea, allowed_plots, size_x, size_z))) { + return false; + } } if (schematic != null && !schematic.isEmpty()) { diff --git a/Core/src/main/java/com/plotsquared/core/command/Claim.java b/Core/src/main/java/com/plotsquared/core/command/Claim.java index c9bfb4c8f..fbbd25013 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Claim.java +++ b/Core/src/main/java/com/plotsquared/core/command/Claim.java @@ -89,7 +89,7 @@ public class Claim extends SubCommand { final PlotArea area = plot.getArea(); - try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData(PlayerMetaDataKeys.GRANTED_PLOTS)) { + try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData(PlayerMetaDataKeys.PERSISTENT_GRANTED_PLOTS)) { int grants = 0; if (currentPlots >= player.getAllowedPlots() && !force) { if (metaDataAccess.has()) { diff --git a/Core/src/main/java/com/plotsquared/core/command/CmdConfirm.java b/Core/src/main/java/com/plotsquared/core/command/CmdConfirm.java index c8aee497c..412cff610 100644 --- a/Core/src/main/java/com/plotsquared/core/command/CmdConfirm.java +++ b/Core/src/main/java/com/plotsquared/core/command/CmdConfirm.java @@ -26,19 +26,29 @@ package com.plotsquared.core.command; import com.plotsquared.core.configuration.Captions; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskTime; +import javax.annotation.Nullable; + public class CmdConfirm { - public static CmdInstance getPending(PlotPlayer player) { - return player.getMeta("cmdConfirm"); + @Nullable public static CmdInstance getPending(PlotPlayer player) { + try (final MetaDataAccess metaDataAccess = player.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_CONFIRM)) { + return metaDataAccess.get().orElse(null); + } } public static void removePending(PlotPlayer player) { - player.deleteMeta("cmdConfirm"); + try (final MetaDataAccess metaDataAccess = player.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_CONFIRM)) { + metaDataAccess.remove(); + } } public static void addPending(final PlotPlayer player, String commandStr, @@ -49,7 +59,10 @@ public class CmdConfirm { } TaskManager.runTaskLater(() -> { CmdInstance cmd = new CmdInstance(runnable); - player.setMeta("cmdConfirm", cmd); + try (final MetaDataAccess metaDataAccess = player.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_CONFIRM)) { + metaDataAccess.set(cmd); + } }, TaskTime.ticks(1L)); } } diff --git a/Core/src/main/java/com/plotsquared/core/command/DebugExec.java b/Core/src/main/java/com/plotsquared/core/command/DebugExec.java index 598baf510..bc39a8f3e 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DebugExec.java +++ b/Core/src/main/java/com/plotsquared/core/command/DebugExec.java @@ -409,46 +409,6 @@ public class DebugExec extends SubCommand { } }, "/plot debugexec list-scripts", "List of scripts"); return true; - case "allcmd": - if (args.length < 3) { - Captions.COMMAND_SYNTAX - .send(player, "/plot debugexec allcmd "); - return false; - } - long start = System.currentTimeMillis(); - Command cmd = MainCommand.getInstance().getCommand(args[3]); - String[] params = Arrays.copyOfRange(args, 4, args.length); - if ("true".equals(args[1])) { - Location location = player.getMeta(PlotPlayer.META_LOCATION); - Plot plot = player.getMeta(PlotPlayer.META_LAST_PLOT); - for (Plot current : PlotSquared.get().getBasePlots()) { - player.setMeta(PlotPlayer.META_LOCATION, current.getBottomAbs()); - player.setMeta(PlotPlayer.META_LAST_PLOT, current); - cmd.execute(player, params, null, null); - } - if (location == null) { - player.deleteMeta(PlotPlayer.META_LOCATION); - } else { - player.setMeta(PlotPlayer.META_LOCATION, location); - } - if (plot == null) { - player.deleteMeta(PlotPlayer.META_LAST_PLOT); - } else { - player.setMeta(PlotPlayer.META_LAST_PLOT, plot); - } - player.sendMessage("&c> " + (System.currentTimeMillis() - start)); - return true; - } - init(); - this.scope.put("_2", params); - this.scope.put("_3", cmd); - script = - "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" - + args[1] - + "){PlotPlayer.setMeta(\"location\",plot.getBottomAbs());PlotPlayer.setMeta(\"lastplot\",plot);_3.onCommand" - + "(PlotPlayer,_2)}}"; - - break; case "all": if (args.length < 3) { Captions.COMMAND_SYNTAX diff --git a/Core/src/main/java/com/plotsquared/core/command/Grant.java b/Core/src/main/java/com/plotsquared/core/command/Grant.java index ad9d09b42..a45905522 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Grant.java +++ b/Core/src/main/java/com/plotsquared/core/command/Grant.java @@ -84,7 +84,7 @@ public class Grant extends Command { PlotPlayer pp = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); if (pp != null) { try (final MetaDataAccess access = pp.accessPersistentMetaData( - PlayerMetaDataKeys.GRANTED_PLOTS)) { + PlayerMetaDataKeys.PERSISTENT_GRANTED_PLOTS)) { if (args[0].equalsIgnoreCase("check")) { Captions.GRANTED_PLOTS.send(player, access.get().orElse(0)); } else { diff --git a/Core/src/main/java/com/plotsquared/core/command/Inbox.java b/Core/src/main/java/com/plotsquared/core/command/Inbox.java index a042e72cb..87ccd16e2 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Inbox.java +++ b/Core/src/main/java/com/plotsquared/core/command/Inbox.java @@ -25,7 +25,9 @@ */ package com.plotsquared.core.command; +import com.google.inject.TypeLiteral; import com.plotsquared.core.configuration.Captions; +import com.plotsquared.core.player.MetaDataAccess; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.comment.CommentInbox; @@ -34,6 +36,7 @@ import com.plotsquared.core.plot.comment.PlotComment; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.task.RunnableVal; +import com.plotsquared.core.player.MetaDataKey; import java.util.List; @@ -140,7 +143,10 @@ public class Inbox extends SubCommand { StringMan.join(CommentManager.inboxes.keySet(), ", ")); return false; } - player.setMeta("inbox:" + inbox.toString(), System.currentTimeMillis()); + final MetaDataKey metaDataKey = MetaDataKey.of(String.format("inbox:%s", inbox.toString()), new TypeLiteral() {}); + try (final MetaDataAccess metaDataAccess = player.accessTemporaryMetaData(metaDataKey)) { + metaDataAccess.set(System.currentTimeMillis()); + } final int page; if (args.length > 1) { switch (args[1].toLowerCase()) { diff --git a/Core/src/main/java/com/plotsquared/core/command/Load.java b/Core/src/main/java/com/plotsquared/core/command/Load.java index cc099687b..60d17a771 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Load.java +++ b/Core/src/main/java/com/plotsquared/core/command/Load.java @@ -28,6 +28,8 @@ package com.plotsquared.core.command; import com.google.inject.Inject; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -43,6 +45,7 @@ import javax.annotation.Nonnull; import java.net.MalformedURLException; import java.net.URL; +import java.util.Collections; import java.util.List; @CommandDeclaration(command = "load", @@ -86,44 +89,46 @@ public class Load extends SubCommand { return false; } - if (args.length != 0) { - if (args.length == 1) { - List schematics = player.getMeta("plot_schematics"); - if (schematics == null) { - // No schematics found: - MainUtil.sendMessage(player, Captions.LOAD_NULL); - return false; - } - String schematic; - try { - schematic = schematics.get(Integer.parseInt(args[0]) - 1); - } catch (Exception ignored) { - // use /plot load - MainUtil.sendMessage(player, Captions.NOT_VALID_NUMBER, - "(1, " + schematics.size() + ')'); - return false; - } - final URL url; - try { - url = new URL(Settings.Web.URL + "saves/" + player.getUUID() + '/' + schematic); - } catch (MalformedURLException e) { - e.printStackTrace(); - MainUtil.sendMessage(player, Captions.LOAD_FAILED); - return false; - } - plot.addRunning(); - MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); - TaskManager.runTaskAsync(() -> { - Schematic taskSchematic = this.schematicHandler.getSchematic(url); - if (taskSchematic == null) { - plot.removeRunning(); - sendMessage(player, Captions.SCHEMATIC_INVALID, - "non-existent or not in gzip format"); - return; + try (final MetaDataAccess> metaDataAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_SCHEMATICS)) { + if (args.length != 0) { + if (args.length == 1) { + List schematics = metaDataAccess.get().orElse(null); + if (schematics == null) { + // No schematics found: + MainUtil.sendMessage(player, Captions.LOAD_NULL); + return false; } - PlotArea area = plot.getArea(); - this.schematicHandler.paste(taskSchematic, plot, 0, area.getMinBuildHeight(), 0, false, - new RunnableVal() { + String schematic; + try { + schematic = schematics.get(Integer.parseInt(args[0]) - 1); + } catch (Exception ignored) { + // use /plot load + MainUtil.sendMessage(player, Captions.NOT_VALID_NUMBER, + "(1, " + schematics.size() + ')'); + return false; + } + final URL url; + try { + url = new URL(Settings.Web.URL + "saves/" + player.getUUID() + '/' + schematic); + } catch (MalformedURLException e) { + e.printStackTrace(); + MainUtil.sendMessage(player, Captions.LOAD_FAILED); + return false; + } + plot.addRunning(); + MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); + TaskManager.runTaskAsync(() -> { + Schematic taskSchematic = this.schematicHandler.getSchematic(url); + if (taskSchematic == null) { + plot.removeRunning(); + sendMessage(player, Captions.SCHEMATIC_INVALID, + "non-existent or not in gzip format"); + return; + } + PlotArea area = plot.getArea(); + this.schematicHandler + .paste(taskSchematic, plot, 0, area.getMinBuildHeight(), 0, false, new RunnableVal() { @Override public void run(Boolean value) { plot.removeRunning(); if (value) { @@ -133,58 +138,61 @@ public class Load extends SubCommand { } } }); - }); - return true; - } - plot.removeRunning(); - MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot load "); - return false; - } - - // list schematics - - List schematics = player.getMeta("plot_schematics"); - if (schematics == null) { - plot.addRunning(); - TaskManager.runTaskAsync(() -> { - List schematics1 = this.schematicHandler.getSaves(player.getUUID()); - plot.removeRunning(); - if ((schematics1 == null) || schematics1.isEmpty()) { - MainUtil.sendMessage(player, Captions.LOAD_FAILED); - return; + }); + return true; } - player.setMeta("plot_schematics", schematics1); + plot.removeRunning(); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot load "); + return false; + } + + // list schematics + + List schematics = metaDataAccess.get().orElse(null); + if (schematics == null) { + plot.addRunning(); + TaskManager.runTaskAsync(() -> { + List schematics1 = this.schematicHandler.getSaves(player.getUUID()); + plot.removeRunning(); + if ((schematics1 == null) || schematics1.isEmpty()) { + MainUtil.sendMessage(player, Captions.LOAD_FAILED); + return; + } + metaDataAccess.set(schematics1); + displaySaves(player); + }); + } else { displaySaves(player); - }); - } else { - displaySaves(player); + } } return true; } public void displaySaves(PlotPlayer player) { - List schematics = player.getMeta("plot_schematics"); - for (int i = 0; i < Math.min(schematics.size(), 32); i++) { - try { - String schematic = schematics.get(i).split("\\.")[0]; - String[] split = schematic.split("_"); - if (split.length < 5) { - continue; + try (final MetaDataAccess> metaDataAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_SCHEMATICS)) { + List schematics = metaDataAccess.get().orElse(Collections.emptyList()); + for (int i = 0; i < Math.min(schematics.size(), 32); i++) { + try { + String schematic = schematics.get(i).split("\\.")[0]; + String[] split = schematic.split("_"); + if (split.length < 5) { + continue; + } + String time = secToTime((System.currentTimeMillis() / 1000) - Long.parseLong(split[0])); + String world = split[1]; + PlotId id = PlotId.fromString(split[2] + ';' + split[3]); + String size = split[4]; + String color = "$4"; + MainUtil.sendMessage(player, + "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ';' + id + + "$3 | " + color + size + 'x' + size); + } catch (Exception e) { + e.printStackTrace(); } - String time = - secToTime((System.currentTimeMillis() / 1000) - Long.parseLong(split[0])); - String world = split[1]; - PlotId id = PlotId.fromString(split[2] + ';' + split[3]); - String size = split[4]; - String color = "$4"; - MainUtil.sendMessage(player, - "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ';' + id - + "$3 | " + color + size + 'x' + size); - } catch (Exception e) { - e.printStackTrace(); } + MainUtil.sendMessage(player, Captions.LOAD_LIST); } - MainUtil.sendMessage(player, Captions.LOAD_LIST); } public String secToTime(long time) { diff --git a/Core/src/main/java/com/plotsquared/core/command/MainCommand.java b/Core/src/main/java/com/plotsquared/core/command/MainCommand.java index d724155cf..cfe608599 100644 --- a/Core/src/main/java/com/plotsquared/core/command/MainCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/MainCommand.java @@ -31,6 +31,8 @@ import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.location.Location; import com.plotsquared.core.player.ConsolePlayer; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -43,6 +45,7 @@ import com.plotsquared.core.util.task.RunnableVal3; import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.concurrent.CompletableFuture; /** @@ -231,7 +234,11 @@ public class MainCommand extends Command { RunnableVal3 confirm, RunnableVal2 whenDone) { // Clear perm caching // - player.deleteMeta("perm"); + try (final MetaDataAccess> permAccess = player.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_PERMISSIONS)) { + permAccess.remove(); + } + // Optional command scope // Location location = null; Plot plot = null; @@ -246,12 +253,17 @@ public class MainCommand extends Command { Location newLoc = newPlot.getCenterSynchronous(); if (player.canTeleport(newLoc)) { // Save meta - location = player.getMeta(PlotPlayer.META_LOCATION); - plot = player.getMeta(PlotPlayer.META_LAST_PLOT); + try (final MetaDataAccess locationMetaDataAccess + = player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + location = locationMetaDataAccess.get().orElse(null); + locationMetaDataAccess.set(newLoc); + } + try (final MetaDataAccess plotMetaDataAccess + = player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + plot = plotMetaDataAccess.get().orElse(null); + plotMetaDataAccess.set(newPlot); + } tp = true; - // Set loc - player.setMeta(PlotPlayer.META_LOCATION, newLoc); - player.setMeta(PlotPlayer.META_LAST_PLOT, newPlot); } else { Captions.BORDER.send(player); } @@ -304,15 +316,21 @@ public class MainCommand extends Command { } // Reset command scope // if (tp && !(player instanceof ConsolePlayer)) { - if (location == null) { - player.deleteMeta(PlotPlayer.META_LOCATION); - } else { - player.setMeta(PlotPlayer.META_LOCATION, location); + try (final MetaDataAccess locationMetaDataAccess + = player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + if (location == null) { + locationMetaDataAccess.remove(); + } else { + locationMetaDataAccess.set(location); + } } - if (plot == null) { - player.deleteMeta(PlotPlayer.META_LAST_PLOT); - } else { - player.setMeta(PlotPlayer.META_LAST_PLOT, plot); + try (final MetaDataAccess plotMetaDataAccess + = player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + if (plot == null) { + plotMetaDataAccess.remove(); + } else { + plotMetaDataAccess.set(plot); + } } } return CompletableFuture.completedFuture(true); diff --git a/Core/src/main/java/com/plotsquared/core/command/Save.java b/Core/src/main/java/com/plotsquared/core/command/Save.java index bde167dd9..7ab7f1a41 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Save.java +++ b/Core/src/main/java/com/plotsquared/core/command/Save.java @@ -28,6 +28,8 @@ package com.plotsquared.core.command; import com.google.inject.Inject; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.location.Location; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotId; @@ -104,9 +106,9 @@ public class Save extends SubCommand { return; } MainUtil.sendMessage(player, Captions.SAVE_SUCCESS); - List schematics = player.getMeta("plot_schematics"); - if (schematics != null) { - schematics.add(file + ".schem"); + try (final MetaDataAccess> schematicAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_SCHEMATICS)) { + schematicAccess.get().ifPresent(schematics -> schematics.add(file + ".schem")); } } }); diff --git a/Core/src/main/java/com/plotsquared/core/command/Setup.java b/Core/src/main/java/com/plotsquared/core/command/Setup.java index cf412656a..a13b54f92 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Setup.java +++ b/Core/src/main/java/com/plotsquared/core/command/Setup.java @@ -29,6 +29,8 @@ import com.google.inject.Inject; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.generator.GeneratorWrapper; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.setup.SetupProcess; import com.plotsquared.core.setup.SetupStep; @@ -72,42 +74,48 @@ public class Setup extends SubCommand { } @Override public boolean onCommand(PlotPlayer player, String[] args) { - SetupProcess process = player.getMeta("setup"); - if (process == null) { - if (args.length > 0) { - MainUtil.sendMessage(player, Captions.SETUP_NOT_STARTED); + try (final MetaDataAccess metaDataAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_SETUP)) { + SetupProcess process = metaDataAccess.get().orElse(null); + if (process == null) { + if (args.length > 0) { + MainUtil.sendMessage(player, Captions.SETUP_NOT_STARTED); + return true; + } + process = new SetupProcess(); + metaDataAccess.set(process); + this.setupUtils.updateGenerators(); + SetupStep step = process.getCurrentStep(); + step.announce(player); + displayGenerators(player); return true; } - process = new SetupProcess(); - player.setMeta("setup", process); - this.setupUtils.updateGenerators(); - SetupStep step = process.getCurrentStep(); - step.announce(player); - displayGenerators(player); + if (args.length == 1) { + if ("back".equalsIgnoreCase(args[0])) { + process.back(); + process.getCurrentStep().announce(player); + } else if ("cancel".equalsIgnoreCase(args[0])) { + metaDataAccess.remove(); + MainUtil.sendMessage(player, Captions.SETUP_CANCELLED); + } else { + process.handleInput(player, args[0]); + if (process.getCurrentStep() != null) { + process.getCurrentStep().announce(player); + } + } + } else { + process.getCurrentStep().announce(player); + } return true; } - if (args.length == 1) { - if ("back".equalsIgnoreCase(args[0])) { - process.back(); - process.getCurrentStep().announce(player); - } else if ("cancel".equalsIgnoreCase(args[0])) { - player.deleteMeta("setup"); - MainUtil.sendMessage(player, Captions.SETUP_CANCELLED); - } else { - process.handleInput(player, args[0]); - if (process.getCurrentStep() != null) { - process.getCurrentStep().announce(player); - } - } - } else { - process.getCurrentStep().announce(player); - } - return true; - } @Override public Collection tab(PlotPlayer player, String[] args, boolean space) { - SetupProcess process = (SetupProcess) player.getMeta("setup"); // TODO use generics -> auto cast + SetupProcess process; + try (final MetaDataAccess metaDataAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_SETUP)) { + process = metaDataAccess.get().orElse(null); + } if (process == null) { return Collections.emptyList(); } diff --git a/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java b/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java index 9fcaad2de..0fb0a8977 100644 --- a/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java +++ b/Core/src/main/java/com/plotsquared/core/listener/PlotListener.java @@ -32,6 +32,7 @@ import com.plotsquared.core.events.PlotFlagRemoveEvent; import com.plotsquared.core.events.Result; import com.plotsquared.core.location.Location; import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.MetaDataKey; import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; @@ -136,14 +137,16 @@ public class PlotListener { .hasPermission(player, "plots.admin.entry.denied")) { return false; } - Plot last = player.getMeta(PlotPlayer.META_LAST_PLOT); - if ((last != null) && !last.getId().equals(plot.getId())) { - plotExit(player, last); + try (final MetaDataAccess lastPlot = player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + Plot last = lastPlot.get().orElse(null); + if ((last != null) && !last.getId().equals(plot.getId())) { + plotExit(player, last); + } + if (ExpireManager.IMP != null) { + ExpireManager.IMP.handleEntry(player, plot); + } + lastPlot.set(plot); } - if (ExpireManager.IMP != null) { - ExpireManager.IMP.handleEntry(player, plot); - } - player.setMeta(PlotPlayer.META_LAST_PLOT, plot); this.eventDispatcher.callEntry(player, plot); if (plot.hasOwner()) { // This will inherit values from PlotArea @@ -230,39 +233,47 @@ public class PlotListener { player.setWeather(plot.getFlag(WeatherFlag.class)); ItemType musicFlag = plot.getFlag(MusicFlag.class); - if (musicFlag != null) { - final String rawId = musicFlag.getId(); - if (rawId.contains("disc") || musicFlag == ItemTypes.AIR) { - Location location = player.getLocation(); - Location lastLocation = player.getMeta("music"); - if (lastLocation != null) { - player.playMusic(lastLocation, musicFlag); - if (musicFlag == ItemTypes.AIR) { - player.deleteMeta("music"); + + try (final MetaDataAccess musicMeta = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_MUSIC)) { + if (musicFlag != null) { + final String rawId = musicFlag.getId(); + if (rawId.contains("disc") || musicFlag == ItemTypes.AIR) { + Location location = player.getLocation(); + Location lastLocation = musicMeta.get().orElse(null); + if (lastLocation != null) { + player.playMusic(lastLocation, musicFlag); + if (musicFlag == ItemTypes.AIR) { + musicMeta.remove(); + } + } + if (musicFlag != ItemTypes.AIR) { + try { + musicMeta.set(location); + player.playMusic(location, musicFlag); + } catch (Exception ignored) { + } } } - if (musicFlag != ItemTypes.AIR) { - try { - player.setMeta("music", location); - player.playMusic(location, musicFlag); - } catch (Exception ignored) { - } - } - } - } else { - Location lastLoc = player.getMeta("music"); - if (lastLoc != null) { - player.deleteMeta("music"); - player.playMusic(lastLoc, ItemTypes.AIR); + } else { + musicMeta.get().ifPresent(lastLoc -> { + musicMeta.remove(); + player.playMusic(lastLoc, ItemTypes.AIR); + }); } } + CommentManager.sendTitle(player, plot); if (titles && !player.getAttribute("disabletitles")) { if (!Captions.TITLE_ENTERED_PLOT.getTranslated().isEmpty() || !Captions.TITLE_ENTERED_PLOT_SUB.getTranslated().isEmpty()) { TaskManager.runTaskLaterAsync(() -> { - Plot lastPlot = player.getMeta(PlotPlayer.META_LAST_PLOT); + Plot lastPlot = null; + try (final MetaDataAccess lastPlotAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + lastPlot = lastPlotAccess.get().orElse(null); + } if ((lastPlot != null) && plot.getId().equals(lastPlot.getId())) { Map replacements = new HashMap<>(); replacements.put("%x%", String.valueOf(lastPlot.getId().getX())); @@ -299,89 +310,96 @@ public class PlotListener { } public boolean plotExit(final PlotPlayer player, Plot plot) { - Object previous = player.deleteMeta(PlotPlayer.META_LAST_PLOT); - this.eventDispatcher.callLeave(player, plot); - if (plot.hasOwner()) { - PlotArea pw = plot.getArea(); - if (pw == null) { - return true; - } - if (plot.getFlag(DenyExitFlag.class) && !Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_EXIT_DENIED) && !player - .getMeta("kick", false)) { - if (previous != null) { - player.setMeta(PlotPlayer.META_LAST_PLOT, previous); + try (final MetaDataAccess lastPlot = player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + final Plot previous = lastPlot.remove(); + this.eventDispatcher.callLeave(player, plot); + if (plot.hasOwner()) { + PlotArea pw = plot.getArea(); + if (pw == null) { + return true; } - return false; - } - if (!plot.getFlag(GamemodeFlag.class).equals(GamemodeFlag.DEFAULT) || !plot - .getFlag(GuestGamemodeFlag.class).equals(GamemodeFlag.DEFAULT)) { - if (player.getGameMode() != pw.getGameMode()) { - if (!Permissions.hasPermission(player, "plots.gamemode.bypass")) { - player.setGameMode(pw.getGameMode()); - } else { - MainUtil.sendMessage(player, StringMan - .replaceAll(Captions.GAMEMODE_WAS_BYPASSED.getTranslated(), "{plot}", - plot.toString(), "{gamemode}", - pw.getGameMode().getName().toLowerCase())); + try (final MetaDataAccess kickAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_KICK)) { + if (plot.getFlag(DenyExitFlag.class) && !Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_EXIT_DENIED) && + !kickAccess.get().orElse(false)) { + if (previous != null) { + lastPlot.set(previous); + } + return false; } } - } - - final String farewell = plot.getFlag(FarewellFlag.class); - if (!farewell.isEmpty()) { - plot.format(Captions.PREFIX_FAREWELL.getTranslated() + farewell, player, false) - .thenAcceptAsync(player::sendMessage); - } - - if (plot.getFlag(NotifyLeaveFlag.class)) { - if (!Permissions.hasPermission(player, "plots.flag.notify-enter.bypass")) { - for (UUID uuid : plot.getOwners()) { - final PlotPlayer owner = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); - if ((owner != null) && !owner.getUUID().equals(player.getUUID())) { - MainUtil.sendMessage(owner, Captions.NOTIFY_LEAVE.getTranslated() - .replace("%player", player.getName()) - .replace("%plot", plot.getId().toString())); + if (!plot.getFlag(GamemodeFlag.class).equals(GamemodeFlag.DEFAULT) || !plot + .getFlag(GuestGamemodeFlag.class).equals(GamemodeFlag.DEFAULT)) { + if (player.getGameMode() != pw.getGameMode()) { + if (!Permissions.hasPermission(player, "plots.gamemode.bypass")) { + player.setGameMode(pw.getGameMode()); + } else { + MainUtil.sendMessage(player, StringMan + .replaceAll(Captions.GAMEMODE_WAS_BYPASSED.getTranslated(), "{plot}", + plot.toString(), "{gamemode}", + pw.getGameMode().getName().toLowerCase())); } } } - } - final FlyFlag.FlyStatus flyStatus = plot.getFlag(FlyFlag.class); - if (flyStatus != FlyFlag.FlyStatus.DEFAULT) { - try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData(PlayerMetaDataKeys.PERSISTENT_FLIGHT)) { - final Optional value = metaDataAccess.get(); - if (value.isPresent()) { - player.setFlight(value.get()); - metaDataAccess.remove(); - } else { - GameMode gameMode = player.getGameMode(); - if (gameMode == GameModes.SURVIVAL || gameMode == GameModes.ADVENTURE) { - player.setFlight(false); - } else if (!player.getFlight()) { - player.setFlight(true); + final String farewell = plot.getFlag(FarewellFlag.class); + if (!farewell.isEmpty()) { + plot.format(Captions.PREFIX_FAREWELL.getTranslated() + farewell, player, false) + .thenAcceptAsync(player::sendMessage); + } + + if (plot.getFlag(NotifyLeaveFlag.class)) { + if (!Permissions.hasPermission(player, "plots.flag.notify-enter.bypass")) { + for (UUID uuid : plot.getOwners()) { + final PlotPlayer owner = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); + if ((owner != null) && !owner.getUUID().equals(player.getUUID())) { + MainUtil.sendMessage(owner, Captions.NOTIFY_LEAVE.getTranslated() + .replace("%player", player.getName()) + .replace("%plot", plot.getId().toString())); + } } } } - } - if (plot.getFlag(TimeFlag.class) != TimeFlag.TIME_DISABLED.getValue().longValue()) { - player.setTime(Long.MAX_VALUE); - } + final FlyFlag.FlyStatus flyStatus = plot.getFlag(FlyFlag.class); + if (flyStatus != FlyFlag.FlyStatus.DEFAULT) { + try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData(PlayerMetaDataKeys.PERSISTENT_FLIGHT)) { + final Optional value = metaDataAccess.get(); + if (value.isPresent()) { + player.setFlight(value.get()); + metaDataAccess.remove(); + } else { + GameMode gameMode = player.getGameMode(); + if (gameMode == GameModes.SURVIVAL || gameMode == GameModes.ADVENTURE) { + player.setFlight(false); + } else if (!player.getFlight()) { + player.setFlight(true); + } + } + } + } - final PlotWeather plotWeather = plot.getFlag(WeatherFlag.class); - if (plotWeather != PlotWeather.CLEAR) { - player.setWeather(PlotWeather.RESET); - } + if (plot.getFlag(TimeFlag.class) != TimeFlag.TIME_DISABLED.getValue().longValue()) { + player.setTime(Long.MAX_VALUE); + } - Location lastLoc = player.getMeta("music"); - if (lastLoc != null) { - player.deleteMeta("music"); - player.playMusic(lastLoc, ItemTypes.AIR); - } + final PlotWeather plotWeather = plot.getFlag(WeatherFlag.class); + if (plotWeather != PlotWeather.CLEAR) { + player.setWeather(PlotWeather.RESET); + } - feedRunnable.remove(player.getUUID()); - healRunnable.remove(player.getUUID()); + try (final MetaDataAccess musicAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_MUSIC)) { + musicAccess.get().ifPresent(lastLoc -> { + musicAccess.remove(); + player.playMusic(lastLoc, ItemTypes.AIR); + }); + } + + feedRunnable.remove(player.getUUID()); + healRunnable.remove(player.getUUID()); + } } return true; } diff --git a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java index c6efe33cd..506736de2 100644 --- a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java @@ -32,6 +32,7 @@ import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.inject.annotations.ConsoleActor; import com.plotsquared.core.location.Location; +import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotWeather; import com.plotsquared.core.plot.world.PlotAreaManager; @@ -134,8 +135,16 @@ public class ConsolePlayer extends PlotPlayer { } @Override public void teleport(Location location, TeleportCause cause) { - setMeta(META_LAST_PLOT, location.getPlot()); - setMeta(META_LOCATION, location); + try (final MetaDataAccess lastPlot = accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + if (location.getPlot() == null) { + lastPlot.remove(); + } else { + lastPlot.set(location.getPlot()); + } + } + try (final MetaDataAccess locationMetaDataAccess = accessPersistentMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + locationMetaDataAccess.set(location); + } } @Override public boolean isOnline() { diff --git a/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java b/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java index b4f494edf..c38111b73 100644 --- a/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java +++ b/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java @@ -28,6 +28,7 @@ package com.plotsquared.core.player; import com.plotsquared.core.synchronization.LockRepository; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Optional; /** @@ -59,8 +60,10 @@ public abstract class MetaDataAccess implements AutoCloseable { /** * Remove the stored value meta data + * + * @return Old value, or {@link null} */ - public abstract void remove(); + @Nullable public abstract T remove(); /** * Set the meta data value diff --git a/Core/src/main/java/com/plotsquared/core/player/MetaDataKey.java b/Core/src/main/java/com/plotsquared/core/player/MetaDataKey.java index 4b51ca12a..ab013e9c9 100644 --- a/Core/src/main/java/com/plotsquared/core/player/MetaDataKey.java +++ b/Core/src/main/java/com/plotsquared/core/player/MetaDataKey.java @@ -27,6 +27,7 @@ package com.plotsquared.core.player; import com.google.common.base.Objects; import com.google.common.base.Preconditions; +import com.google.inject.TypeLiteral; import com.plotsquared.core.synchronization.LockKey; import javax.annotation.Nonnull; @@ -44,10 +45,10 @@ public final class MetaDataKey { private static final Object keyMetaData = new Object(); private final String key; - private final Class type; + private final TypeLiteral type; private final LockKey lockKey; - private MetaDataKey(@Nonnull final String key, @Nonnull final Class type) { + private MetaDataKey(@Nonnull final String key, @Nonnull final TypeLiteral type) { this.key = Preconditions.checkNotNull(key, "Key may not be null"); this.type = Preconditions.checkNotNull(type, "Type may not be null"); this.lockKey = LockKey.of(this.key); @@ -60,7 +61,7 @@ public final class MetaDataKey { * @param Type * @return MetaData key instance */ - @Nonnull public static MetaDataKey of(@Nonnull final String key, @Nonnull final Class type) { + @Nonnull public static MetaDataKey of(@Nonnull final String key, @Nonnull final TypeLiteral type) { synchronized (keyMetaData) { return (MetaDataKey) keyMap.computeIfAbsent(key, missingKey -> new MetaDataKey<>(missingKey, type)); @@ -100,7 +101,7 @@ public final class MetaDataKey { * * @return Meta data type */ - @Nonnull public Class getType() { + @Nonnull public TypeLiteral getType() { return this.type; } diff --git a/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java b/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java index c0380b233..e7bb67103 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java +++ b/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java @@ -28,9 +28,10 @@ package com.plotsquared.core.player; import com.plotsquared.core.synchronization.LockRepository; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Optional; -public final class PersistentMetaDataAccess extends MetaDataAccess { +final class PersistentMetaDataAccess extends MetaDataAccess { PersistentMetaDataAccess(@Nonnull final PlotPlayer player, @Nonnull final MetaDataKey metaDataKey, @@ -42,8 +43,12 @@ public final class PersistentMetaDataAccess extends MetaDataAccess { return this.getPlayer().hasPersistentMeta(getMetaDataKey().toString()); } - @Override public void remove() { - this.getPlayer().removePersistentMeta(this.getMetaDataKey().toString()); + @Override @Nullable public T remove() { + final Object old = this.getPlayer().removePersistentMeta(this.getMetaDataKey().toString()); + if (old == null) { + return null; + } + return (T) old; } @Override public void set(@Nonnull T value) { diff --git a/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java b/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java index 5140c4b5c..d1cf087d9 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java @@ -25,10 +25,36 @@ */ package com.plotsquared.core.player; +import com.google.inject.TypeLiteral; +import com.plotsquared.core.command.Auto; +import com.plotsquared.core.command.CmdInstance; +import com.plotsquared.core.location.Location; +import com.plotsquared.core.plot.Plot; +import com.plotsquared.core.plot.PlotInventory; +import com.plotsquared.core.setup.SetupProcess; + +import java.util.List; +import java.util.Map; + public final class PlayerMetaDataKeys { - public static final MetaDataKey PERSISTENT_FLIGHT = MetaDataKey.of("flight", Boolean.class); - public static final MetaDataKey GRANTED_PLOTS = MetaDataKey.of("grantedPlots", Integer.class); + //@formatter:off + public static final MetaDataKey PERSISTENT_FLIGHT = MetaDataKey.of("flight", new TypeLiteral() {}); + public static final MetaDataKey PERSISTENT_GRANTED_PLOTS = MetaDataKey.of("grantedPlots", new TypeLiteral() {}); + + public static final MetaDataKey TEMPORARY_LAST_PLOT = MetaDataKey.of("lastplot", new TypeLiteral() {}); + public static final MetaDataKey TEMPORARY_MUSIC = MetaDataKey.of("music", new TypeLiteral() {}); + public static final MetaDataKey TEMPORARY_KICK = MetaDataKey.of("kick", new TypeLiteral() {}); + public static final MetaDataKey TEMPORARY_SETUP = MetaDataKey.of("setup", new TypeLiteral() {}); + public static final MetaDataKey TEMPORARY_INVENTORY = MetaDataKey.of("inventory", new TypeLiteral() {}); + public static final MetaDataKey TEMPORARY_IGNORE_EXPIRE_TASK = MetaDataKey.of("ignoreExpireTask", new TypeLiteral() {}); + public static final MetaDataKey TEMPORARY_WORLD_EDIT_REGION_PLOT = MetaDataKey.of("WorldEditRegionPlot", new TypeLiteral() {}); + public static final MetaDataKey TEMPORARY_AUTO = MetaDataKey.of(Auto.class.getName(), new TypeLiteral() {}); + public static final MetaDataKey> TEMPORARY_PERMISSIONS = MetaDataKey.of("permissions", new TypeLiteral>() {}); + public static final MetaDataKey> TEMPORARY_SCHEMATICS = MetaDataKey.of("plot_schematics", new TypeLiteral>() {}); + public static final MetaDataKey TEMPORARY_LOCATION = MetaDataKey.of("location", new TypeLiteral() {}); + public static final MetaDataKey TEMPORARY_CONFIRM = MetaDataKey.of("cmdConfirm", new TypeLiteral() {}); + //@formatter:on private PlayerMetaDataKeys() { } diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index 8907a2069..43390b2fe 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -81,9 +81,6 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer private static final Logger logger = LoggerFactory.getLogger("P2/" + PlotPlayer.class.getSimpleName()); - public static final String META_LAST_PLOT = "lastplot"; - public static final String META_LOCATION = "location"; - // Used to track debug mode private static final Set> debugModeEnabled = Collections.synchronizedSet(new HashSet<>()); @@ -162,7 +159,7 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer * @param key * @param value */ - public void setMeta(String key, Object value) { + void setMeta(String key, Object value) { if (value == null) { deleteMeta(key); } else { @@ -180,14 +177,14 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer * @param the object type to return * @return the value assigned to the key or null if it does not exist */ - public T getMeta(String key) { + T getMeta(String key) { if (this.meta != null) { return (T) this.meta.get(key); } return null; } - public T getMeta(String key, T defaultValue) { + T getMeta(String key, T defaultValue) { T meta = getMeta(key); if (meta == null) { return defaultValue; @@ -206,7 +203,7 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer * * @param key */ - public Object deleteMeta(String key) { + Object deleteMeta(String key) { return this.meta == null ? null : this.meta.remove(key); } @@ -225,11 +222,13 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer * @return the plot the player is standing on or null if standing on a road or not in a {@link PlotArea} */ public Plot getCurrentPlot() { - Plot value = getMeta(PlotPlayer.META_LAST_PLOT); - if (value == null && !Settings.Enabled_Components.EVENTS) { - return getLocation().getPlot(); + try (final MetaDataAccess lastPlotAccess = + this.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + if (lastPlotAccess.get().orElse(null) == null && !Settings.Enabled_Components.EVENTS) { + return this.getLocation().getPlot(); + } + return lastPlotAccess.get().orElse(null); } - return value; } /** @@ -730,11 +729,12 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return this.metaMap.get(key); } - void removePersistentMeta(String key) { - this.metaMap.remove(key); + Object removePersistentMeta(String key) { + final Object old = this.metaMap.remove(key); if (Settings.Enabled_Components.PERSISTENT_META) { DBFunc.removePersistentMeta(getUUID(), key); } + return old; } /** @@ -756,15 +756,34 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return new PersistentMetaDataAccess<>(this, key, this.lockRepository.lock(key.getLockKey())); } + /** + * Access keyed temporary meta data for this player. This returns a meta data + * access instance, that MUST be closed. It is meant to be used with try-with-resources, + * like such: + *

{@code
+     * try (final MetaDataAccess access = player.accessTemporaryMetaData(PlayerMetaKeys.GRANTS)) {
+     *     int grants = access.get();
+     *     access.set(grants + 1);
+     * }
+     * }
+ * + * @param key Meta data key + * @param Meta data type + * @return Meta data access. MUST be closed after being used + */ + @Nonnull public MetaDataAccess accessTemporaryMetaData(@Nonnull final MetaDataKey key) { + return new TemporaryMetaDataAccess<>(this, key, this.lockRepository.lock(key.getLockKey())); + } + void setPersistentMeta(@Nonnull final MetaDataKey key, @Nonnull final T value) { final Object rawValue = value; - if (key.getType().equals(Integer.class)) { + if (key.getType().getRawType().equals(Integer.class)) { this.setPersistentMeta(key.toString(), Ints.toByteArray((int) rawValue)); - } else if (key.getType().equals(Boolean.class)) { + } else if (key.getType().getRawType().equals(Boolean.class)) { this.setPersistentMeta(key.toString(), ByteArrayUtilities.booleanToBytes((boolean) rawValue)); } else { - throw new IllegalArgumentException(String.format("Unknown meta data type '%s'", key.getType().getSimpleName())); + throw new IllegalArgumentException(String.format("Unknown meta data type '%s'", key.getType().toString())); } } @@ -774,12 +793,12 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer return null; } final Object returnValue; - if (key.getType().equals(Integer.class)) { + if (key.getType().getRawType().equals(Integer.class)) { returnValue = Ints.fromByteArray(value); - } else if (key.getType().equals(Boolean.class)) { + } else if (key.getType().getRawType().equals(Boolean.class)) { returnValue = ByteArrayUtilities.bytesToBoolean(value); } else { - throw new IllegalArgumentException(String.format("Unknown meta data type '%s'", key.getType().getSimpleName())); + throw new IllegalArgumentException(String.format("Unknown meta data type '%s'", key.getType().toString())); } return (T) returnValue; } diff --git a/Core/src/main/java/com/plotsquared/core/player/TemporaryMetaDataAccess.java b/Core/src/main/java/com/plotsquared/core/player/TemporaryMetaDataAccess.java new file mode 100644 index 000000000..b301f5be7 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/player/TemporaryMetaDataAccess.java @@ -0,0 +1,62 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package com.plotsquared.core.player; + +import com.plotsquared.core.synchronization.LockRepository; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; + +final class TemporaryMetaDataAccess extends MetaDataAccess { + + TemporaryMetaDataAccess(@Nonnull final PlotPlayer player, + @Nonnull final MetaDataKey metaDataKey, + @Nonnull final LockRepository.LockAccess lockAccess) { + super(player, metaDataKey, lockAccess); + } + + @Override public boolean has() { + return this.getPlayer().getMeta(this.getMetaDataKey().toString()) != null; + } + + @Override @Nullable public T remove() { + final Object old = getPlayer().deleteMeta(this.getMetaDataKey().toString()); + if (old == null) { + return null; + } + return (T) old; + } + + @Override public void set(@Nonnull T value) { + this.getPlayer().setMeta(this.getMetaDataKey().toString(), null); + } + + @Nonnull @Override public Optional get() { + return Optional.ofNullable(this.getPlayer().getMeta(this.getMetaDataKey().toString())); + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java index 815bdeae2..438c4bcde 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java @@ -42,6 +42,8 @@ import com.plotsquared.core.inject.annotations.WorldConfig; import com.plotsquared.core.location.Direction; import com.plotsquared.core.location.Location; import com.plotsquared.core.location.PlotLoc; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.flag.FlagContainer; import com.plotsquared.core.plot.flag.FlagParseException; @@ -787,8 +789,11 @@ public abstract class PlotArea { } public boolean addPlot(@Nonnull final Plot plot) { - for (PlotPlayer pp : plot.getPlayersInPlot()) { - pp.setMeta(PlotPlayer.META_LAST_PLOT, plot); + for (final PlotPlayer pp : plot.getPlayersInPlot()) { + try (final MetaDataAccess metaDataAccess = pp.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + metaDataAccess.set(plot); + } } return this.plots.put(plot.getId(), plot) == null; } @@ -826,8 +831,11 @@ public abstract class PlotArea { public boolean addPlotIfAbsent(@Nonnull final Plot plot) { if (this.plots.putIfAbsent(plot.getId(), plot) == null) { - for (PlotPlayer pp : plot.getPlayersInPlot()) { - pp.setMeta(PlotPlayer.META_LAST_PLOT, plot); + for (PlotPlayer pp : plot.getPlayersInPlot()) { + try (final MetaDataAccess metaDataAccess = pp.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + metaDataAccess.set(plot); + } } return true; } diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotInventory.java b/Core/src/main/java/com/plotsquared/core/plot/PlotInventory.java index a810093b0..d843030c3 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotInventory.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotInventory.java @@ -25,18 +25,19 @@ */ package com.plotsquared.core.plot; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.util.InventoryUtil; - -import javax.annotation.Nonnull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; + public class PlotInventory { private static final Logger logger = LoggerFactory.getLogger("P2/" + PlotInventory.class.getSimpleName()); - private static final String META_KEY = "inventory"; public final PlotPlayer player; public final int size; private final PlotItemStack[] items; @@ -58,16 +59,25 @@ public class PlotInventory { } public static PlotInventory getOpenPlotInventory(@Nonnull final PlotPlayer plotPlayer) { - return plotPlayer.getMeta(META_KEY, null); + try (final MetaDataAccess inventoryAccess = plotPlayer.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_INVENTORY)) { + return inventoryAccess.get().orElse(null); + } } public static void setPlotInventoryOpen(@Nonnull final PlotPlayer plotPlayer, @Nonnull final PlotInventory plotInventory) { - plotPlayer.setMeta(META_KEY, plotInventory); + try (final MetaDataAccess inventoryAccess = plotPlayer.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_INVENTORY)) { + inventoryAccess.set(plotInventory); + } } public static void removePlotInventoryOpen(@Nonnull final PlotPlayerplotPlayer) { - plotPlayer.deleteMeta(META_KEY); + try (final MetaDataAccess inventoryAccess = plotPlayer.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_INVENTORY)) { + inventoryAccess.remove(); + } } public boolean onClick(int index) { diff --git a/Core/src/main/java/com/plotsquared/core/plot/comment/CommentManager.java b/Core/src/main/java/com/plotsquared/core/plot/comment/CommentManager.java index c751fe54a..df899fbd8 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/comment/CommentManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/comment/CommentManager.java @@ -26,8 +26,11 @@ package com.plotsquared.core.plot.comment; import com.google.common.annotations.Beta; +import com.google.inject.TypeLiteral; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.MetaDataKey; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.util.task.RunnableVal; @@ -77,7 +80,10 @@ import java.util.concurrent.atomic.AtomicInteger; } public static long getTimestamp(PlotPlayer player, String inbox) { - return player.getMeta("inbox:" + inbox, player.getLastPlayed()); + final MetaDataKey inboxKey = MetaDataKey.of(String.format("inbox:%s", inbox), new TypeLiteral() {}); + try (final MetaDataAccess inboxAccess = player.accessTemporaryMetaData(inboxKey)) { + return inboxAccess.get().orElse(player.getLastPlayed()); + } } public static void addInbox(CommentInbox inbox) { diff --git a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java index 2a3514540..6b14d0866 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java @@ -31,7 +31,9 @@ import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.events.PlotFlagAddEvent; import com.plotsquared.core.events.PlotUnlinkEvent; import com.plotsquared.core.events.Result; +import com.plotsquared.core.player.MetaDataAccess; import com.plotsquared.core.player.OfflinePlotPlayer; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -137,44 +139,42 @@ public class ExpireManager { } } - public void confirmExpiry(final PlotPlayer pp) { - if (pp.getMeta("ignoreExpireTask") != null) { - return; - } - if (plotsToDelete != null && !plotsToDelete.isEmpty() && pp - .hasPermission("plots.admin.command.autoclear")) { - final int num = plotsToDelete.size(); - while (!plotsToDelete.isEmpty()) { - Iterator iter = plotsToDelete.iterator(); - final Plot current = iter.next(); - if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) { - TaskManager.runTask(() -> { - pp.setMeta("ignoreExpireTask", true); - current.getCenter(pp::teleport); - pp.deleteMeta("ignoreExpireTask"); - PlotMessage msg = new PlotMessage() - .text(num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ") - .color("$1").text(current.toString()).color("$2") - .command("/plot list expired").tooltip("/plot list expired") - //.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired") - .text("\n - ").color("$3").text("Delete this (/plot delete)") - .color("$2").command("/plot delete").tooltip("/plot delete") - .text("\n - ").color("$3").text("Remind later (/plot flag set keep 1d)") - .color("$2").command("/plot flag set keep 1d").tooltip("/plot flag set keep 1d") - .text("\n - ").color("$3").text("Keep this (/plot flag set keep true)") - .color("$2").command("/plot flag set keep true") - .tooltip("/plot flag set keep true").text("\n - ").color("$3") - .text("Don't show me this").color("$2") - .command("/plot toggle clear-confirmation") - .tooltip("/plot toggle clear-confirmation"); - msg.send(pp); - }); - return; - } else { - iter.remove(); - } + public void confirmExpiry(final PlotPlayer pp) { + try (final MetaDataAccess metaDataAccess = pp.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_IGNORE_EXPIRE_TASK)) { + if (metaDataAccess.has()) { + return; + } + if (plotsToDelete != null && !plotsToDelete.isEmpty() && pp.hasPermission("plots.admin.command.autoclear")) { + final int num = plotsToDelete.size(); + while (!plotsToDelete.isEmpty()) { + Iterator iter = plotsToDelete.iterator(); + final Plot current = iter.next(); + if (!isExpired(new ArrayDeque<>(tasks), current).isEmpty()) { + TaskManager.runTask(() -> { + metaDataAccess.set(true); + current.getCenter(pp::teleport); + metaDataAccess.remove(); + PlotMessage msg = new PlotMessage().text( + num + " " + (num > 1 ? "plots are" : "plot is") + " expired: ").color("$1").text(current.toString()).color("$2") + .command("/plot list expired").tooltip("/plot list expired") + //.text("\n - ").color("$3").text("Delete all (/plot delete expired)").color("$2").command("/plot delete expired") + .text("\n - ").color("$3").text("Delete this (/plot delete)").color("$2").command("/plot delete").tooltip("/plot delete") + .text("\n - ").color("$3").text("Remind later (/plot flag set keep 1d)").color("$2") + .command("/plot flag set keep 1d").tooltip("/plot flag set keep 1d") + .text("\n - ").color("$3").text("Keep this (/plot flag set keep true)").color("$2") + .command("/plot flag set keep true").tooltip("/plot flag set keep true").text("\n - ").color("$3") + .text("Don't show me this").color("$2").command("/plot toggle clear-confirmation") + .tooltip("/plot toggle clear-confirmation"); + msg.send(pp); + }); + return; + } else { + iter.remove(); + } + } + plotsToDelete.clear(); } - plotsToDelete.clear(); } } diff --git a/Core/src/main/java/com/plotsquared/core/setup/CommonSetupSteps.java b/Core/src/main/java/com/plotsquared/core/setup/CommonSetupSteps.java index 2535a0e1f..dad52b55f 100644 --- a/Core/src/main/java/com/plotsquared/core/setup/CommonSetupSteps.java +++ b/Core/src/main/java/com/plotsquared/core/setup/CommonSetupSteps.java @@ -30,6 +30,8 @@ import com.plotsquared.core.configuration.Caption; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.generator.GeneratorWrapper; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotAreaTerrainType; @@ -221,7 +223,10 @@ public enum CommonSetupSteps implements SetupStep { MainUtil.sendMessage(plotPlayer, Captions.SETUP_WORLD_APPLY_PLOTSQUARED); } builder.worldName(argument); - plotPlayer.deleteMeta("setup"); + try (final MetaDataAccess setupAccess = plotPlayer.accessTemporaryMetaData( + PlayerMetaDataKeys.TEMPORARY_SETUP)) { + setupAccess.remove(); + } String world; if (builder.setupManager() == null) { world = PlotSquared.platform().getInjector().getInstance(SetupUtils.class).setupWorld(builder); diff --git a/Core/src/main/java/com/plotsquared/core/util/Permissions.java b/Core/src/main/java/com/plotsquared/core/util/Permissions.java index 34754e7c8..32dc6a747 100644 --- a/Core/src/main/java/com/plotsquared/core/util/Permissions.java +++ b/Core/src/main/java/com/plotsquared/core/util/Permissions.java @@ -28,9 +28,12 @@ package com.plotsquared.core.util; import com.plotsquared.core.command.CommandCaller; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import java.util.HashMap; +import java.util.Map; /** * The Permissions class handles checking user permissions.
@@ -65,19 +68,21 @@ public class Permissions { if (!Settings.Enabled_Components.PERMISSION_CACHE) { return hasPermission((CommandCaller) player, permission); } - HashMap map = player.getMeta("perm"); - if (map != null) { - Boolean result = map.get(permission); - if (result != null) { - return result; + try (final MetaDataAccess> mapAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_PERMISSIONS)) { + Map map = mapAccess.get().orElse(null); + if (map != null) { + final Boolean result = map.get(permission); + if (result != null) { + return result; + } + } else { + mapAccess.set((map = new HashMap<>())); } - } else { - map = new HashMap<>(); - player.setMeta("perm", map); + boolean result = hasPermission((CommandCaller) player, permission); + map.put(permission, result); + return result; } - boolean result = hasPermission((CommandCaller) player, permission); - map.put(permission, result); - return result; } /** diff --git a/Core/src/main/java/com/plotsquared/core/util/WEManager.java b/Core/src/main/java/com/plotsquared/core/util/WEManager.java index ea5d98ab8..ce065063d 100644 --- a/Core/src/main/java/com/plotsquared/core/util/WEManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/WEManager.java @@ -28,6 +28,8 @@ package com.plotsquared.core.util; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.location.Location; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -100,19 +102,22 @@ public class WEManager { } boolean allowMember = player.hasPermission("plots.worldedit.member"); Plot plot = player.getCurrentPlot(); - if (plot == null) { - plot = player.getMeta("WorldEditRegionPlot"); - } - if (plot != null && (!Settings.Done.RESTRICT_BUILDING || !DoneFlag.isDone(plot)) && ( - (allowMember && plot.isAdded(uuid)) || (!allowMember && (plot.isOwner(uuid)) || plot - .getTrusted().contains(uuid))) && !plot.getFlag(NoWorldeditFlag.class)) { - for (CuboidRegion region : plot.getRegions()) { - BlockVector3 pos1 = region.getMinimumPoint().withY(area.getMinBuildHeight()); - BlockVector3 pos2 = region.getMaximumPoint().withY(area.getMaxBuildHeight()); - CuboidRegion copy = new CuboidRegion(pos1, pos2); - regions.add(copy); + try (final MetaDataAccess metaDataAccess = + player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_WORLD_EDIT_REGION_PLOT)) { + if (plot == null) { + plot = metaDataAccess.get().orElse(null); + } + if (plot != null && (!Settings.Done.RESTRICT_BUILDING || !DoneFlag.isDone(plot)) && ( + (allowMember && plot.isAdded(uuid)) || (!allowMember && (plot.isOwner(uuid)) || plot + .getTrusted().contains(uuid))) && !plot.getFlag(NoWorldeditFlag.class)) { + for (CuboidRegion region : plot.getRegions()) { + BlockVector3 pos1 = region.getMinimumPoint().withY(area.getMinBuildHeight()); + BlockVector3 pos2 = region.getMaximumPoint().withY(area.getMaxBuildHeight()); + CuboidRegion copy = new CuboidRegion(pos1, pos2); + regions.add(copy); + } + metaDataAccess.set(plot); } - player.setMeta("WorldEditRegionPlot", plot); } return regions; } diff --git a/Core/src/main/java/com/plotsquared/core/util/task/AutoClaimFinishTask.java b/Core/src/main/java/com/plotsquared/core/util/task/AutoClaimFinishTask.java index cdcdee0e7..b4dc0a3b3 100644 --- a/Core/src/main/java/com/plotsquared/core/util/task/AutoClaimFinishTask.java +++ b/Core/src/main/java/com/plotsquared/core/util/task/AutoClaimFinishTask.java @@ -30,6 +30,8 @@ import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.events.PlotMergeEvent; import com.plotsquared.core.events.Result; import com.plotsquared.core.location.Direction; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -50,7 +52,10 @@ public final class AutoClaimFinishTask implements Callable { private final EventDispatcher eventDispatcher; @Override public Boolean call() { - player.deleteMeta(Auto.class.getName()); + try (final MetaDataAccess autoAccess + = player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_AUTO)) { + autoAccess.remove(); + } if (plot == null) { sendMessage(player, Captions.NO_FREE_PLOTS); return false; From 722361aedb0b363e3830367d8bd0ebccce271183 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Fri, 24 Jul 2020 12:15:07 +0200 Subject: [PATCH 22/25] Implement suggestions from PR comments --- .../com/plotsquared/core/command/Auto.java | 2 +- .../com/plotsquared/core/command/Claim.java | 2 +- .../core/player/MetaDataAccess.java | 31 +++++++++++++++++-- .../core/player/PersistentMetaDataAccess.java | 6 +++- .../core/player/TemporaryMetaDataAccess.java | 6 +++- .../core/plot/expiration/ExpireManager.java | 2 +- 6 files changed, 41 insertions(+), 8 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/command/Auto.java b/Core/src/main/java/com/plotsquared/core/command/Auto.java index 2cd105ffa..aadb763c8 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Auto.java +++ b/Core/src/main/java/com/plotsquared/core/command/Auto.java @@ -94,7 +94,7 @@ public class Auto extends SubCommand { if (diff - sizeX * sizeZ < 0) { try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData( PlayerMetaDataKeys.PERSISTENT_GRANTED_PLOTS)) { - if (metaDataAccess.has()) { + if (metaDataAccess.isPresent()) { int grantedPlots = metaDataAccess.get().orElse(0); if (diff < 0 && grantedPlots < sizeX * sizeZ) { MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); diff --git a/Core/src/main/java/com/plotsquared/core/command/Claim.java b/Core/src/main/java/com/plotsquared/core/command/Claim.java index fbbd25013..d2285e7ba 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Claim.java +++ b/Core/src/main/java/com/plotsquared/core/command/Claim.java @@ -92,7 +92,7 @@ public class Claim extends SubCommand { try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData(PlayerMetaDataKeys.PERSISTENT_GRANTED_PLOTS)) { int grants = 0; if (currentPlots >= player.getAllowedPlots() && !force) { - if (metaDataAccess.has()) { + if (metaDataAccess.isPresent()) { grants = metaDataAccess.get().orElse(0); if (grants <= 0) { metaDataAccess.remove(); diff --git a/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java b/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java index c38111b73..800f1c080 100644 --- a/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java +++ b/Core/src/main/java/com/plotsquared/core/player/MetaDataAccess.java @@ -34,7 +34,6 @@ import java.util.Optional; /** * Access to player meta data * - * @param

Player type * @param Meta data type */ public abstract class MetaDataAccess implements AutoCloseable { @@ -42,6 +41,7 @@ public abstract class MetaDataAccess implements AutoCloseable { private final PlotPlayer player; private final MetaDataKey metaDataKey; private final LockRepository.LockAccess lockAccess; + private boolean closed = false; MetaDataAccess(@Nonnull final PlotPlayer player, @Nonnull final MetaDataKey metaDataKey, @Nonnull final LockRepository.LockAccess lockAccess) { @@ -56,12 +56,12 @@ public abstract class MetaDataAccess implements AutoCloseable { * @return {@code true} if player has meta data with this key, or * {@code false} */ - public abstract boolean has(); + public abstract boolean isPresent(); /** * Remove the stored value meta data * - * @return Old value, or {@link null} + * @return Old value, or {@code null} */ @Nullable public abstract T remove(); @@ -81,6 +81,7 @@ public abstract class MetaDataAccess implements AutoCloseable { @Override public final void close() { this.lockAccess.close(); + this.closed = true; } /** @@ -101,4 +102,28 @@ public abstract class MetaDataAccess implements AutoCloseable { return this.metaDataKey; } + /** + * Check whether or not the meta data access has been closed. + * After being closed, all attempts to access the meta data + * through the instance, will lead to {@link IllegalAccessException} + * being thrown + * + * @return {@code true} if the access has been closed + */ + public boolean isClosed() { + return this.closed; + } + + protected void checkClosed() { + if (this.closed) { + sneakyThrow(new IllegalAccessException("The meta data access instance has been closed")); + } + } + + @SuppressWarnings("ALL") + private static void sneakyThrow(final Throwable e) throws E { + throw (E) e; + } + + } diff --git a/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java b/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java index e7bb67103..1e3767c7d 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java +++ b/Core/src/main/java/com/plotsquared/core/player/PersistentMetaDataAccess.java @@ -39,11 +39,13 @@ final class PersistentMetaDataAccess extends MetaDataAccess { super(player, metaDataKey, lockAccess); } - @Override public boolean has() { + @Override public boolean isPresent() { + this.checkClosed(); return this.getPlayer().hasPersistentMeta(getMetaDataKey().toString()); } @Override @Nullable public T remove() { + this.checkClosed(); final Object old = this.getPlayer().removePersistentMeta(this.getMetaDataKey().toString()); if (old == null) { return null; @@ -52,10 +54,12 @@ final class PersistentMetaDataAccess extends MetaDataAccess { } @Override public void set(@Nonnull T value) { + this.checkClosed(); this.getPlayer().setPersistentMeta(this.getMetaDataKey(), value); } @Nonnull @Override public Optional get() { + this.checkClosed(); return Optional.ofNullable(this.getPlayer().getPersistentMeta(this.getMetaDataKey())); } diff --git a/Core/src/main/java/com/plotsquared/core/player/TemporaryMetaDataAccess.java b/Core/src/main/java/com/plotsquared/core/player/TemporaryMetaDataAccess.java index b301f5be7..22c5dd631 100644 --- a/Core/src/main/java/com/plotsquared/core/player/TemporaryMetaDataAccess.java +++ b/Core/src/main/java/com/plotsquared/core/player/TemporaryMetaDataAccess.java @@ -39,11 +39,13 @@ final class TemporaryMetaDataAccess extends MetaDataAccess { super(player, metaDataKey, lockAccess); } - @Override public boolean has() { + @Override public boolean isPresent() { + this.checkClosed(); return this.getPlayer().getMeta(this.getMetaDataKey().toString()) != null; } @Override @Nullable public T remove() { + this.checkClosed(); final Object old = getPlayer().deleteMeta(this.getMetaDataKey().toString()); if (old == null) { return null; @@ -52,10 +54,12 @@ final class TemporaryMetaDataAccess extends MetaDataAccess { } @Override public void set(@Nonnull T value) { + this.checkClosed(); this.getPlayer().setMeta(this.getMetaDataKey().toString(), null); } @Nonnull @Override public Optional get() { + this.checkClosed(); return Optional.ofNullable(this.getPlayer().getMeta(this.getMetaDataKey().toString())); } diff --git a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java index 6b14d0866..e0fb65d26 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java @@ -142,7 +142,7 @@ public class ExpireManager { public void confirmExpiry(final PlotPlayer pp) { try (final MetaDataAccess metaDataAccess = pp.accessTemporaryMetaData( PlayerMetaDataKeys.TEMPORARY_IGNORE_EXPIRE_TASK)) { - if (metaDataAccess.has()) { + if (metaDataAccess.isPresent()) { return; } if (plotsToDelete != null && !plotsToDelete.isEmpty() && pp.hasPermission("plots.admin.command.autoclear")) { From c9c62a10830f5ac4d7ef5f26c9f69416f994f569 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Fri, 24 Jul 2020 12:44:04 +0200 Subject: [PATCH 23/25] Remove dumb permission mess. --- .../core/permissions/PermissionHolder.java | 2 +- .../plotsquared/core/util/Permissions.java | 81 +++---------------- .../plotsquared/core/util/PlayerManager.java | 2 +- 3 files changed, 15 insertions(+), 70 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java index abff13262..7f42c24f0 100644 --- a/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java +++ b/Core/src/main/java/com/plotsquared/core/permissions/PermissionHolder.java @@ -89,6 +89,6 @@ public interface PermissionHolder { * @param permission Permission * @return {@code true} if the owner has the given permission, else {@code false} */ - boolean hasPermission(@Nullable final String world, @Nonnull String permission); + boolean hasPermission(@Nullable String world, @Nonnull String permission); } diff --git a/Core/src/main/java/com/plotsquared/core/util/Permissions.java b/Core/src/main/java/com/plotsquared/core/util/Permissions.java index 24256da11..256dbb212 100644 --- a/Core/src/main/java/com/plotsquared/core/util/Permissions.java +++ b/Core/src/main/java/com/plotsquared/core/util/Permissions.java @@ -25,16 +25,13 @@ */ package com.plotsquared.core.util; -import com.plotsquared.core.command.CommandCaller; +import com.plotsquared.core.configuration.Caption; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Settings; -import com.plotsquared.core.player.MetaDataAccess; -import com.plotsquared.core.player.PlayerMetaDataKeys; -import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.permissions.PermissionHolder; +import com.plotsquared.core.player.PlotPlayer; -import java.util.HashMap; -import java.util.Map; +import javax.annotation.Nonnull; /** * The Permissions class handles checking user permissions.
@@ -48,75 +45,23 @@ public class Permissions { } /** - * Check if a player has a permission (Captions class helps keep track of permissions). + * Check if the owner of the profile has a given (global) permission * - * @param player - * @param caption - * @return + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} */ - public static boolean hasPermission(PlotPlayer player, Captions caption) { - return hasPermission(player, caption.getTranslated()); + public static boolean hasPermission(@Nonnull final PermissionHolder caller, @Nonnull final Caption permission) { + return caller.hasPermission(permission.getTranslated()); } /** - * Check if a {@link PlotPlayer} has a permission. + * Check if the owner of the profile has a given (global) permission * - * @param player - * @param permission - * @return + * @param permission Permission + * @return {@code true} if the owner has the given permission, else {@code false} */ - public static boolean hasPermission(PlotPlayer player, String permission) { - if (!Settings.Enabled_Components.PERMISSION_CACHE) { - return hasPermission((PermissionHolder) player, permission); - } - try (final MetaDataAccess> mapAccess = - player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_PERMISSIONS)) { - Map map = mapAccess.get().orElse(null); - if (map != null) { - final Boolean result = map.get(permission); - if (result != null) { - return result; - } - } else { - mapAccess.set((map = new HashMap<>())); - } - boolean result = hasPermission((PermissionHolder) player, permission); - map.put(permission, result); - return result; - } - } - - /** - * Check if a {@code CommandCaller} has a permission. - * - * @param caller - * @param permission - * @return - */ - public static boolean hasPermission(PermissionHolder caller, String permission) { - if (caller.hasPermission(permission)) { - return true; - }/* TODO: DECIDE WHAT TO DO HERE; else if (caller.isPermissionSet(permission)) { - return false; - }*/ - if (caller.hasPermission(Captions.PERMISSION_ADMIN.getTranslated())) { - return true; - } - permission = permission.toLowerCase().replaceAll("^[^a-z|0-9|\\.|_|-]", ""); - String[] nodes = permission.split("\\."); - StringBuilder n = new StringBuilder(); - for (int i = 0; i <= (nodes.length - 1); i++) { - n.append(nodes[i] + "."); - String combined = n + Captions.PERMISSION_STAR.getTranslated(); - if (!permission.equals(combined)) { - if (caller.hasPermission(combined)) { - return true; - }/* TODO: DECIDE WHAT TO DO HERE; else if (caller.isPermissionSet(combined)) { - return false; - }*/ - } - } - return false; + public static boolean hasPermission(@Nonnull final PermissionHolder caller, @Nonnull final String permission) { + return caller.hasPermission(permission); } /** diff --git a/Core/src/main/java/com/plotsquared/core/util/PlayerManager.java b/Core/src/main/java/com/plotsquared/core/util/PlayerManager.java index e316d6c19..cfe666569 100644 --- a/Core/src/main/java/com/plotsquared/core/util/PlayerManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/PlayerManager.java @@ -239,7 +239,7 @@ public abstract class PlayerManager

, T> { /** * Get a plot player from a platform player object. This method requires - * that the caller actually knows that the player exists. + * that the caller actually knows that the player exists and is online. *

* The method will throw an exception if there is no such * player online. From fe7a57b2b7a40ede27fb08525ce65d1666599723 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Fri, 24 Jul 2020 12:48:45 +0200 Subject: [PATCH 24/25] Remove mainutil cache workaround --- .../com/plotsquared/core/util/MainUtil.java | 47 ------------------- 1 file changed, 47 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/util/MainUtil.java b/Core/src/main/java/com/plotsquared/core/util/MainUtil.java index 010622813..2a96b7120 100644 --- a/Core/src/main/java/com/plotsquared/core/util/MainUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/MainUtil.java @@ -44,53 +44,6 @@ import javax.annotation.Nonnull; private static final Logger logger = LoggerFactory.getLogger("P2/" + MainUtil.class.getSimpleName()); - /** - * Cache of mapping x,y,z coordinates to the chunk array
- * - Used for efficient world generation
- */ - public static short[][] x_loc; - public static short[][] y_loc; - public static short[][] z_loc; - public static short[][][] CACHE_I = null; - public static short[][][] CACHE_J = null; - - /** - * This cache is used for world generation and just saves a bit of calculation time when checking if something is in the plot area. - */ - public static void initCache() { - if (x_loc == null) { - x_loc = new short[16][4096]; - y_loc = new short[16][4096]; - z_loc = new short[16][4096]; - for (int i = 0; i < 16; i++) { - int i4 = i << 4; - for (int j = 0; j < 4096; j++) { - int y = i4 + (j >> 8); - int a = j - ((y & 0xF) << 8); - int z1 = a >> 4; - int x1 = a - (z1 << 4); - x_loc[i][j] = (short) x1; - y_loc[i][j] = (short) y; - z_loc[i][j] = (short) z1; - } - } - } - if (CACHE_I == null) { - CACHE_I = new short[256][16][16]; - CACHE_J = new short[256][16][16]; - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - for (int y = 0; y < 256; y++) { - short i = (short) (y >> 4); - short j = (short) ((y & 0xF) << 8 | z << 4 | x); - CACHE_I[y][x][z] = i; - CACHE_J[y][x][z] = j; - } - } - } - } - } - /** * Send a message to the player. * From dc1f669a1f189810dd055545a18a8c961702101e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Fri, 24 Jul 2020 13:01:38 +0200 Subject: [PATCH 25/25] Remove permission caching --- .../java/com/plotsquared/bukkit/listener/PlayerEvents.java | 7 ------- .../java/com/plotsquared/core/command/MainCommand.java | 7 ------- .../com/plotsquared/core/player/PlayerMetaDataKeys.java | 2 -- 3 files changed, 16 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java index e07a1ce28..0e783067c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java @@ -225,7 +225,6 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; @@ -1203,12 +1202,6 @@ import java.util.regex.Pattern; } } } - if (Settings.Enabled_Components.PERMISSION_CACHE) { - try (final MetaDataAccess> metaDataAccess = - pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_PERMISSIONS)) { - metaDataAccess.remove(); - } - } Location location = pp.getLocation(); PlotArea area = location.getPlotArea(); if (location.isPlotArea()) { diff --git a/Core/src/main/java/com/plotsquared/core/command/MainCommand.java b/Core/src/main/java/com/plotsquared/core/command/MainCommand.java index cfe608599..641047389 100644 --- a/Core/src/main/java/com/plotsquared/core/command/MainCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/MainCommand.java @@ -45,7 +45,6 @@ import com.plotsquared.core.util.task.RunnableVal3; import java.util.Arrays; import java.util.LinkedList; import java.util.List; -import java.util.Map; import java.util.concurrent.CompletableFuture; /** @@ -233,12 +232,6 @@ public class MainCommand extends Command { public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { - // Clear perm caching // - try (final MetaDataAccess> permAccess = player.accessTemporaryMetaData( - PlayerMetaDataKeys.TEMPORARY_PERMISSIONS)) { - permAccess.remove(); - } - // Optional command scope // Location location = null; Plot plot = null; diff --git a/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java b/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java index d1cf087d9..d45e0aa60 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlayerMetaDataKeys.java @@ -34,7 +34,6 @@ import com.plotsquared.core.plot.PlotInventory; import com.plotsquared.core.setup.SetupProcess; import java.util.List; -import java.util.Map; public final class PlayerMetaDataKeys { @@ -50,7 +49,6 @@ public final class PlayerMetaDataKeys { public static final MetaDataKey TEMPORARY_IGNORE_EXPIRE_TASK = MetaDataKey.of("ignoreExpireTask", new TypeLiteral() {}); public static final MetaDataKey TEMPORARY_WORLD_EDIT_REGION_PLOT = MetaDataKey.of("WorldEditRegionPlot", new TypeLiteral() {}); public static final MetaDataKey TEMPORARY_AUTO = MetaDataKey.of(Auto.class.getName(), new TypeLiteral() {}); - public static final MetaDataKey> TEMPORARY_PERMISSIONS = MetaDataKey.of("permissions", new TypeLiteral>() {}); public static final MetaDataKey> TEMPORARY_SCHEMATICS = MetaDataKey.of("plot_schematics", new TypeLiteral>() {}); public static final MetaDataKey TEMPORARY_LOCATION = MetaDataKey.of("location", new TypeLiteral() {}); public static final MetaDataKey TEMPORARY_CONFIRM = MetaDataKey.of("cmdConfirm", new TypeLiteral() {});