♻️ Refactor of the folders and fixed shutdown task register

This commit is contained in:
stijnb1234 2022-06-10 20:36:08 +02:00
parent d6149955b3
commit ca0d2dcd6d
41 changed files with 213 additions and 115 deletions

View file

@ -0,0 +1,152 @@
package nl.SBDeveloper.V10Lift;
import nl.SBDeveloper.V10Lift.api.V10LiftAPI;
import nl.SBDeveloper.V10Lift.commands.V10LiftCommand;
import nl.SBDeveloper.V10Lift.commands.V10LiftTabCompleter;
import nl.SBDeveloper.V10Lift.listeners.BlockBreakListener;
import nl.SBDeveloper.V10Lift.listeners.EntityDamageListener;
import nl.SBDeveloper.V10Lift.listeners.PlayerInteractListener;
import nl.SBDeveloper.V10Lift.listeners.SignChangeListener;
import nl.SBDeveloper.V10Lift.managers.DBManager;
import nl.SBDeveloper.V10Lift.managers.DataManager;
import nl.SBDeveloper.V10Lift.managers.VaultManager;
import nl.SBDeveloper.V10Lift.sbutils.ConfigUpdater;
import nl.SBDeveloper.V10Lift.sbutils.UpdateManager;
import nl.SBDeveloper.V10Lift.sbutils.YamlFile;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.SingleLineChart;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collections;
public class V10LiftPlugin extends JavaPlugin {
private static V10LiftPlugin instance;
private static YamlFile config;
private static DBManager dbManager;
private static YamlFile messages;
private static boolean vault = false;
@Override
public void onEnable() {
instance = this;
//Load the config
config = new YamlFile("config");
config.loadDefaults();
//And update config
try {
ConfigUpdater.update(this, "config.yml", config.getJavaFile(), Collections.emptyList());
} catch (IOException e) {
Bukkit.getLogger().warning("[V10Lift] Couldn't update the config.yml. Please check the stacktrace below.");
e.printStackTrace();
}
//Load the messages
messages = new YamlFile("messages");
messages.loadDefaults();
//Load the database
dbManager = new DBManager("data");
try {
dbManager.load();
} catch (SQLException e) {
Bukkit.getLogger().warning("[V10Lift] Couldn't connect to the SQLite database. Please check the stacktrace below.");
e.printStackTrace();
}
//Load vault if found
if (VaultManager.setupPermissions()) {
Bukkit.getLogger().info("[V10Lift] Loading Vault hook for group whitelist support.");
vault = true;
}
//Load the command
getCommand("v10lift").setExecutor(new V10LiftCommand());
getCommand("v10lift").setTabCompleter(new V10LiftTabCompleter());
//Register the listeners
Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(), this);
Bukkit.getPluginManager().registerEvents(new BlockBreakListener(), this);
Bukkit.getPluginManager().registerEvents(new SignChangeListener(), this);
Bukkit.getPluginManager().registerEvents(new EntityDamageListener(), this);
//Load metrics
Bukkit.getLogger().info("[V10Lift] Loading metrics. Can be disabled in the global bStats config.");
Metrics metrics = new Metrics(this, 6564);
metrics.addCustomChart(new SingleLineChart("lifts", () -> DataManager.getLifts().size()));
//Load the update checker
if (getSConfig().getFile().getBoolean("UpdateChecker.Enabled")) {
UpdateManager updateManager = new UpdateManager(this, 72317);
updateManager.handleResponse((versionResponse, version) -> {
switch (versionResponse) {
case FOUND_NEW:
Bukkit.getLogger().warning("[V10Lift] There is a new version available! Current: " + this.getDescription().getVersion() + " New: " + version.get());
if (getSConfig().getFile().getBoolean("UpdateChecker.DownloadOnUpdate")) {
Bukkit.getLogger().info("[V10Lift] Trying to download the update. This could take some time...");
updateManager.handleDownloadResponse((downloadResponse, fileName) -> {
switch (downloadResponse) {
case DONE:
Bukkit.getLogger().info("[V10Lift] Update downloaded! If you restart your server, it will be loaded. Filename: " + fileName);
break;
case ERROR:
Bukkit.getLogger().severe("[V10Lift] Something went wrong when trying downloading the latest version.");
break;
case UNAVAILABLE:
Bukkit.getLogger().warning("[V10Lift] Unable to download the latest version.");
break;
}
}).runUpdate();
}
break;
case LATEST:
Bukkit.getLogger().info("[V10Lift] You are running the latest version [" + this.getDescription().getVersion() + "]!");
break;
case THIS_NEWER:
Bukkit.getLogger().info("[V10Lift] You are running a newer version [" + this.getDescription().getVersion() + "]! This is probably fine.");
break;
case UNAVAILABLE:
Bukkit.getLogger().severe("[V10Lift] Unable to perform an update check.");
break;
}
}).check();
}
Bukkit.getLogger().info("[V10Lift] Plugin loaded successfully!");
}
@Override
public void onDisable() {
dbManager.save(true);
dbManager.closeConnection();
instance = null;
}
public static V10LiftPlugin getInstance() {
return instance;
}
public static YamlFile getSConfig() {
return config;
}
public static DBManager getDBManager() {
return dbManager;
}
public static YamlFile getMessages() {
return messages;
}
public static boolean isVaultEnabled() {
return vault;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,5 @@
package nl.SBDeveloper.V10Lift.api.enums;
public enum LiftDirection {
UP, DOWN, STOP
}

View file

@ -0,0 +1,4 @@
/**
* All the enums used for V10Lift
*/
package nl.SBDeveloper.V10Lift.api.enums;

View file

@ -0,0 +1,53 @@
package nl.SBDeveloper.V10Lift.api.objects;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.UUID;
/** A floor object, for a floor in the lift. */
@Getter @Setter @NoArgsConstructor @ToString
public class Floor {
private String world;
private int y;
private ArrayList<LiftBlock> doorBlocks = new ArrayList<>();
private ArrayList<LiftBlock> realDoorBlocks = new ArrayList<>();
private HashSet<UUID> userWhitelist = new HashSet<>();
private HashSet<String> groupWhitelist = new HashSet<>();
/**
* Construct a new Floor
*
* @param y The y/height of the floor
* @param world The world of the floor
*/
public Floor(int y, String world) {
this.y = y;
this.world = world;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Floor floor = (Floor) o;
if (world == null) {
if (floor.getWorld() != null) return false;
} else if (!world.equals(floor.getWorld())) return false;
return y == floor.getY();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((world == null) ? 0 : world.hashCode());
result = prime * result + y;
return result;
}
}

View file

@ -0,0 +1,62 @@
package nl.SBDeveloper.V10Lift.api.objects;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import nl.SBDeveloper.V10Lift.api.runnables.DoorCloser;
import java.util.*;
/** A lift object, to create a lift. */
@NoArgsConstructor @ToString
public class Lift {
@Getter @Setter private String worldName;
@Getter @Setter private int y;
@Getter private HashSet<UUID> owners;
@Getter private final TreeSet<LiftBlock> blocks = new TreeSet<>();
@Getter private final LinkedHashMap<String, Floor> floors = new LinkedHashMap<>();
@Getter private final HashSet<LiftSign> signs = new HashSet<>();
@Getter private final HashSet<LiftBlock> inputs = new HashSet<>();
@Getter private final HashSet<LiftBlock> offlineInputs = new HashSet<>();
@Getter @Setter private LinkedHashMap<String, Floor> queue = null;
@Getter private final HashSet<LiftRope> ropes = new HashSet<>();
@Getter private transient final ArrayList<V10Entity> toMove = new ArrayList<>();
@Getter @Setter private int speed;
@Getter @Setter private boolean realistic;
@Getter @Setter private boolean offline = false;
@Getter @Setter private boolean sound = true;
@Getter @Setter private boolean defective = false;
@Getter @Setter private String signText = null;
@Getter @Setter private int counter = 0;
@Getter @Setter private Floor doorOpen = null;
@Getter @Setter private DoorCloser doorCloser = null;
/**
* Construct a new Lift with multiple owners
*
* @param owners The owners, by uuid
* @param speed The speed, 1 is slowest, higher is faster
* @param realistic Realistic lift, or not
*/
public Lift(HashSet<UUID> owners, int speed, boolean realistic) {
this.owners = owners;
this.speed = speed;
this.realistic = realistic;
}
/**
* Construct a new Lift with one owners
*
* @param owner The owner, by uuid
* @param speed The speed, 1 is slowest, higher is faster
* @param realistic Realistic lift, or not
*/
public Lift(UUID owner, int speed, boolean realistic) {
HashSet<UUID> hs = new HashSet<>();
hs.add(owner);
this.owners = hs;
this.speed = speed;
this.realistic = realistic;
}
}

View file

@ -0,0 +1,285 @@
package nl.SBDeveloper.V10Lift.api.objects;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.Map;
/** A liftblock object, for a block in a lift. */
@NoArgsConstructor
public class LiftBlock implements Comparable<LiftBlock> {
@Getter @Setter private String world;
@Getter private int x;
@Getter @Setter private int y;
@Getter private int z;
//Only used for cabine blocks, because those need caching!
@Getter @Setter private Material mat;
@Getter private byte data;
@Getter private BlockFace face;
@Getter private String bisected;
@Getter private String slabtype;
@Getter private String[] signLines;
//Only used for inputs!
@Getter private String floor;
@Getter @Setter private boolean active = false;
//Only used for chests
public Map<String, Object>[] serializedItemStacks = null;
/**
* A floor based liftblock, without material (no caching)
*
* @param world The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param floor The floorname of the block
*/
public LiftBlock(String world, int x, int y, int z, String floor) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.mat = null;
this.data = 0;
this.face = null;
this.signLines = null;
this.floor = floor;
this.bisected = null;
this.slabtype = null;
}
/**
* 1.12 liftblock, with material and data [NO SIGN]
*
* @param world The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param mat The Material of the block
* @param data The data of the block
*/
public LiftBlock(String world, int x, int y, int z, Material mat, byte data) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.mat = mat;
this.face = null;
this.data = data;
this.signLines = null;
this.floor = null;
this.bisected = null;
this.slabtype = null;
}
/**
* 1.12 liftblock (signs)
*
* @param world The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param mat The Material of the block
* @param data The data of the block
* @param signLines The lines of the sign
*/
public LiftBlock(String world, int x, int y, int z, Material mat, byte data, String[] signLines) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.mat = mat;
this.face = null;
this.data = data;
this.signLines = signLines;
this.floor = null;
this.bisected = null;
this.slabtype = null;
}
/**
* 1.13 liftblock, without a direction
*
* @param world The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param mat The Material of the block
*/
public LiftBlock(String world, int x, int y, int z, Material mat) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.mat = mat;
this.face = null;
this.data = 0;
this.signLines = null;
this.floor = null;
this.bisected = null;
this.slabtype = null;
}
/**
* 1.13 liftblock with a direction
*
* @param world The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param mat The Material of the block
* @param face The blockface of the block
*/
public LiftBlock(String world, int x, int y, int z, Material mat, BlockFace face) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.mat = mat;
this.face = face;
this.data = 0;
this.signLines = null;
this.floor = null;
this.bisected = null;
this.slabtype = null;
}
/**
* 1.13 liftblock, with a direction and a bisected
*
* @param world The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param mat The Material of the block
* @param face The blockface of the block
* @param bisected The bisected of the block
*/
public LiftBlock(String world, int x, int y, int z, Material mat, BlockFace face, String bisected) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.mat = mat;
this.face = face;
this.data = 0;
this.signLines = null;
this.floor = null;
this.bisected = bisected;
this.slabtype = null;
}
/**
* 1/13 liftblock (sign)
*
* @param world The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param mat The Material of the block
* @param face The blockface of the block
* @param signLines The lines of the sign
*/
public LiftBlock(String world, int x, int y, int z, Material mat, BlockFace face, String[] signLines) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.mat = mat;
this.face = face;
this.data = 0;
this.signLines = signLines;
this.floor = null;
this.bisected = null;
this.slabtype = null;
}
/**
* 1.13 liftblock (slab)
*
* @param world The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param mat The Material of the block
* @param slabtype The typ of slab (low, high, double)
*/
public LiftBlock(String world, int x, int y, int z, Material mat, String slabtype) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.mat = mat;
this.face = null;
this.data = 0;
this.signLines = null;
this.floor = null;
this.bisected = null;
this.slabtype = slabtype;
}
@Override
public int compareTo(@Nonnull LiftBlock lb) {
int ret = Integer.compare(y, lb.y);
if (ret == 0) ret = Integer.compare(x, lb.x);
if (ret == 0) ret = Integer.compare(z, lb.z);
return ret;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LiftBlock)) {
if (!(o instanceof LiftSign)) return false;
LiftSign other = (LiftSign) o;
return world.equals(other.getWorld()) &&
x == other.getX() &&
y == other.getY() &&
z == other.getZ();
}
LiftBlock other = (LiftBlock) o;
return world.equals(other.world) &&
x == other.x &&
y == other.y &&
z == other.z;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((world == null) ? 0 : world.hashCode());
result = prime * result + x;
result = prime * result + y;
result = prime * result + z;
return result;
}
@Override
public String toString() {
return "LiftBlock{" +
"world='" + world + '\'' +
", x=" + x +
", y=" + y +
", z=" + z +
", mat=" + mat +
", data=" + data +
", face=" + face +
", bisected='" + bisected + '\'' +
", signLines=" + Arrays.toString(signLines) +
", floor='" + floor + '\'' +
", active=" + active +
", serializedItemStacks=" + Arrays.toString(serializedItemStacks) +
'}';
}
}

View file

@ -0,0 +1,82 @@
package nl.SBDeveloper.V10Lift.api.objects;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import java.util.Objects;
/** A liftrope object, for a rope in the lift. */
@Getter @Setter @NoArgsConstructor
public class LiftRope {
private Material type;
private BlockFace face;
private String world;
private int x;
private int minY;
private int maxY;
private int z;
private int currently;
/**
* Construct a new liftrope
*
* @param type The material of the rope
* @param face The face of the rope
* @param world The world
* @param x The x-pos
* @param minY The starting x-pos
* @param maxY The stopping x-pos
* @param z The z-pos
*/
public LiftRope(Material type, BlockFace face, String world, int x, int minY, int maxY, int z) {
this.type = type;
this.face = face;
this.world = world;
this.x = x;
this.minY = minY;
this.maxY = maxY;
this.z = z;
this.currently = minY;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LiftRope liftRope = (LiftRope) o;
return x == liftRope.x &&
minY == liftRope.minY &&
maxY == liftRope.maxY &&
z == liftRope.z &&
Objects.equals(world, liftRope.world);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + world.hashCode();
result = prime * result + x;
result = prime * result + minY;
result = prime * result + maxY;
result = prime * result + z;
return result;
}
@Override
public String toString() {
return "LiftRope{" +
"type=" + type +
", face=" + face +
", world='" + world + '\'' +
", x=" + x +
", minY=" + minY +
", maxY=" + maxY +
", z=" + z +
", currently=" + currently +
'}';
}
}

View file

@ -0,0 +1,79 @@
package nl.SBDeveloper.V10Lift.api.objects;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/** A liftsign object, for a info sign for the lift. */
@Getter @Setter @NoArgsConstructor
public class LiftSign {
private String world;
private int x;
private int z;
private int y;
private String oldText = null;
private byte type;
private byte state;
/**
* Construct a new liftsign
*
* @param world The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param type The type of the sign
* @param state The state of the sign
*/
public LiftSign(String world, int x, int y, int z, byte type, byte state) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.type = type;
this.state = state;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LiftSign)) {
if (!(o instanceof LiftBlock))
return false;
LiftBlock other = (LiftBlock) o;
return world.equals(other.getWorld()) &&
x == other.getX() &&
y == other.getY() &&
z == other.getZ();
}
LiftSign other = (LiftSign) o;
return world.equals(other.world) &&
x == other.x &&
y == other.y &&
z == other.z;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((world == null) ? 0 : world.hashCode());
result = prime * result + x;
result = prime * result + y;
result = prime * result + z;
return result;
}
@Override
public String toString() {
return "LiftSign{" +
"world='" + world + '\'' +
", x=" + x +
", z=" + z +
", y=" + y +
", oldText='" + oldText + '\'' +
", type=" + type +
", state=" + state +
'}';
}
}

View file

@ -0,0 +1,109 @@
package nl.SBDeveloper.V10Lift.api.objects;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import java.util.UUID;
/** A v10entity object, for a entity in the lift. */
@Getter @NoArgsConstructor
public class V10Entity {
private UUID entityUUID;
private String world;
private int locX;
private int locY;
private int locZ;
private int y;
@Setter private short step;
/**
* Construct a new V10LiftEntity
*
* @param entityUUID The UUID of the entity
* @param worldName The world
* @param x The x-pos
* @param y The y-pos
* @param z The z-pos
* @param cury The current y-pos
*/
public V10Entity(UUID entityUUID, String worldName, int x, int y, int z, int cury) {
this.entityUUID = entityUUID;
this.world = worldName;
this.locX = x;
this.locY = y;
this.locZ = z;
this.y = cury;
this.step = 0;
}
/**
* Move a entity up
*/
public void moveUp() {
if (entityUUID == null) return;
Entity entity = Bukkit.getEntity(entityUUID);
if (entity == null || entity.isDead()) return;
locY = y + step;
entity.teleport(new Location(Bukkit.getWorld(world), locX, locY, locZ));
}
/**
* Move a entity down
*/
public void moveDown() {
if (entityUUID == null) return;
Entity entity = Bukkit.getEntity(entityUUID);
if (entity == null || entity.isDead()) return;
locY = y - step;
entity.teleport(new Location(Bukkit.getWorld(world), locX, locY, locZ));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
UUID uuid;
if (o instanceof V10Entity) {
Entity ent = Bukkit.getEntity(((V10Entity) o).getEntityUUID());
if (ent == null || ent.isDead()) {
Entity e = Bukkit.getEntity(entityUUID);
return e == null || e.isDead();
}
uuid = ent.getUniqueId();
} else if (o instanceof Entity) {
Entity ent = (Entity) o;
if (ent.isDead()) {
Entity e = Bukkit.getEntity(entityUUID);
return e == null || e.isDead();
}
uuid = ((Entity) o).getUniqueId();
} else
return false;
Entity e = Bukkit.getEntity(entityUUID);
if (e == null || e.isDead())
return false;
return uuid == e.getUniqueId();
}
@Override
public int hashCode() {
return 31 + ((entityUUID == null) ? 0 : entityUUID.hashCode());
}
@Override
public String toString() {
return "V10Entity{" +
"entityUUID=" + entityUUID +
", world='" + world + '\'' +
", locX=" + locX +
", locY=" + locY +
", locZ=" + locZ +
", y=" + y +
", step=" + step +
'}';
}
}

View file

@ -0,0 +1,4 @@
/**
* All the objects used for V10Lift
*/
package nl.SBDeveloper.V10Lift.api.objects;

View file

@ -0,0 +1,4 @@
/**
* The main API package
*/
package nl.SBDeveloper.V10Lift.api;

View file

@ -0,0 +1,29 @@
package nl.SBDeveloper.V10Lift.api.runnables;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import nl.SBDeveloper.V10Lift.api.V10LiftAPI;
import nl.SBDeveloper.V10Lift.managers.DataManager;
import org.bukkit.Bukkit;
/** The DoorCloser runnable, used for checking if the door can be closed. */
public class DoorCloser implements Runnable {
private final String liftName;
private final int taskID;
public DoorCloser(String liftName) {
this.liftName = liftName;
final long doorCloseTime = V10LiftPlugin.getSConfig().getFile().getLong("DoorCloseTime");
this.taskID = Bukkit.getScheduler().runTaskTimer(V10LiftPlugin.getInstance(), this, doorCloseTime, doorCloseTime).getTaskId();
}
@Override
public void run() {
if (V10LiftAPI.getInstance().closeDoor(liftName)) stop();
}
public void stop() {
Bukkit.getScheduler().cancelTask(taskID);
if (DataManager.containsLift(liftName)) DataManager.getLift(liftName).setDoorCloser(null);
}
}

View file

@ -0,0 +1,436 @@
package nl.SBDeveloper.V10Lift.api.runnables;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import nl.SBDeveloper.V10Lift.api.V10LiftAPI;
import nl.SBDeveloper.V10Lift.api.enums.LiftDirection;
import nl.SBDeveloper.V10Lift.api.objects.*;
import nl.SBDeveloper.V10Lift.managers.AntiCopyBlockManager;
import nl.SBDeveloper.V10Lift.managers.DataManager;
import nl.SBDeveloper.V10Lift.sbutils.LocationSerializer;
import nl.SBDeveloper.V10Lift.utils.ConfigUtil;
import nl.SBDeveloper.V10Lift.utils.DirectionUtil;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Chest;
import org.bukkit.block.Sign;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
/** The MoveLift runnable, used for moving a lift. */
public class MoveLift implements Runnable {
/* Packet teleportation method */
private final Method[] methods = ((Supplier<Method[]>) () -> {
try {
Method getHandle = Class.forName(Bukkit.getServer().getClass().getPackage().getName() + ".entity.CraftEntity").getDeclaredMethod("getHandle");
return new Method[] {
getHandle, getHandle.getReturnType().getDeclaredMethod("setPositionRotation", double.class, double.class, double.class, float.class, float.class)
};
} catch (Exception ex) {
return null;
}
}).get();
private final String liftName;
private final int ft;
public MoveLift(String liftName, long speed) {
this.liftName = liftName;
if (speed > 32L) {
ft = 1;
} else if (speed > 16L) {
ft = 2;
} else if (speed > 8L) {
ft = 4;
} else if (speed > 4L) {
ft = 8;
} else if (speed > 2L) {
ft = 16;
} else if (speed > 1L) {
ft = 32;
} else {
ft = 64;
}
}
@Override
public void run() {
//Check if lift exists
Lift lift = DataManager.getLift(liftName);
if (lift == null) {
stop();
return;
}
//If the queue is NOT empty and the lift is NOT offline
if (lift.getQueue().isEmpty() || lift.isOffline()) {
lift.setQueue(null);
stop();
return;
}
//If the lift is NOT in edit mode and the lift is NOT defective
if (DataManager.containsEditLift(liftName) || lift.isDefective()) return;
//If the lift is NOT in delay
if (lift.getCounter() > 0) {
lift.setCounter(lift.getCounter() - 1);
return;
}
//Check if the chunk of the first block is loaded
LiftBlock lb = lift.getBlocks().first();
World world = Bukkit.getWorld(lb.getWorld());
if (world == null) {
lift.setCounter(ft);
return;
}
Location loc = new Location(world, lb.getX(), lb.getY(), lb.getZ());
if (!loc.getChunk().isLoaded()) {
lift.setCounter(ft);
return;
}
//And if the chunk of the last block is loaded
lb = lift.getBlocks().last();
world = Bukkit.getWorld(lb.getWorld());
if (world == null) {
lift.setCounter(ft);
return;
}
loc = new Location(world, lb.getX(), lb.getY(), lb.getZ());
if (!loc.getChunk().isLoaded()) {
lift.setCounter(ft);
return;
}
//Handle malfunction
double changeOfDefect = V10LiftPlugin.getSConfig().getFile().getDouble("DefectRate");
if (changeOfDefect > 0.0D) {
double chance = ThreadLocalRandom.current().nextDouble(100);
if (chance < changeOfDefect) {
V10LiftAPI.getInstance().setDefective(liftName, true);
return;
}
}
Iterator<Map.Entry<String, Floor>> queueIterator = lift.getQueue().entrySet().iterator();
Map.Entry<String, Floor> floor = queueIterator.next();
String floorName = floor.getKey();
Floor floorTo = floor.getValue();
LiftDirection direction;
if (lift.getY() < floorTo.getY()) {
direction = LiftDirection.UP;
} else if (lift.getY() > floorTo.getY()) {
direction = LiftDirection.DOWN;
} else {
direction = LiftDirection.STOP;
}
List<LiftBlock> antiCopyBlocks = new ArrayList<>();
if (direction == LiftDirection.UP || direction == LiftDirection.DOWN) {
if (!V10LiftAPI.getInstance().closeDoor(liftName)) return;
if (direction == LiftDirection.UP) {
//MOVE ROPES
for (LiftRope rope : lift.getRopes()) {
if (rope.getCurrently() > rope.getMaxY()) {
Bukkit.getLogger().info("[V10Lift] Lift " + liftName + " reaches the upper rope end but won't stop!!");
V10LiftAPI.getInstance().setDefective(liftName, true);
lift.getToMove().clear();
queueIterator.remove();
return;
}
Block currentRopeBlock = Bukkit.getWorld(rope.getWorld()).getBlockAt(rope.getX(), rope.getCurrently(), rope.getZ());
currentRopeBlock.setType(Material.AIR);
rope.setCurrently(rope.getCurrently() + 1);
}
}
Iterator<LiftBlock> blockIterator = lift.getBlocks().iterator();
while (blockIterator.hasNext()) {
LiftBlock liftBlock = blockIterator.next();
if (AntiCopyBlockManager.isAntiCopy(liftBlock.getMat())) {
antiCopyBlocks.add(liftBlock);
blockIterator.remove();
Block antiCopyBlock = Bukkit.getWorld(liftBlock.getWorld()).getBlockAt(liftBlock.getX(), liftBlock.getY(), liftBlock.getZ());
antiCopyBlock.setType(Material.AIR);
liftBlock.setY(direction == LiftDirection.UP ? liftBlock.getY() + 1 : liftBlock.getY() - 1);
}
}
Set<LiftBlock> set = direction == LiftDirection.UP ? lift.getBlocks().descendingSet() : lift.getBlocks();
for (LiftBlock lib : set) {
Block block = Bukkit.getWorld(lib.getWorld()).getBlockAt(lib.getX(), lib.getY(), lib.getZ());
if ((lib.getMat() == Material.CHEST || lib.getMat() == Material.TRAPPED_CHEST) && lib.serializedItemStacks == null) {
Chest c = (Chest) block.getState();
Inventory inv = c.getInventory();
ItemStack[] invContents = inv.getContents();
boolean by = false;
lib.serializedItemStacks = new Map[invContents.length];
for (int i = 0; i < invContents.length; i++) {
ItemStack is = invContents[i];
if (is != null) {
by = true;
lib.serializedItemStacks[i] = is.serialize();
}
}
if (by) {
inv.clear();
c.update();
} else {
lib.serializedItemStacks = null;
}
}
block.setType(Material.AIR);
lib.setY(direction == LiftDirection.UP ? lib.getY() + 1 : lib.getY() - 1);
Block nextBlock = Bukkit.getWorld(lib.getWorld()).getBlockAt(lib.getX(), lib.getY(), lib.getZ());
if (lib.getMat() == null) lib.setMat(Material.AIR);
BlockState state = nextBlock.getState();
state.setType(lib.getMat());
if (!XMaterial.isNewVersion()) {
state.setRawData(lib.getData());
}
state.update(true);
if (XMaterial.isNewVersion()) {
DirectionUtil.setDirection(nextBlock, lib.getFace());
DirectionUtil.setBisected(nextBlock, lib.getBisected());
DirectionUtil.setSlabType(nextBlock, lib.getSlabtype());
}
if (direction == LiftDirection.UP) { //Teleportation is only required if we go up, for down gravity works fine. ;)
for (Entity ent : nextBlock.getChunk().getEntities()) {
V10Entity v10ent = new V10Entity(ent.getUniqueId(), null, 0, 0, 0, 0);
if (lift.getToMove().contains(v10ent)) continue;
Location entLoc = ent.getLocation();
if ((entLoc.getBlockY() == lib.getY() || entLoc.getBlockY() + 1 == lib.getY()) && entLoc.getBlockX() == lib.getX() && entLoc.getBlockZ() == lib.getZ()) {
entLoc.setY(entLoc.getY() + 1);
if (V10LiftPlugin.getSConfig().getFile().getBoolean("PacketTeleport")) {
try {
methods[1].invoke(methods[0].invoke(ent), entLoc.getX(), entLoc.getY(), entLoc.getZ(), entLoc.getYaw(), entLoc.getPitch());
} catch (Exception ex) {
Bukkit.getLogger().severe("[V10Lift] PacketTeleportation is enabled, but couldn't get the method.");
}
} else {
ent.teleport(entLoc);
}
}
}
}
}
Iterator<V10Entity> toMoveIterator = lift.getToMove().iterator();
while (toMoveIterator.hasNext()) {
V10Entity v10ent = toMoveIterator.next();
if (v10ent.getStep() > 0) {
if (direction == LiftDirection.UP) v10ent.moveUp(); else v10ent.moveDown();
if (v10ent.getStep() > 16) {
toMoveIterator.remove();
}
}
v10ent.setStep((short) (v10ent.getStep() + 1));
}
for (LiftBlock lib : antiCopyBlocks) {
Block block = Bukkit.getWorld(lib.getWorld()).getBlockAt(lib.getX(), lib.getY(), lib.getZ());
if (lib.getMat() == null) lib.setMat(Material.AIR);
BlockState state = block.getState();
state.setType(lib.getMat());
if (!XMaterial.isNewVersion()) {
state.setRawData(lib.getData());
}
state.update(true);
if (XMaterial.isNewVersion()) {
DirectionUtil.setDirection(block, lib.getFace());
DirectionUtil.setBisected(block, lib.getBisected());
DirectionUtil.setSlabType(block, lib.getSlabtype());
}
lift.getBlocks().add(lib);
if (lib.getSignLines() != null) {
BlockState bs = block.getState();
if (bs instanceof Sign) {
Sign sign = (Sign) bs;
for (int i = 0; i < 3; i++) {
sign.setLine(i, lib.getSignLines()[i]);
if (i == 0 && lib.getSignLines()[i].equalsIgnoreCase(ConfigUtil.getConfigText("SignText")) && lib.getSignLines()[1].equals(liftName)) {
sign.setLine(1, liftName);
sign.setLine(3, ChatColor.GOLD + floorName);
}
}
sign.update();
}
}
}
lift.setY(direction == LiftDirection.UP ? lift.getY() + 1 : lift.getY() - 1);
int signState = direction == LiftDirection.UP ? 1 : 2;
Iterator<LiftSign> signIterator = lift.getSigns().iterator();
while (signIterator.hasNext()) {
LiftSign ls = signIterator.next();
if (ls.getState() == signState) continue;
Block block = Bukkit.getWorld(ls.getWorld()).getBlockAt(ls.getX(), ls.getY(), ls.getZ());
BlockState bs = block.getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation()));
signIterator.remove();
continue;
}
Sign sign = (Sign) bs;
if (ls.getType() == 0) {
String text = direction == LiftDirection.UP ? ConfigUtil.getConfigText("UpText") : ConfigUtil.getConfigText("DownText");
sign.setLine(3, text);
} else {
sign.setLine(3, ChatColor.GRAY + ChatColor.stripColor(sign.getLine(3)));
}
sign.update();
ls.setState((byte) signState);
}
if (direction == LiftDirection.DOWN) {
//MOVE ROPES
for (LiftRope rope : lift.getRopes()) {
boolean stopAfter = false;
if (rope.getCurrently() < rope.getMinY()) {
Bukkit.getLogger().info("[V10Lift] Lift " + liftName + " reaches the upper rope end but won't stop!!");
V10LiftAPI.getInstance().setDefective(liftName, true);
lift.getToMove().clear();
queueIterator.remove();
stopAfter = true;
}
rope.setCurrently(rope.getCurrently() - 1);
Block block = Bukkit.getWorld(rope.getWorld()).getBlockAt(rope.getX(), rope.getCurrently(), rope.getZ());
if (rope.getType() == null) rope.setType(Material.AIR);
block.setType(rope.getType());
if (XMaterial.isNewVersion()) {
DirectionUtil.setDirection(block, rope.getFace());
} else {
BlockState state = block.getState();
org.bukkit.material.Ladder ladder = new org.bukkit.material.Ladder(rope.getType());
ladder.setFacingDirection(rope.getFace());
state.setData(ladder);
state.update(true);
}
if (stopAfter) return;
}
}
} else {
lift.getToMove().clear();
queueIterator.remove();
for (LiftBlock lib : lift.getBlocks()) {
BlockState bs = Bukkit.getWorld(lib.getWorld()).getBlockAt(lib.getX(), lib.getY(), lib.getZ()).getState();
if (!(bs instanceof Sign)) {
if (bs instanceof Chest && lib.serializedItemStacks != null) {
ItemStack[] isa = new ItemStack[lib.serializedItemStacks.length];
boolean by = false;
for (int i = 0; i < lib.serializedItemStacks.length; i++) {
if (lib.serializedItemStacks[i] != null) {
isa[i] = ItemStack.deserialize(lib.serializedItemStacks[i]);
by = true;
}
}
if (by) {
Chest c = (Chest) bs;
c.getInventory().setContents(isa);
c.update();
}
lib.serializedItemStacks = null;
}
continue;
}
Sign sign = (Sign) bs;
if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) continue;
sign.setLine(1, liftName);
sign.setLine(3, ChatColor.GREEN + floorName);
sign.update();
}
Block block = null;
Iterator<LiftSign> signIterator = lift.getSigns().iterator();
while (signIterator.hasNext()) {
LiftSign ls = signIterator.next();
if (ls.getState() == 0) continue;
block = Bukkit.getWorld(ls.getWorld()).getBlockAt(ls.getX(), ls.getY(), ls.getZ());
BlockState bs = block.getState();
if (!(bs instanceof Sign)) {
Bukkit.getLogger().severe("[V10Lift] Wrong sign removed at: " + LocationSerializer.serialize(block.getLocation()));
signIterator.remove();
continue;
}
Sign sign = (Sign) bs;
if (ls.getType() == 0) {
sign.setLine(3, ChatColor.GREEN + floorName);
} else {
String l3 = ChatColor.stripColor(sign.getLine(3));
if (!floorName.equals(l3)) {
sign.setLine(3, ChatColor.GRAY + l3);
} else {
sign.setLine(3, ChatColor.GREEN + l3);
}
}
sign.update();
ls.setState((byte) 0);
}
V10LiftAPI.getInstance().openDoor(lift, liftName, floorTo);
if (lift.isRealistic()) lift.setCounter(ft);
if (lift.isSound() && block != null) XSound.ENTITY_EXPERIENCE_ORB_PICKUP.play(block.getLocation(), 2.0F, 63.0F);
}
}
private void stop() {
Bukkit.getServer().getScheduler().cancelTask(DataManager.getMovingTask(liftName));
DataManager.removeMovingTask(liftName);
}
}

View file

@ -0,0 +1,4 @@
/**
* All the runnables of V10Lift
*/
package nl.SBDeveloper.V10Lift.api.runnables;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,91 @@
package nl.SBDeveloper.V10Lift.commands;
import nl.SBDeveloper.V10Lift.api.objects.Lift;
import nl.SBDeveloper.V10Lift.managers.DataManager;
import nl.SBDeveloper.V10Lift.managers.VaultManager;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class V10LiftTabCompleter implements TabCompleter {
private static final List<String> COMMANDS = Arrays.asList("create", "delete", "rename", "abort", "whois", "edit", "floor", "input", "build", "rope", "door", "speed", "realistic", "repair", "disable", "whitelist", "reload", "help", "start", "stop", "offline");
private static final List<String> SUBRENAME = Arrays.asList("add", "del", "rename");
private static final List<String> SUB = Arrays.asList("add", "del");
@Override
public List<String> onTabComplete(@Nonnull CommandSender commandSender, @Nonnull Command cmd, @Nonnull String label, @Nonnull String[] args) {
if (label.equalsIgnoreCase("v10lift")) {
if (args.length == 1) {
return StringUtil.copyPartialMatches(args[0], COMMANDS, new ArrayList<>());
} else if (args.length == 2) {
//Command based sub-commands
if (args[0].equalsIgnoreCase("delete")
|| args[0].equalsIgnoreCase("edit")
|| args[0].equalsIgnoreCase("whois")
|| args[0].equalsIgnoreCase("repair")
|| args[0].equalsIgnoreCase("disable")
|| args[0].equalsIgnoreCase("start")
|| args[0].equalsIgnoreCase("stop")) {
return StringUtil.copyPartialMatches(args[1], DataManager.getLifts().keySet(), new ArrayList<>());
} else if (args[0].equalsIgnoreCase("floor")) {
return StringUtil.copyPartialMatches(args[1], SUBRENAME, new ArrayList<>());
} else if (args[0].equalsIgnoreCase("input")
|| args[0].equalsIgnoreCase("offline")
|| args[0].equalsIgnoreCase("whitelist")) {
return StringUtil.copyPartialMatches(args[1], SUB, new ArrayList<>());
}
} else if (args.length == 3) {
//Command based arguments
if (args[0].equalsIgnoreCase("floor") && (args[1].equalsIgnoreCase("del") || args[1].equalsIgnoreCase("rename"))) {
if (commandSender instanceof Player) {
Player p = (Player) commandSender;
if (DataManager.containsEditPlayer(p.getUniqueId())) {
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
return StringUtil.copyPartialMatches(args[2], lift.getFloors().keySet(), new ArrayList<>());
}
}
} else if ((args[0].equalsIgnoreCase("input")
|| args[0].equalsIgnoreCase("offline")) && args[1].equalsIgnoreCase("del")) {
if (commandSender instanceof Player) {
Player p = (Player) commandSender;
if (DataManager.containsEditPlayer(p.getUniqueId())) {
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
return StringUtil.copyPartialMatches(args[2], lift.getFloors().keySet(), new ArrayList<>());
}
}
} else if (args[0].equalsIgnoreCase("whitelist")) {
ArrayList<String> playerOrGroupNames = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
playerOrGroupNames.add(p.getName());
}
if (V10LiftPlugin.isVaultEnabled()) {
playerOrGroupNames.addAll(VaultManager.getGroups());
}
return StringUtil.copyPartialMatches(args[2], playerOrGroupNames, new ArrayList<>());
}
} else if (args.length == 4) {
//Command based arguments
if (args[0].equalsIgnoreCase("whitelist")) {
if (commandSender instanceof Player) {
Player p = (Player) commandSender;
if (DataManager.containsEditPlayer(p.getUniqueId())) {
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
return StringUtil.copyPartialMatches(args[3], lift.getFloors().keySet(), new ArrayList<>());
}
}
}
}
}
return null;
}
}

View file

@ -0,0 +1,4 @@
/**
* The command and tab manager of v10lift
*/
package nl.SBDeveloper.V10Lift.commands;

View file

@ -0,0 +1,74 @@
package nl.SBDeveloper.V10Lift.listeners;
import nl.SBDeveloper.V10Lift.api.V10LiftAPI;
import nl.SBDeveloper.V10Lift.api.objects.Floor;
import nl.SBDeveloper.V10Lift.api.objects.Lift;
import nl.SBDeveloper.V10Lift.api.objects.LiftBlock;
import nl.SBDeveloper.V10Lift.managers.DataManager;
import nl.SBDeveloper.V10Lift.utils.ConfigUtil;
import nl.SBDeveloper.V10Lift.utils.DoorUtil;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import java.util.Map;
import java.util.Objects;
public class BlockBreakListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent e) {
Block b = e.getBlock();
if (V10LiftAPI.getInstance().isRope(b)) {
ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveRopeFirst");
e.setCancelled(true);
return;
}
LiftBlock tlb = new LiftBlock(b.getWorld().getName(), b.getX(), b.getY(), b.getZ(), (String) null);
for (Map.Entry<String, Lift> entry : DataManager.getLifts().entrySet()) {
Lift lift = entry.getValue();
if (lift.getBlocks().contains(tlb)) {
ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveLiftFirst");
e.setCancelled(true);
return;
}
for (Floor f : lift.getFloors().values()) {
if (f.getDoorBlocks().contains(tlb)) {
ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveDoorFirst");
e.setCancelled(true);
return;
}
for (LiftBlock lb : f.getRealDoorBlocks()) {
Location loc = DoorUtil.getLowerLocationOfDoor(b);
if (lb.getWorld().equals(Objects.requireNonNull(loc.getWorld(), "World is null at BlockBreakListener").getName())
&& lb.getX() == loc.getBlockX()
&& lb.getY() == loc.getBlockY()
&& lb.getZ() == loc.getBlockZ()) {
ConfigUtil.sendMessage(e.getPlayer(), "General.RemoveDoorFirst");
e.setCancelled(true);
return;
}
}
}
if (!(b.getState() instanceof Sign)) continue;
if (!lift.getSigns().contains(tlb)) continue;
if (!lift.getOwners().contains(e.getPlayer().getUniqueId()) && !e.getPlayer().hasPermission("v10lift.admin")) {
ConfigUtil.sendMessage(e.getPlayer(), "General.NoPermission");
e.setCancelled(true);
} else {
lift.getSigns().remove(tlb);
ConfigUtil.sendMessage(e.getPlayer(), "LiftSign.Removed");
}
}
}
}

View file

@ -0,0 +1,43 @@
package nl.SBDeveloper.V10Lift.listeners;
import nl.SBDeveloper.V10Lift.api.objects.Lift;
import nl.SBDeveloper.V10Lift.api.objects.LiftBlock;
import nl.SBDeveloper.V10Lift.managers.DataManager;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
public class EntityDamageListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent e) {
if (e.getCause() != EntityDamageEvent.DamageCause.SUFFOCATION) return;
Entity entity = e.getEntity();
Location loc;
if (e instanceof LivingEntity) {
loc = ((LivingEntity) entity).getEyeLocation();
} else {
loc = entity.getLocation();
}
if (loc.getWorld() == null) return;
String world = loc.getWorld().getName();
int x = loc.getBlockX();
int y = loc.getBlockY();
int z = loc.getBlockZ();
for (Lift lift : DataManager.getLifts().values()) {
for (LiftBlock lb : lift.getBlocks()) {
if (world.equals(lb.getWorld()) && x == lb.getX() && y == lb.getY() && z == lb.getZ()) {
e.setCancelled(true);
return;
}
}
}
}
}

View file

@ -0,0 +1,425 @@
package nl.SBDeveloper.V10Lift.listeners;
import com.cryptomorin.xseries.XMaterial;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import nl.SBDeveloper.V10Lift.api.V10LiftAPI;
import nl.SBDeveloper.V10Lift.api.objects.Floor;
import nl.SBDeveloper.V10Lift.api.objects.Lift;
import nl.SBDeveloper.V10Lift.api.objects.LiftBlock;
import nl.SBDeveloper.V10Lift.managers.DataManager;
import nl.SBDeveloper.V10Lift.managers.ForbiddenBlockManager;
import nl.SBDeveloper.V10Lift.managers.VaultManager;
import nl.SBDeveloper.V10Lift.utils.ConfigUtil;
import nl.SBDeveloper.V10Lift.utils.DoorUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerAnimationEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import java.util.*;
public class PlayerInteractListener implements Listener {
private final ArrayList<UUID> rightClicked = new ArrayList<>();
//BUTTON CLICK
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerInteractButton(PlayerInteractEvent e) {
Action action = e.getAction();
Block block = e.getClickedBlock();
if (block == null) return;
Material button = block.getType();
if (action == Action.RIGHT_CLICK_BLOCK
&& e.getHand() != EquipmentSlot.OFF_HAND
&& (button.toString().contains("BUTTON") || button == XMaterial.LEVER.parseMaterial())) {
String world = block.getWorld().getName();
int x = block.getX();
int y = block.getY();
int z = block.getZ();
for (Map.Entry<String, Lift> entry : DataManager.getLifts().entrySet()) {
Lift lift = entry.getValue();
for (LiftBlock lb : lift.getOfflineInputs()) {
if (world.equals(lb.getWorld()) && x == lb.getX() && y == lb.getY() && z == lb.getZ()) {
lb.setActive(!lb.isActive());
V10LiftAPI.getInstance().setOffline(entry.getKey(), lb.isActive());
return;
}
}
if (lift.isOffline()) return;
for (LiftBlock lb : lift.getInputs()) {
if (world.equals(lb.getWorld()) && x == lb.getX() && y == lb.getY() && z == lb.getZ()) {
V10LiftAPI.getInstance().addToQueue(entry.getKey(), lift.getFloors().get(lb.getFloor()), lb.getFloor());
e.setCancelled(true);
return;
}
}
}
}
}
//Gamemode adventure left click fix
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerLeftClickSign(PlayerAnimationEvent e) {
Player p = e.getPlayer();
if (p.getGameMode() != GameMode.ADVENTURE) return;
Block lookingBlock = p.getTargetBlock(null, 5);
BlockState bs = lookingBlock.getState();
if (!(bs instanceof Sign)) return;
if (rightClicked.contains(p.getUniqueId())) {
rightClicked.remove(p.getUniqueId());
return;
}
Sign sign = (Sign) bs;
if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) return;
String liftName = sign.getLine(1);
if (!DataManager.containsLift(liftName)) return;
Lift lift = DataManager.getLift(liftName);
if (lift.isOffline()) {
e.setCancelled(true);
return;
}
if (lift.isDefective()) {
e.setCancelled(true);
return;
}
if (!lift.getBlocks().contains(new LiftBlock(sign.getWorld().getName(), sign.getX(), sign.getY(), sign.getZ(), (String) null))) return;
if (DataManager.containsEditLift(liftName)) return;
e.setCancelled(true);
if (lift.isDefective()) return;
String f = ChatColor.stripColor(sign.getLine(3));
if (!lift.getFloors().containsKey(f)) {
ConfigUtil.sendMessage(e.getPlayer(), "General.FloorDoesntExists");
return;
}
Floor floor = lift.getFloors().get(f);
if (!floor.getUserWhitelist().isEmpty() && !floor.getUserWhitelist().contains(p.getUniqueId()) && !p.hasPermission("v10lift.admin")) {
ConfigUtil.sendMessage(e.getPlayer(), "General.NoWhitelistPermission");
e.setCancelled(true);
return;
}
if (!floor.getGroupWhitelist().isEmpty() && !VaultManager.inAnyGroup(p, floor.getGroupWhitelist()) && !p.hasPermission("v10lift.admin")) {
ConfigUtil.sendMessage(e.getPlayer(), "General.NoWhitelistPermission");
e.setCancelled(true);
return;
}
V10LiftAPI.getInstance().addToQueue(liftName, lift.getFloors().get(f), f);
}
//BLOCK ADD
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent e) {
rightClicked.add(e.getPlayer().getUniqueId());
if (e.getHand() != EquipmentSlot.OFF_HAND && e.getClickedBlock() != null) {
Player p = e.getPlayer();
if (DataManager.containsPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
e.setCancelled(true);
int res = V10LiftAPI.getInstance().switchBlockAtLift(DataManager.getPlayer(p.getUniqueId()), e.getClickedBlock());
switch (res) {
case 0:
ConfigUtil.sendMessage(e.getPlayer(), "Build.BlockAdded");
break;
case 1:
ConfigUtil.sendMessage(e.getPlayer(), "Build.BlockRemoved");
break;
case -2:
ConfigUtil.sendMessage(e.getPlayer(), "Build.BlacklistedMaterial", Collections.singletonMap("%Name%", e.getClickedBlock().getType().toString().toLowerCase()));
break;
default:
ConfigUtil.sendMessage(e.getPlayer(), "General.InternalError");
break;
}
} else if (DataManager.containsInputEditsPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
Block block = e.getClickedBlock();
LiftBlock tlb = new LiftBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), DataManager.getInputEditsPlayer(p.getUniqueId()));
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
e.setCancelled(true);
if (lift.getInputs().contains(tlb)) {
ConfigUtil.sendMessage(e.getPlayer(), "Input.AlreadyAdded");
return;
}
lift.getInputs().add(tlb);
DataManager.removeInputEditsPlayer(p.getUniqueId());
ConfigUtil.sendMessage(e.getPlayer(), "Input.Created");
} else if (DataManager.containsOfflineEditsPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
Block block = e.getClickedBlock();
LiftBlock tlb = new LiftBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), (String) null);
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
e.setCancelled(true);
if (lift.getOfflineInputs().contains(tlb)) {
ConfigUtil.sendMessage(e.getPlayer(), "OfflineInput.AlreadyAdded");
return;
}
lift.getOfflineInputs().add(tlb);
DataManager.removeOfflineEditsPlayer(p.getUniqueId());
ConfigUtil.sendMessage(e.getPlayer(), "OfflineInput.Created");
} else if (DataManager.containsInputRemovesPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
Block block = e.getClickedBlock();
LiftBlock tlb = new LiftBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), (String) null);
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
e.setCancelled(true);
if (lift.getInputs().contains(tlb)) {
lift.getInputs().remove(tlb);
DataManager.removeInputRemovesPlayer(p.getUniqueId());
ConfigUtil.sendMessage(e.getPlayer(), "Input.Removed");
return;
}
ConfigUtil.sendMessage(e.getPlayer(), "Input.NoInput");
} else if (DataManager.containsOfflineRemovesPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
Block block = e.getClickedBlock();
LiftBlock tlb = new LiftBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), (String) null);
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
e.setCancelled(true);
if (lift.getOfflineInputs().contains(tlb)) {
lift.getOfflineInputs().remove(tlb);
DataManager.removeOfflineRemovesPlayer(p.getUniqueId());
ConfigUtil.sendMessage(e.getPlayer(), "OfflineInput.Removed");
return;
}
ConfigUtil.sendMessage(e.getPlayer(), "OfflineInput.NoInput");
} else if (DataManager.containsBuilderPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
e.setCancelled(true);
int res = V10LiftAPI.getInstance().switchBlockAtLift(DataManager.getEditPlayer(p.getUniqueId()), e.getClickedBlock());
switch (res) {
case 0:
ConfigUtil.sendMessage(e.getPlayer(), "Build.BlockAdded");
break;
case 1:
ConfigUtil.sendMessage(e.getPlayer(), "Build.BlockRemoved");
break;
case -2:
ConfigUtil.sendMessage(e.getPlayer(), "Build.BlacklistedMaterial", Collections.singletonMap("%Name%", e.getClickedBlock().getType().toString().toLowerCase()));
break;
default:
ConfigUtil.sendMessage(e.getPlayer(), "General.InternalError");
break;
}
} else if (DataManager.containsRopeEditPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
e.setCancelled(true);
LiftBlock start = DataManager.getRopeEditPlayer(p.getUniqueId());
Block now = e.getClickedBlock();
if (start == null) {
ConfigUtil.sendMessage(e.getPlayer(), "Rope.Delete");
DataManager.addRopeEditPlayer(p.getUniqueId(), new LiftBlock(now.getWorld().getName(), now.getX(), now.getY(), now.getZ(), (String) null));
} else if (start.equals(new LiftBlock(now.getWorld().getName(), now.getX(), now.getY(), now.getZ(), (String) null))) {
DataManager.addRopeEditPlayer(p.getUniqueId(), null);
ConfigUtil.sendMessage(e.getPlayer(), "Rope.PartRemoved");
} else {
if (start.getX() != now.getX() || start.getZ() != now.getZ()) {
ConfigUtil.sendMessage(e.getPlayer(), "Rope.OnlyUp");
return;
}
int res = V10LiftAPI.getInstance().addRope(DataManager.getEditPlayer(p.getUniqueId()), now.getWorld(), start.getX(), now.getY(), start.getY(), start.getZ());
switch (res) {
case 0:
ConfigUtil.sendMessage(e.getPlayer(), "Rope.Created");
break;
case -2:
ConfigUtil.sendMessage(e.getPlayer(), "Rope.OnlyOneMaterial");
break;
case -3:
ConfigUtil.sendMessage(e.getPlayer(), "Rope.AlreadyARope");
break;
case -4:
ConfigUtil.sendMessage(e.getPlayer(), "Rope.BlacklistedMaterial");
break;
default:
ConfigUtil.sendMessage(e.getPlayer(), "General.InternalError");
break;
}
DataManager.removeRopeEditPlayer(p.getUniqueId());
}
} else if (DataManager.containsRopeRemovesPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
e.setCancelled(true);
Block block = e.getClickedBlock();
String liftName = DataManager.getEditPlayer(p.getUniqueId());
if (!V10LiftAPI.getInstance().containsRope(liftName, block)) {
ConfigUtil.sendMessage(e.getPlayer(), "Rope.NotARope");
return;
}
V10LiftAPI.getInstance().removeRope(liftName, block);
DataManager.removeRopeRemovesPlayer(p.getUniqueId());
ConfigUtil.sendMessage(e.getPlayer(), "Rope.Removed");
} else if (DataManager.containsDoorEditPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
e.setCancelled(true);
Block block = e.getClickedBlock();
if (ForbiddenBlockManager.isForbidden(block.getType())) {
ConfigUtil.sendMessage(e.getPlayer(), "Door.BlacklistedMaterial", Collections.singletonMap("%Name%", e.getClickedBlock().getType().toString().toLowerCase()));
return;
}
LiftBlock lb;
if (XMaterial.isNewVersion()) {
lb = new LiftBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), block.getType());
} else {
lb = new LiftBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), block.getType(), block.getState().getRawData());
}
Lift lift = DataManager.getLift(DataManager.getEditPlayer(p.getUniqueId()));
Floor floor = lift.getFloors().get(DataManager.getDoorEditPlayer(p.getUniqueId()));
if (DoorUtil.isOpenable(block)) {
if (floor.getRealDoorBlocks().contains(lb)) {
floor.getRealDoorBlocks().remove(lb);
ConfigUtil.sendMessage(e.getPlayer(), "Door.Removed");
return;
}
floor.getRealDoorBlocks().add(lb);
} else {
if (floor.getDoorBlocks().contains(lb)) {
floor.getDoorBlocks().remove(lb);
ConfigUtil.sendMessage(e.getPlayer(), "Door.Removed");
return;
}
floor.getDoorBlocks().add(lb);
}
ConfigUtil.sendMessage(e.getPlayer(), "Door.Created");
} else if (DataManager.containsWhoisREQPlayer(p.getUniqueId())) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
e.setCancelled(true);
Block block = e.getClickedBlock();
LiftBlock lb = new LiftBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), (String) null);
DataManager.removeWhoisREQPlayer(p.getUniqueId());
for (Map.Entry<String, Lift> entry : DataManager.getLifts().entrySet()) {
Lift lift = entry.getValue();
if (lift.getBlocks().contains(lb) || lift.getInputs().contains(lb) || lift.getSigns().contains(lb) || lift.getRopes().contains(lb) || lift.getOfflineInputs().contains(lb)) {
V10LiftAPI.getInstance().sendLiftInfo(p, entry.getKey(), lift);
return;
}
}
ConfigUtil.sendMessage(e.getPlayer(), "Whois.NotALift");
} else {
Action a = e.getAction();
if (a != Action.RIGHT_CLICK_BLOCK && a != Action.LEFT_CLICK_BLOCK) return;
BlockState bs = e.getClickedBlock().getState();
if (!(bs instanceof Sign)) return;
Sign sign = (Sign) bs;
if (!sign.getLine(0).equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) return;
String liftName = sign.getLine(1);
if (!DataManager.containsLift(liftName)) return;
Lift lift = DataManager.getLift(liftName);
if (lift.isOffline()) {
e.setCancelled(true);
return;
}
if (lift.isDefective()) {
if (sign.getLine(3).equals(ConfigUtil.getConfigText("DefectText")) && p.hasPermission("v10lift.repair") && a == Action.RIGHT_CLICK_BLOCK) {
int masterAmount = V10LiftPlugin.getSConfig().getFile().getInt("RepairAmount");
Optional<XMaterial> mat = XMaterial.matchXMaterial(Objects.requireNonNull(V10LiftPlugin.getSConfig().getFile().getString("RepairItem"), "RepairItem is null"));
if (!mat.isPresent()) {
Bukkit.getLogger().severe("[V10Lift] The material for RepairItem is undefined!");
return;
}
Material masterItem = mat.get().parseMaterial();
if (masterItem == null) {
Bukkit.getLogger().severe("[V10Lift] The material for RepairItem is undefined!");
return;
}
if (p.getGameMode() != GameMode.CREATIVE && masterAmount > 0) {
if (!p.getInventory().contains(masterItem)) {
Map<String, String> replacements = new HashMap<>();
replacements.put("%Amount%", String.valueOf(masterAmount));
replacements.put("%ItemName%", masterItem.toString().toLowerCase());
ConfigUtil.sendMessage(e.getPlayer(), "Repair.ItemsNeeded", replacements);
return;
}
p.getInventory().remove(new ItemStack(masterItem, masterAmount));
}
V10LiftAPI.getInstance().setDefective(liftName, false);
}
e.setCancelled(true);
return;
}
if (!lift.getBlocks().contains(new LiftBlock(sign.getWorld().getName(), sign.getX(), sign.getY(), sign.getZ(), (String) null))) return;
if (DataManager.containsEditLift(liftName)) return;
e.setCancelled(true);
if (lift.isDefective()) return;
String f = ChatColor.stripColor(sign.getLine(3));
if (a == Action.RIGHT_CLICK_BLOCK) {
Iterator<String> iter = lift.getFloors().keySet().iterator();
if (!lift.getFloors().containsKey(f)) {
if (!iter.hasNext()) {
ConfigUtil.sendMessage(e.getPlayer(), "General.NoFloors");
return;
}
f = iter.next();
}
while (iter.hasNext()) {
if (iter.next().equals(f)) break;
}
if (!iter.hasNext()) iter = lift.getFloors().keySet().iterator();
String f2 = iter.next();
Floor floor = lift.getFloors().get(f2);
if (lift.getY() == floor.getY()) {
sign.setLine(3, ChatColor.GREEN + f2);
} else if (!floor.getUserWhitelist().isEmpty() && !floor.getUserWhitelist().contains(p.getUniqueId()) && !p.hasPermission("v10lift.admin")) {
sign.setLine(3, ChatColor.RED + f2);
} else if (!floor.getGroupWhitelist().isEmpty() && !VaultManager.inAnyGroup(p, floor.getGroupWhitelist()) && !p.hasPermission("v10lift.admin")) {
sign.setLine(3, ChatColor.RED + f2);
} else {
sign.setLine(3, ChatColor.YELLOW + f2);
}
sign.update();
} else {
if (!lift.getFloors().containsKey(f)) {
ConfigUtil.sendMessage(e.getPlayer(), "General.FloorDoesntExists");
return;
}
Floor floor = lift.getFloors().get(f);
if (!floor.getUserWhitelist().isEmpty() && !floor.getUserWhitelist().contains(p.getUniqueId()) && !p.hasPermission("v10lift.admin")) {
ConfigUtil.sendMessage(e.getPlayer(), "General.NoWhitelistPermission");
e.setCancelled(true);
return;
}
if (!floor.getGroupWhitelist().isEmpty() && !VaultManager.inAnyGroup(p, floor.getGroupWhitelist()) && !p.hasPermission("v10lift.admin")) {
ConfigUtil.sendMessage(e.getPlayer(), "General.NoWhitelistPermission");
e.setCancelled(true);
return;
}
V10LiftAPI.getInstance().addToQueue(liftName, lift.getFloors().get(f), f);
}
}
}
}
}

View file

@ -0,0 +1,54 @@
package nl.SBDeveloper.V10Lift.listeners;
import nl.SBDeveloper.V10Lift.api.objects.Lift;
import nl.SBDeveloper.V10Lift.api.objects.LiftSign;
import nl.SBDeveloper.V10Lift.managers.DataManager;
import nl.SBDeveloper.V10Lift.utils.ConfigUtil;
import org.bukkit.ChatColor;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
public class SignChangeListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignChange(SignChangeEvent e) {
String[] lines = e.getLines();
if (!lines[0].equalsIgnoreCase(ConfigUtil.getConfigText("SignText"))) return;
Player p = e.getPlayer();
if (lines[1].isEmpty()) {
ConfigUtil.sendMessage(e.getPlayer(), "LiftSign.NoName");
return;
}
if (!DataManager.containsLift(lines[1])) {
ConfigUtil.sendMessage(e.getPlayer(), "General.DoesntExists");
return;
}
Lift lift = DataManager.getLift(lines[1]);
if (!lift.getOwners().contains(p.getUniqueId()) && !p.hasPermission("v10lift.admin")) {
ConfigUtil.sendMessage(e.getPlayer(), "General.NoPermission");
e.setCancelled(true);
return;
}
byte type;
if (lift.getFloors().containsKey(lines[2])) {
type = 1;
e.setLine(3, ChatColor.GRAY + lines[2]);
} else {
type = 0;
}
e.setLine(2, "");
Block b = e.getBlock();
lift.getSigns().add(new LiftSign(b.getWorld().getName(), b.getX(), b.getY(), b.getZ(), type, (byte) 0));
ConfigUtil.sendMessage(e.getPlayer(), "LiftSign.Created");
}
}

View file

@ -0,0 +1,4 @@
/**
* All the event listeners of V10Lift
*/
package nl.SBDeveloper.V10Lift.listeners;

View file

@ -0,0 +1,95 @@
package nl.SBDeveloper.V10Lift.managers;
import com.cryptomorin.xseries.XMaterial;
import org.bukkit.Material;
import java.util.HashSet;
/**
* This class contains a set with all the blocks who may not be copied
*/
public class AntiCopyBlockManager {
private static final HashSet<XMaterial> antiCopy = new HashSet<>();
static {
//TODO Add more anti copy materials
//TODO Add to config
antiCopy.add(XMaterial.REDSTONE_TORCH);
antiCopy.add(XMaterial.REDSTONE_WALL_TORCH);
antiCopy.add(XMaterial.REPEATER);
antiCopy.add(XMaterial.COMPARATOR);
antiCopy.add(XMaterial.REDSTONE_WIRE);
antiCopy.add(XMaterial.ACACIA_BUTTON);
antiCopy.add(XMaterial.BIRCH_BUTTON);
antiCopy.add(XMaterial.DARK_OAK_BUTTON);
antiCopy.add(XMaterial.JUNGLE_BUTTON);
antiCopy.add(XMaterial.OAK_BUTTON);
antiCopy.add(XMaterial.SPRUCE_BUTTON);
antiCopy.add(XMaterial.STONE_BUTTON);
antiCopy.add(XMaterial.TORCH);
antiCopy.add(XMaterial.ACACIA_TRAPDOOR);
antiCopy.add(XMaterial.BIRCH_TRAPDOOR);
antiCopy.add(XMaterial.DARK_OAK_TRAPDOOR);
antiCopy.add(XMaterial.JUNGLE_TRAPDOOR);
antiCopy.add(XMaterial.OAK_TRAPDOOR);
antiCopy.add(XMaterial.SPRUCE_TRAPDOOR);
antiCopy.add(XMaterial.IRON_TRAPDOOR);
antiCopy.add(XMaterial.ACACIA_PRESSURE_PLATE);
antiCopy.add(XMaterial.BIRCH_PRESSURE_PLATE);
antiCopy.add(XMaterial.DARK_OAK_PRESSURE_PLATE);
antiCopy.add(XMaterial.JUNGLE_PRESSURE_PLATE);
antiCopy.add(XMaterial.OAK_PRESSURE_PLATE);
antiCopy.add(XMaterial.SPRUCE_PRESSURE_PLATE);
antiCopy.add(XMaterial.STONE_PRESSURE_PLATE);
antiCopy.add(XMaterial.HEAVY_WEIGHTED_PRESSURE_PLATE);
antiCopy.add(XMaterial.LIGHT_WEIGHTED_PRESSURE_PLATE);
antiCopy.add(XMaterial.ACACIA_SIGN);
antiCopy.add(XMaterial.BIRCH_SIGN);
antiCopy.add(XMaterial.DARK_OAK_SIGN);
antiCopy.add(XMaterial.JUNGLE_SIGN);
antiCopy.add(XMaterial.OAK_SIGN);
antiCopy.add(XMaterial.SPRUCE_SIGN);
antiCopy.add(XMaterial.ACACIA_WALL_SIGN);
antiCopy.add(XMaterial.BIRCH_WALL_SIGN);
antiCopy.add(XMaterial.DARK_OAK_WALL_SIGN);
antiCopy.add(XMaterial.JUNGLE_WALL_SIGN);
antiCopy.add(XMaterial.OAK_WALL_SIGN);
antiCopy.add(XMaterial.SPRUCE_WALL_SIGN);
antiCopy.add(XMaterial.RAIL);
antiCopy.add(XMaterial.POWERED_RAIL);
antiCopy.add(XMaterial.DETECTOR_RAIL);
antiCopy.add(XMaterial.ACTIVATOR_RAIL);
antiCopy.add(XMaterial.LADDER);
/* Because of datatypes */
antiCopy.add(XMaterial.BEEHIVE);
antiCopy.add(XMaterial.BELL);
antiCopy.add(XMaterial.BREWING_STAND);
antiCopy.add(XMaterial.BUBBLE_COLUMN);
antiCopy.add(XMaterial.CAKE);
antiCopy.add(XMaterial.CAMPFIRE);
antiCopy.add(XMaterial.COCOA);
antiCopy.add(XMaterial.COMMAND_BLOCK);
antiCopy.add(XMaterial.CHAIN_COMMAND_BLOCK);
antiCopy.add(XMaterial.REPEATING_COMMAND_BLOCK);
antiCopy.add(XMaterial.DAYLIGHT_DETECTOR);
antiCopy.add(XMaterial.DISPENSER);
antiCopy.add(XMaterial.END_PORTAL_FRAME);
antiCopy.add(XMaterial.FARMLAND);
antiCopy.add(XMaterial.FIRE);
antiCopy.add(XMaterial.FURNACE);
antiCopy.add(XMaterial.HOPPER);
antiCopy.add(XMaterial.JUKEBOX);
}
/**
* Check if this block may not be copied
*
* @param mat The material to check for
* @return true = not copy this block
*/
public static boolean isAntiCopy(Material mat) {
XMaterial xmat = XMaterial.matchXMaterial(mat);
return antiCopy.contains(xmat);
}
}

View file

@ -0,0 +1,165 @@
package nl.SBDeveloper.V10Lift.managers;
import com.google.gson.Gson;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import nl.SBDeveloper.V10Lift.api.objects.Lift;
import nl.SBDeveloper.V10Lift.sbutils.SQLiteDB;
import org.bukkit.Bukkit;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
/**
* The DBManager manages the database
*/
public class DBManager {
private static final Gson gson = new Gson();
private static SQLiteDB data;
private static Connection con;
/**
* Construct the database manager
*
* @param name The name of the sqlite database file
*/
public DBManager(String name) {
data = new SQLiteDB(name);
try {
con = data.getConnection();
String query = "CREATE TABLE IF NOT EXISTS lifts (liftName varchar(255) NOT NULL, liftData blob NOT NULL, UNIQUE (liftName))";
PreparedStatement statement = con.prepareStatement(query);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Load the database from data
*
* @throws SQLException If the SQL SELECT fails
*/
public void load() throws SQLException {
String query = "SELECT * FROM lifts";
PreparedStatement statement = con.prepareStatement(query);
ResultSet liftSet = statement.executeQuery();
while (liftSet.next()) {
//Loading a lift...
/*
* @todo Fix migrating from 1.12.2- to 1.13+
* - byte to Facing for signs
* - Facing opposite for ropes
* - New materials
*/
byte[] blob = liftSet.getBytes("liftData");
String json = new String(blob);
Lift lift = gson.fromJson(json, Lift.class);
DataManager.addLift(liftSet.getString("liftName"), lift);
Bukkit.getLogger().info("[V10Lift] Loading lift " + liftSet.getString("liftName") + " from data...");
}
}
/**
* Remove a lift from data
*
* @param liftName The name of the lift
*/
public void remove(String liftName) {
if (!DataManager.containsLift(liftName)) {
Bukkit.getLogger().info("[V10Lift] Removing lift " + liftName + " to data...");
Bukkit.getScheduler().runTaskAsynchronously(V10LiftPlugin.getInstance(), () -> {
try {
String query = "DELETE FROM lifts WHERE liftName = ?";
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, liftName);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
}
/**
* Save all lifts to data
* This is done async
*/
public void save() {
save(false);
}
/**
* Save all lifts to data
* @param force true if sync, false if async
*/
public void save(boolean force) {
if (!force) {
Bukkit.getScheduler().runTaskAsynchronously(V10LiftPlugin.getInstance(), () -> {
for (Map.Entry<String, Lift> entry : DataManager.getLifts().entrySet()) {
saveLift(entry.getKey(), entry.getValue());
}
});
} else {
for (Map.Entry<String, Lift> entry : DataManager.getLifts().entrySet()) {
saveLift(entry.getKey(), entry.getValue());
}
}
}
/**
* Save a lift to data
*
* @param liftName The name of the lift
* @param lift The lift itself
*/
public void saveLift(String liftName, Lift lift) {
Bukkit.getLogger().info("[V10Lift] Saving lift " + liftName + " to data...");
byte[] blob = gson.toJson(lift).getBytes();
Bukkit.getScheduler().runTaskAsynchronously(V10LiftPlugin.getInstance(), () -> updateLift(liftName, blob));
}
/**
* Update a lift in data
*
* @param liftName The name of the lift
* @param liftData The JSON blob of the lift object
*/
private void updateLift(String liftName, byte[] liftData) {
try {
String query = "INSERT INTO lifts (liftName, liftData) VALUES (?, ?)";
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, liftName);
statement.setBytes(2, liftData);
statement.executeUpdate();
} catch (SQLException ignored) {}
try {
String query2 = "UPDATE lifts SET liftData = ? WHERE liftName = ?";
PreparedStatement statement2 = con.prepareStatement(query2);
statement2.setBytes(1, liftData);
statement2.setString(2, liftName);
statement2.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Close the connection with the database
*/
public void closeConnection() {
data.closeSource();
}
}

View file

@ -0,0 +1,231 @@
package nl.SBDeveloper.V10Lift.managers;
import lombok.Getter;
import nl.SBDeveloper.V10Lift.api.objects.Lift;
import nl.SBDeveloper.V10Lift.api.objects.LiftBlock;
import java.util.*;
public class DataManager {
/* A manager for general HashMaps */
@Getter private static final Map<String, Lift> lifts = new LinkedHashMap<>();
private static final Map<UUID, TreeSet<LiftBlock>> builds = new LinkedHashMap<>();
@Getter private static final Map<UUID, String> editors = new LinkedHashMap<>();
private static final Map<UUID, String> inputEdits = new LinkedHashMap<>();
private static final List<UUID> inputRemoves = new ArrayList<>();
private static final List<UUID> offlineEdits = new ArrayList<>();
private static final List<UUID> offlineRemoves = new ArrayList<>();
private static final List<UUID> builder = new ArrayList<>();
private static final Map<UUID, LiftBlock> ropeEdits = new LinkedHashMap<>();
private static final List<UUID> ropeRemoves = new ArrayList<>();
private static final Map<UUID, String> doorEdits = new HashMap<>();
private static final List<UUID> whoisReq = new ArrayList<>();
private static final Map<String, Integer> movingTasks = new HashMap<>();
/* HashMap methods */
// //
public static void addLift(String liftName, Lift lift) {
lifts.put(liftName, lift);
}
public static void removeLift(String liftName) {
lifts.remove(liftName);
}
public static boolean containsLift(String liftName) {
return lifts.containsKey(liftName);
}
public static Lift getLift(String liftName) {
return lifts.get(liftName);
}
// //
public static boolean containsPlayer(UUID player) {
return builds.containsKey(player);
}
public static void addPlayer(UUID player) {
builds.put(player, new TreeSet<>());
}
public static void removePlayer(UUID player) {
builds.remove(player);
}
public static TreeSet<LiftBlock> getPlayer(UUID player) {
return builds.get(player);
}
// //
public static boolean containsInputEditsPlayer(UUID player) {
return inputEdits.containsKey(player);
}
public static void addInputEditsPlayer(UUID player, String liftName) {
inputEdits.put(player, liftName);
}
public static void removeInputEditsPlayer(UUID player) {
inputEdits.remove(player);
}
public static String getInputEditsPlayer(UUID player) {
return inputEdits.get(player);
}
// //
public static boolean containsRopeEditPlayer(UUID player) {
return ropeEdits.containsKey(player);
}
public static void addRopeEditPlayer(UUID player, LiftBlock liftBlock) {
ropeEdits.put(player, liftBlock);
}
public static void removeRopeEditPlayer(UUID player) {
ropeEdits.remove(player);
}
public static LiftBlock getRopeEditPlayer(UUID player) {
return ropeEdits.get(player);
}
// //
public static boolean containsEditPlayer(UUID player) {
return editors.containsKey(player);
}
public static boolean containsEditLift(String liftName) {
return editors.containsValue(liftName);
}
public static void addEditPlayer(UUID player, String liftName) {
editors.put(player, liftName);
}
public static void removeEditPlayer(UUID player) {
editors.remove(player);
}
public static String getEditPlayer(UUID player) {
return editors.get(player);
}
// //
public static void addMovingTask(String liftName, int taskid) {
movingTasks.put(liftName, taskid);
}
public static void removeMovingTask(String liftName) {
movingTasks.remove(liftName);
}
public static boolean containsMovingTask(String liftName) {
return movingTasks.containsKey(liftName);
}
public static int getMovingTask(String liftName) {
return movingTasks.get(liftName);
}
public static void clearMovingTasks() { movingTasks.clear(); }
// //
public static boolean containsDoorEditPlayer(UUID player) {
return doorEdits.containsKey(player);
}
public static void addDoorEditPlayer(UUID player, String floorName) {
doorEdits.put(player, floorName);
}
public static void removeDoorEditPlayer(UUID player) {
doorEdits.remove(player);
}
public static String getDoorEditPlayer(UUID player) {
return doorEdits.get(player);
}
/* ArrayList methods */
// //
public static boolean containsOfflineEditsPlayer(UUID player) {
return offlineEdits.contains(player);
}
public static void addOfflineEditsPlayer(UUID player) {
offlineEdits.add(player);
}
public static void removeOfflineEditsPlayer(UUID player) {
offlineEdits.remove(player);
}
// //
public static boolean containsOfflineRemovesPlayer(UUID player) {
return offlineRemoves.contains(player);
}
public static void addOfflineRemovesPlayer(UUID player) {
offlineRemoves.add(player);
}
public static void removeOfflineRemovesPlayer(UUID player) {
offlineRemoves.remove(player);
}
// //
public static boolean containsBuilderPlayer(UUID player) {
return builder.contains(player);
}
public static void addBuilderPlayer(UUID player) {
builder.add(player);
}
public static void removeBuilderPlayer(UUID player) {
builder.remove(player);
}
// //
public static boolean containsRopeRemovesPlayer(UUID player) {
return ropeRemoves.contains(player);
}
public static void addRopeRemovesPlayer(UUID player) {
ropeRemoves.add(player);
}
public static void removeRopeRemovesPlayer(UUID player) {
ropeRemoves.remove(player);
}
// //
public static boolean containsInputRemovesPlayer(UUID player) {
return inputRemoves.contains(player);
}
public static void addInputRemovesPlayer(UUID player) {
inputRemoves.add(player);
}
public static void removeInputRemovesPlayer(UUID player) {
inputRemoves.remove(player);
}
// //
public static boolean containsWhoisREQPlayer(UUID player) {
return whoisReq.contains(player);
}
public static void addWhoisREQPlayer(UUID player) {
whoisReq.add(player);
}
public static void removeWhoisREQPlayer(UUID player) {
whoisReq.remove(player);
}
}

View file

@ -0,0 +1,57 @@
package nl.SBDeveloper.V10Lift.managers;
import com.cryptomorin.xseries.XMaterial;
import org.bukkit.Material;
import java.util.HashSet;
/**
* This class contains a set with all the blocks who may not be placed in a lift
*/
public class ForbiddenBlockManager {
private static final HashSet<XMaterial> forbidden = new HashSet<>();
static {
//TODO Add more forbidden materials
//TODO Add to config
forbidden.add(XMaterial.BLACK_BED);
forbidden.add(XMaterial.BLUE_BED);
forbidden.add(XMaterial.BROWN_BED);
forbidden.add(XMaterial.CYAN_BED);
forbidden.add(XMaterial.GRAY_BED);
forbidden.add(XMaterial.GREEN_BED);
forbidden.add(XMaterial.LIGHT_BLUE_BED);
forbidden.add(XMaterial.LIGHT_GRAY_BED);
forbidden.add(XMaterial.LIME_BED);
forbidden.add(XMaterial.MAGENTA_BED);
forbidden.add(XMaterial.ORANGE_BED);
forbidden.add(XMaterial.PINK_BED);
forbidden.add(XMaterial.PURPLE_BED);
forbidden.add(XMaterial.RED_BED);
forbidden.add(XMaterial.WHITE_BED);
forbidden.add(XMaterial.YELLOW_BED);
forbidden.add(XMaterial.ACACIA_SAPLING);
forbidden.add(XMaterial.BAMBOO_SAPLING);
forbidden.add(XMaterial.BIRCH_SAPLING);
forbidden.add(XMaterial.DARK_OAK_SAPLING);
forbidden.add(XMaterial.JUNGLE_SAPLING);
forbidden.add(XMaterial.OAK_SAPLING);
forbidden.add(XMaterial.SPRUCE_SAPLING);
forbidden.add(XMaterial.TNT);
forbidden.add(XMaterial.PISTON);
forbidden.add(XMaterial.PISTON_HEAD);
forbidden.add(XMaterial.MOVING_PISTON);
forbidden.add(XMaterial.STICKY_PISTON);
}
/**
* Check if this block may not be placed in a lift
*
* @param mat The material to check for
* @return true = not place this block
*/
public static boolean isForbidden(Material mat) {
XMaterial xmat = XMaterial.matchXMaterial(mat);
return forbidden.contains(xmat);
}
}

View file

@ -0,0 +1,63 @@
package nl.SBDeveloper.V10Lift.managers;
import net.milkbowl.vault.permission.Permission;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class VaultManager {
private static Permission perms = null;
/**
* Setup the Vault permission API
*
* @return true if success, false if Vault not found
*/
public static boolean setupPermissions() {
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
RegisteredServiceProvider<Permission> rsp = V10LiftPlugin.getInstance().getServer().getServicesManager().getRegistration(Permission.class);
perms = rsp.getProvider();
return true;
}
/**
* Get all the groups in the server
*
* @return A list with all the names of all the groups in the server
*/
public static List<String> getGroups() {
return Arrays.asList(perms.getGroups());
}
/**
* Check if a group exists
*
* @param groupName The name of the group
* @return true if exists
*/
public static boolean isGroup(String groupName) {
return Arrays.asList(perms.getGroups()).contains(groupName);
}
/**
* Check if a user is in any of the groups provided
*
* @param player The player to check for
* @param groups The groups to check for
* @return true if in a group
*/
public static boolean inAnyGroup(Player player, HashSet<String> groups) {
boolean found = false;
for (String group : groups) {
found = Arrays.asList(perms.getPlayerGroups(player)).contains(group);
}
return found;
}
}

View file

@ -0,0 +1,4 @@
/**
* The package with all the managers, like forbidden blocks, data and more
*/
package nl.SBDeveloper.V10Lift.managers;

View file

@ -0,0 +1,4 @@
/**
* Main package of V10Lift
*/
package nl.SBDeveloper.V10Lift;

View file

@ -0,0 +1,331 @@
package nl.SBDeveloper.V10Lift.sbutils;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
/**
* A class to update/add new sections/keys to your config while keeping your current values and keeping your comments
* Algorithm:
* Read the new file and scan for comments and ignored sections, if ignored section is found it is treated as a comment.
* Read and write each line of the new config, if the old config has value for the given key it writes that value in the new config.
* If a key has an attached comment above it, it is written first.
* @author tchristofferson
*/
public class ConfigUpdater {
/**
* Update a yaml file from a resource inside your plugin jar
* @param plugin You plugin
* @param resourceName The yaml file name to update from, typically config.yml
* @param toUpdate The yaml file to update
* @param ignoredSections List of sections to ignore and copy from the current config
* @throws IOException If an IOException occurs
*/
public static void update(Plugin plugin, String resourceName, File toUpdate, List<String> ignoredSections) throws IOException {
BufferedReader newReader = new BufferedReader(new InputStreamReader(plugin.getResource(resourceName), StandardCharsets.UTF_8));
List<String> newLines = newReader.lines().collect(Collectors.toList());
newReader.close();
FileConfiguration oldConfig = YamlConfiguration.loadConfiguration(toUpdate);
FileConfiguration newConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin.getResource(resourceName)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toUpdate), StandardCharsets.UTF_8));
List<String> ignoredSectionsArrayList = new ArrayList<>(ignoredSections);
//ignoredSections can ONLY contain configurations sections
ignoredSectionsArrayList.removeIf(ignoredSection -> !newConfig.isConfigurationSection(ignoredSection));
DumperOptions options = new DumperOptions();
options.setSplitLines(false);
Yaml yaml = new Yaml(options);
Map<String, String> comments = parseComments(newLines, ignoredSectionsArrayList, oldConfig, yaml);
write(newConfig, oldConfig, comments, ignoredSectionsArrayList, writer, yaml);
}
//Write method doing the work.
//It checks if key has a comment associated with it and writes comment then the key and value
private static void write(FileConfiguration newConfig, FileConfiguration oldConfig, Map<String, String> comments, List<String> ignoredSections, BufferedWriter writer, Yaml yaml) throws IOException {
outer: for (String key : newConfig.getKeys(true)) {
String[] keys = key.split("\\.");
String actualKey = keys[keys.length - 1];
String comment = comments.remove(key);
StringBuilder prefixBuilder = new StringBuilder();
int indents = keys.length - 1;
appendPrefixSpaces(prefixBuilder, indents);
String prefixSpaces = prefixBuilder.toString();
if (comment != null) {
writer.write(comment);//No \n character necessary, new line is automatically at end of comment
}
for (String ignoredSection : ignoredSections) {
if (key.startsWith(ignoredSection)) {
continue outer;
}
}
Object newObj = newConfig.get(key);
Object oldObj = oldConfig.get(key);
if (newObj instanceof ConfigurationSection && oldObj instanceof ConfigurationSection) {
//write the old section
writeSection(writer, actualKey, prefixSpaces, (ConfigurationSection) oldObj);
} else if (newObj instanceof ConfigurationSection) {
//write the new section, old value is no more
writeSection(writer, actualKey, prefixSpaces, (ConfigurationSection) newObj);
} else if (oldObj != null) {
//write the old object
write(oldObj, actualKey, prefixSpaces, yaml, writer);
} else {
//write new object
write(newObj, actualKey, prefixSpaces, yaml, writer);
}
}
String danglingComments = comments.get(null);
if (danglingComments != null) {
writer.write(danglingComments);
}
writer.close();
}
//Doesn't work with configuration sections, must be an actual object
//Auto checks if it is serializable and writes to file
private static void write(Object obj, String actualKey, String prefixSpaces, Yaml yaml, BufferedWriter writer) throws IOException {
if (obj instanceof ConfigurationSerializable) {
writer.write(prefixSpaces + actualKey + ": " + yaml.dump(((ConfigurationSerializable) obj).serialize()));
} else if (obj instanceof String || obj instanceof Character) {
if (obj instanceof String) {
String s = (String) obj;
obj = s.replace("\n", "\\n");
}
writer.write(prefixSpaces + actualKey + ": " + yaml.dump(obj));
} else if (obj instanceof List) {
writeList((List<?>) obj, actualKey, prefixSpaces, yaml, writer);
} else {
writer.write(prefixSpaces + actualKey + ": " + yaml.dump(obj));
}
}
//Writes a configuration section
private static void writeSection(BufferedWriter writer, String actualKey, String prefixSpaces, ConfigurationSection section) throws IOException {
if (section.getKeys(false).isEmpty()) {
writer.write(prefixSpaces + actualKey + ": {}");
} else {
writer.write(prefixSpaces + actualKey + ":");
}
writer.write("\n");
}
//Writes a list of any object
private static void writeList(List<?> list, String actualKey, String prefixSpaces, Yaml yaml, BufferedWriter writer) throws IOException {
writer.write(getListAsString(list, actualKey, prefixSpaces, yaml));
}
private static String getListAsString(List<?> list, String actualKey, String prefixSpaces, Yaml yaml) {
StringBuilder builder = new StringBuilder(prefixSpaces).append(actualKey).append(":");
if (list.isEmpty()) {
builder.append(" []\n");
return builder.toString();
}
builder.append("\n");
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if (o instanceof String || o instanceof Character) {
builder.append(prefixSpaces).append("- '").append(o).append("'");
} else if (o instanceof List) {
builder.append(prefixSpaces).append("- ").append(yaml.dump(o));
} else {
builder.append(prefixSpaces).append("- ").append(o);
}
if (i != list.size()) {
builder.append("\n");
}
}
return builder.toString();
}
//Key is the config key, value = comment and/or ignored sections
//Parses comments, blank lines, and ignored sections
private static Map<String, String> parseComments(List<String> lines, List<String> ignoredSections, FileConfiguration oldConfig, Yaml yaml) {
Map<String, String> comments = new HashMap<>();
StringBuilder builder = new StringBuilder();
StringBuilder keyBuilder = new StringBuilder();
int lastLineIndentCount = 0;
outer: for (int i = 0; i<lines.size(); i++) {
String line = lines.get(i);
if (line != null && line.trim().startsWith("-"))
continue;
if (line == null || line.trim().equals("") || line.trim().startsWith("#")) {
builder.append(line).append("\n");
} else {
lastLineIndentCount = setFullKey(keyBuilder, i, lines, lastLineIndentCount);
for (String ignoredSection : ignoredSections) {
if (keyBuilder.toString().equals(ignoredSection)) {
Object value = oldConfig.get(keyBuilder.toString());
if (value instanceof ConfigurationSection)
appendSection(builder, (ConfigurationSection) value, new StringBuilder(getPrefixSpaces(lastLineIndentCount)), yaml);
continue outer;
}
}
if (keyBuilder.length() > 0) {
comments.put(keyBuilder.toString(), builder.toString());
builder.setLength(0);
}
}
}
if (builder.length() > 0) {
comments.put(null, builder.toString());
}
return comments;
}
private static void appendSection(StringBuilder builder, ConfigurationSection section, StringBuilder prefixSpaces, Yaml yaml) {
builder.append(prefixSpaces).append(getKeyFromFullKey(section.getCurrentPath())).append(":");
Set<String> keys = section.getKeys(false);
if (keys.isEmpty()) {
builder.append(" {}\n");
return;
}
builder.append("\n");
prefixSpaces.append(" ");
for (String key : keys) {
Object value = section.get(key);
String actualKey = getKeyFromFullKey(key);
if (value instanceof ConfigurationSection) {
appendSection(builder, (ConfigurationSection) value, prefixSpaces, yaml);
prefixSpaces.setLength(prefixSpaces.length() - 2);
} else if (value instanceof List) {
builder.append(getListAsString((List<?>) value, actualKey, prefixSpaces.toString(), yaml));
} else {
builder.append(prefixSpaces.toString()).append(actualKey).append(": ").append(yaml.dump(value));
}
}
}
//Check how many times spaces make a jump of at least two
private static int countIndents(int index, List<String> lines) {
int currentSpaces = getSpaces(lines.get(index));
int indents = 0;
for (int i = index-1; i >= 0; i--){
String line = lines.get(i);
if (line == null || line.trim().equals("")) continue;
int newSpaces = getSpaces(lines.get(i));
// differs at least two
if (newSpaces < currentSpaces - 1){
indents++;
currentSpaces = newSpaces;
}
if (currentSpaces <= 1) break;
}
return indents;
}
private static int getSpaces(String line){
int spaces = 0;
for (char c : line.toCharArray()) {
if (c == ' ') {
spaces += 1;
} else {
break;
}
}
return spaces;
}
//Ex. keyBuilder = key1.key2.key3 --> key1.key2
private static void removeLastKey(StringBuilder keyBuilder) {
String temp = keyBuilder.toString();
String[] keys = temp.split("\\.");
if (keys.length == 1) {
keyBuilder.setLength(0);
return;
}
temp = temp.substring(0, temp.length() - keys[keys.length - 1].length() - 1);
keyBuilder.setLength(temp.length());
}
private static String getKeyFromFullKey(String fullKey) {
String[] keys = fullKey.split("\\.");
return keys[keys.length - 1];
}
//Updates the keyBuilder and returns configLines number of indents
private static int setFullKey(StringBuilder keyBuilder, int index, List<String> configLines, int lastLineIndentCount) {
int currentIndents = countIndents(index, configLines);
String key = configLines.get(index).trim().split(":")[0];
if (keyBuilder.length() == 0) {
keyBuilder.append(key);
} else if (currentIndents == lastLineIndentCount) {
//Replace the last part of the key with current key
removeLastKey(keyBuilder);
if (keyBuilder.length() > 0) {
keyBuilder.append(".");
}
keyBuilder.append(key);
} else if (currentIndents > lastLineIndentCount) {
//Append current key to the keyBuilder
keyBuilder.append(".").append(key);
} else {
int difference = lastLineIndentCount - currentIndents;
for (int i = 0; i < difference + 1; i++) {
removeLastKey(keyBuilder);
}
if (keyBuilder.length() > 0) {
keyBuilder.append(".");
}
keyBuilder.append(key);
}
return currentIndents;
}
private static String getPrefixSpaces(int indents) {
return new String(new char[Math.max(0, indents)]).replace("\0", " ");
}
private static void appendPrefixSpaces(StringBuilder builder, int indents) {
builder.append(getPrefixSpaces(indents));
}
}

View file

@ -0,0 +1,79 @@
package nl.SBDeveloper.V10Lift.sbutils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class LocationSerializer {
/**
* Deserialize a serialized location, without {@link Location#getYaw()} and {@link Location#getPitch()}
*
* @param string The location string
*
* @return The location or null if error
*/
@Nullable
public static Location deserialize(@Nonnull String string) {
String[] split = string.split("_");
if (split.length < 4) return null;
//world_x_y_z
return new Location(
Bukkit.getWorld(split[0]),
Double.parseDouble(split[1]),
Double.parseDouble(split[2]),
Double.parseDouble(split[3])
);
}
/**
* Deserialize a serialized location, with {@link Location#getYaw()} and {@link Location#getPitch()}
*
* @param string The location string
*
* @return The location or null if error
*/
@Nonnull
public static Location deserializePY(@Nonnull String string) {
String[] split = string.split("_");
//world_x_y_z
return new Location(
Bukkit.getWorld(split[0]),
Double.parseDouble(split[1]),
Double.parseDouble(split[2]),
Double.parseDouble(split[3]),
Float.parseFloat(split[4]),
Float.parseFloat(split[5])
);
}
/**
* Serialize a location, without {@link Location#getYaw()} and {@link Location#getPitch()}
*
* @param loc The location
*
* @return The serialized string
*/
@Nullable
public static String serialize(@Nonnull Location loc) {
if (loc.getWorld() == null) return null;
return loc.getWorld().getName() + "_" + loc.getX() + "_" + loc.getY() + "_" + loc.getZ();
}
/**
* Serialize a location, with {@link Location#getYaw()} and {@link Location#getPitch()}
*
* @param loc The location
*
* @return The serialized string
*/
@Nullable
public static String serializePY(@Nonnull Location loc) {
if (loc.getWorld() == null) return null;
return loc.getWorld().getName() + "_" + loc.getX() + "_" + loc.getY() + "_" + loc.getZ() + "_" + loc.getYaw() + "_" + loc.getPitch();
}
}

View file

@ -0,0 +1,89 @@
package nl.SBDeveloper.V10Lift.sbutils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import org.bukkit.Bukkit;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class SQLiteDB {
private final String dbName;
private HikariDataSource source;
private Connection con;
/**
* Initialize a new connection
*
* @param dbName The database name
*/
public SQLiteDB(String dbName) {
this.dbName = dbName;
File dbFile = new File(V10LiftPlugin.getInstance().getDataFolder(), dbName + ".db");
if (!dbFile.exists()) {
try {
Bukkit.getLogger().info("[V10Lift] Generating the " + dbName + ".db!");
if (!dbFile.createNewFile()) {
Bukkit.getLogger().severe("[V10Lift] Couldn't generate the " + dbName + ".db!");
return;
}
} catch (IOException e) {
Bukkit.getLogger().info("[V10Lift] Couldn't generate the " + dbName + ".db!");
return;
}
}
HikariConfig config = new HikariConfig();
config.setPoolName("V10Lift");
config.setUsername(null);
config.setPassword(null);
config.setDriverClassName("org.sqlite.JDBC");
config.setConnectionTestQuery("SELECT 1");
config.setMaximumPoolSize(1);
Properties prop = new Properties();
prop.setProperty("date_string_format", "yyyy-MM-dd HH:mm:ss");
config.setJdbcUrl("jdbc:sqlite:" + dbFile.getAbsolutePath());
config.setDataSourceProperties(prop);
this.source = new HikariDataSource(config);
try {
this.con = this.source.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Get the connection, to execute queries
*
* CREATE TABLE - execute()
* SELECT - executeQuery()
* UPDATE - executeUpdate()
*
* @return Connection
*/
public Connection getConnection() {
return this.con;
}
/**
* Close the connection
*/
public void closeSource() {
Bukkit.getLogger().info("[V10Lift] Closing the database connection for " + dbName + ".db!");
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
this.source.close();
}
}

View file

@ -0,0 +1,296 @@
package nl.SBDeveloper.V10Lift.sbutils;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.function.BiConsumer;
/**
* Update class for SBDevelopment
*
* @author Stijn [SBDeveloper]
* @version 2.1 [19-11-2021] - This class supports both the v2 Spiget and v2 SBDUpdate API
*
* <p>&copy; Stijn Bannink [stijnbannink23@gmail.com] - All rights reserved.</p>
* @since 05-03-2020
*/
public class UpdateManager {
private static final JsonParser parser = new JsonParser();
private static final String SPIGOT_API = "https://api.spiget.org/v2/resources/%s/versions/latest";
private static final String SPIGOT_DOWNLOAD = "https://api.spiget.org/v2/resources/%s/download";
private static final String SBDPLUGINS_API = "https://updates.sbdplugins.nl/api/v2/plugins/%d";
private static final String SBDPLUGINS_DOWNLOAD = "https://updates.sbdplugins.nl/api/v2/download/%d";
private final Plugin plugin;
private final Version currentVersion;
private final int resourceID;
private final CheckType type;
private final String license;
private BiConsumer<VersionResponse, Version> versionResponse;
private BiConsumer<DownloadResponse, String> downloadResponse;
/**
* Construct a new UpdateManager for Spigot
*
* @param plugin The javaplugin (Main class)
* @param resourceID The resourceID on spigot/sbdplugins
*/
public UpdateManager(Plugin plugin, int resourceID) {
this.plugin = plugin;
this.currentVersion = new Version(plugin.getDescription().getVersion());
this.resourceID = resourceID;
this.type = CheckType.SPIGOT;
this.license = null;
}
/**
* Construct a new UpdateManager for SBDPlugins
*
* @param plugin The javaplugin (Main class)
* @param resourceID The resourceID on spigot/sbdplugins
* @param license The license for the download
*/
public UpdateManager(Plugin plugin, int resourceID, String license) {
this.plugin = plugin;
this.currentVersion = new Version(plugin.getDescription().getVersion());
this.resourceID = resourceID;
this.type = CheckType.SBDPLUGINS;
this.license = license;
}
/**
* Handle the response given by check();
*
* @param versionResponse The response
* @return The updatemanager
*/
public UpdateManager handleResponse(BiConsumer<VersionResponse, Version> versionResponse) {
this.versionResponse = versionResponse;
return this;
}
public UpdateManager handleDownloadResponse(BiConsumer<DownloadResponse, String> downloadResponse) {
this.downloadResponse = downloadResponse;
return this;
}
/**
* Check for a new version
*/
public void check() {
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
try {
BufferedReader in = null;
if (type == CheckType.SPIGOT) {
HttpsURLConnection con = (HttpsURLConnection) new URL(String.format(SPIGOT_API, this.resourceID)).openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else if (type == CheckType.SBDPLUGINS) {
HttpsURLConnection con = (HttpsURLConnection) new URL(String.format(SBDPLUGINS_API, this.resourceID)).openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
}
if (in == null) return;
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String version = parser.parse(response.toString()).getAsJsonObject().get(type == CheckType.SPIGOT ? "name" : "version").getAsString();
if (version == null) return;
Version onlineVersion = new Version(version);
VersionResponse verRes = this.currentVersion.check(onlineVersion);
Bukkit.getScheduler().runTask(this.plugin, () -> this.versionResponse.accept(verRes, onlineVersion));
} catch (IOException | NullPointerException e) {
e.printStackTrace();
Bukkit.getScheduler().runTask(this.plugin, () -> this.versionResponse.accept(VersionResponse.UNAVAILABLE, null));
}
});
}
public void runUpdate() {
File pluginFile = getPluginFile(); // /plugins/XXX.jar
if (pluginFile == null) {
this.downloadResponse.accept(DownloadResponse.ERROR, null);
Bukkit.getLogger().info("Pluginfile is null");
return;
}
File updateFolder = Bukkit.getUpdateFolderFile();
if (!updateFolder.exists()) {
if (!updateFolder.mkdirs()) {
this.downloadResponse.accept(DownloadResponse.ERROR, null);
Bukkit.getLogger().info("Updatefolder doesn't exists, and can't be made");
return;
}
}
final File updateFile = new File(updateFolder, pluginFile.getName());
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
ReadableByteChannel channel;
try {
//https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java
int response;
InputStream stream;
HttpsURLConnection connection;
if (type == CheckType.SBDPLUGINS) {
connection = (HttpsURLConnection) new URL(String.format(SBDPLUGINS_DOWNLOAD, this.resourceID)).openConnection();
String urlParameters = "license=" + license + "&port=" + Bukkit.getPort();
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(postData);
wr.close();
} else {
connection = (HttpsURLConnection) new URL(String.format(SPIGOT_DOWNLOAD, this.resourceID)).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
}
response = connection.getResponseCode();
stream = connection.getInputStream();
if (response != 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine;
StringBuilder responsestr = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
responsestr.append(inputLine);
}
in.close();
throw new RuntimeException("Download returned status #" + response, new Throwable(responsestr.toString()));
}
channel = Channels.newChannel(stream);
} catch (IOException e) {
Bukkit.getScheduler().runTask(this.plugin, () -> this.downloadResponse.accept(DownloadResponse.ERROR, null));
e.printStackTrace();
return;
}
FileChannel fileChannel = null;
try {
FileOutputStream fosForDownloadedFile = new FileOutputStream(updateFile);
fileChannel = fosForDownloadedFile.getChannel();
fileChannel.transferFrom(channel, 0, Long.MAX_VALUE);
} catch (IOException e) {
Bukkit.getScheduler().runTask(this.plugin, () -> this.downloadResponse.accept(DownloadResponse.ERROR, null));
e.printStackTrace();
return;
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException ioe) {
System.out.println("Error while closing response body channel");
}
}
if (fileChannel != null) {
try {
fileChannel.close();
} catch (IOException ioe) {
System.out.println("Error while closing file channel for downloaded file");
}
}
}
Bukkit.getScheduler().runTask(this.plugin, () -> this.downloadResponse.accept(DownloadResponse.DONE, updateFile.getPath()));
});
}
private File getPluginFile() {
if (!(this.plugin instanceof JavaPlugin)) {
return null;
}
try {
Method method = JavaPlugin.class.getDeclaredMethod("getFile");
method.setAccessible(true);
return (File) method.invoke(this.plugin);
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Could not get plugin file", e);
}
}
private enum CheckType {
SPIGOT, SBDPLUGINS
}
public enum VersionResponse {
LATEST, //Latest version
FOUND_NEW, //Newer available
THIS_NEWER, //Local version is newer?
UNAVAILABLE //Error
}
public enum DownloadResponse {
DONE, ERROR, UNAVAILABLE
}
public static class Version {
private final String version;
private Version(String version) {
if (version == null)
throw new IllegalArgumentException("Version can not be null");
if (!version.matches("[0-9]+(\\.[0-9]+)*"))
throw new IllegalArgumentException("Invalid version format");
this.version = version;
}
public final String get() {
return this.version;
}
private VersionResponse check(Version that) {
String[] thisParts = this.get().split("\\.");
String[] thatParts = that.get().split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
for (int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0;
if (thisPart < thatPart)
return VersionResponse.FOUND_NEW;
if (thisPart > thatPart)
return VersionResponse.THIS_NEWER;
}
return VersionResponse.LATEST;
}
}
}

View file

@ -0,0 +1,73 @@
package nl.SBDeveloper.V10Lift.sbutils;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
public class YamlFile {
private final String name;
private FileConfiguration fileConfiguration;
private File file;
public YamlFile(String name) {
this.name = name;
if (!V10LiftPlugin.getInstance().getDataFolder().exists()) {
if (!V10LiftPlugin.getInstance().getDataFolder().mkdir()) {
Bukkit.getLogger().severe("[ActionFoto] Couldn't generate the pluginfolder!");
return;
}
}
this.file = new File(V10LiftPlugin.getInstance().getDataFolder(), name + ".yml");
if (!this.file.exists()) {
try {
if (!this.file.createNewFile()) {
Bukkit.getLogger().severe("[ActionFoto] Couldn't generate the " + name + ".yml!");
return;
}
Bukkit.getLogger().info("[ActionFoto] Generating the " + name + ".yml!");
} catch (IOException e) {
Bukkit.getLogger().severe("[ActionFoto] Couldn't generate the " + name + ".yml!");
return;
}
}
this.fileConfiguration = YamlConfiguration.loadConfiguration(this.file);
}
public void loadDefaults() {
Reader defConfigStream1 = new InputStreamReader(Objects.requireNonNull(V10LiftPlugin.getInstance().getResource(name + ".yml"), "Resource is null"), StandardCharsets.UTF_8);
YamlConfiguration defConfig1 = YamlConfiguration.loadConfiguration(defConfigStream1);
getFile().setDefaults(defConfig1);
getFile().options().copyDefaults(true);
saveFile();
}
public File getJavaFile() {
return this.file;
}
public FileConfiguration getFile() {
return this.fileConfiguration;
}
public void saveFile() {
try {
this.fileConfiguration.save(this.file);
} catch (IOException e) {
Bukkit.getLogger().severe("[ActionFoto] Couldn't save the " + name + ".yml!");
}
}
public void reloadConfig() {
this.fileConfiguration = YamlConfiguration.loadConfiguration(this.file);
}
}

View file

@ -0,0 +1,4 @@
/**
* The package with all the SBDevelopment utils
*/
package nl.SBDeveloper.V10Lift.sbutils;

View file

@ -0,0 +1,97 @@
package nl.SBDeveloper.V10Lift.utils;
import nl.SBDeveloper.V10Lift.V10LiftPlugin;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConfigUtil {
/* Helps building the messages */
/**
* Get a message from the config.yml
*
* @param path The path to look for
* @return The message
*/
@Nonnull
public static String getConfigText(@Nonnull String path) {
return ChatColor.translateAlternateColorCodes('&', Objects.requireNonNull(V10LiftPlugin.getSConfig().getFile().getString(path), "Message " + path + " not found in config.yml!"));
}
/**
* Send a message from the messages.yml without variables
*
* @param p The commandsender to send it to
* @param path The path to look for
*/
public static void sendMessage(CommandSender p, @Nonnull String path) {
if (V10LiftPlugin.getMessages().getFile().get(path) == null) {
throw new NullPointerException("Message " + path + " not found in messages.yml!");
}
if (V10LiftPlugin.getMessages().getFile().isList(path)) {
//Multi line message
for (String message : V10LiftPlugin.getMessages().getFile().getStringList(path)) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', message));
}
} else {
//Single line message
p.sendMessage(ChatColor.translateAlternateColorCodes('&', Objects.requireNonNull(V10LiftPlugin.getMessages().getFile().getString(path))));
}
}
/**
* Get a message from the messages.yml with variables
*
* @param p The commandsender to send it to
* @param path The path to look for
* @param replacement The replacements - key: %Name% = value: TheName
*/
public static void sendMessage(CommandSender p, @Nonnull String path, Map<String, String> replacement) {
if (V10LiftPlugin.getMessages().getFile().get(path) == null) {
throw new NullPointerException("Message " + path + " not found in messages.yml!");
}
if (V10LiftPlugin.getMessages().getFile().isList(path)) {
//Multi line message
for (String message : V10LiftPlugin.getMessages().getFile().getStringList(path)) {
p.sendMessage(formatMessage(message, replacement));
}
} else {
//Single line message
String message = V10LiftPlugin.getMessages().getFile().getString(path);
p.sendMessage(formatMessage(message, replacement));
}
}
@Nonnull
private static String formatMessage(String message, @Nonnull Map<String, String> replacement) {
Map<String, String> fixedMap = new HashMap<>();
for (Map.Entry<String, String> ent : replacement.entrySet()) {
fixedMap.put(ent.getKey().replaceAll("%", ""), ent.getValue());
}
Pattern pattern = Pattern.compile("%(.*?)%");
Matcher matcher = pattern.matcher(Objects.requireNonNull(message));
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
String repl = fixedMap.get(matcher.group(1));
builder.append(message, i, matcher.start());
if (repl == null)
builder.append(matcher.group(0));
else
builder.append(repl);
i = matcher.end();
}
builder.append(message.substring(i));
return ChatColor.translateAlternateColorCodes('&', builder.toString());
}
}

View file

@ -0,0 +1,89 @@
package nl.SBDeveloper.V10Lift.utils;
import com.cryptomorin.xseries.XMaterial;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class DirectionUtil {
@Nullable
public static BlockFace getDirection(@Nonnull Block block) {
if (!XMaterial.isNewVersion()) return null;
if (block.getBlockData() instanceof org.bukkit.block.data.Directional) {
org.bukkit.block.data.Directional dir = (org.bukkit.block.data.Directional) block.getBlockData();
return dir.getFacing();
}
return null;
}
public static void setDirection(@Nonnull Block block, BlockFace blockFace) {
if (!XMaterial.isNewVersion()) return;
if (blockFace != null && block.getBlockData() instanceof org.bukkit.block.data.Directional) {
org.bukkit.block.data.BlockData bd = block.getBlockData();
org.bukkit.block.data.Directional dir = (org.bukkit.block.data.Directional) bd;
dir.setFacing(blockFace);
block.setBlockData(bd);
}
}
@Nullable
public static String getBisected(@Nonnull Block block) {
if (!XMaterial.isNewVersion()) return null;
if (block.getBlockData() instanceof org.bukkit.block.data.Bisected) {
org.bukkit.block.data.Bisected bis = (org.bukkit.block.data.Bisected) block.getBlockData();
return bis.getHalf().toString();
}
return null;
}
public static void setBisected(@Nonnull Block block, String bisected) {
if (!XMaterial.isNewVersion()) return;
if (bisected != null && block.getBlockData() instanceof org.bukkit.block.data.Bisected) {
org.bukkit.block.data.Bisected.Half half;
try {
half = org.bukkit.block.data.Bisected.Half.valueOf(bisected);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
org.bukkit.block.data.BlockData bd = block.getBlockData();
org.bukkit.block.data.Bisected bis = (org.bukkit.block.data.Bisected) bd;
bis.setHalf(half);
block.setBlockData(bd);
}
}
@Nullable
public static String getSlabType(@Nonnull Block block) {
if (!XMaterial.isNewVersion()) return null;
if (block.getBlockData() instanceof org.bukkit.block.data.type.Slab) {
org.bukkit.block.data.type.Slab slab = (org.bukkit.block.data.type.Slab) block.getBlockData();
return slab.getType().toString();
}
return null;
}
public static void setSlabType(@Nonnull Block block, String slabtype) {
if (!XMaterial.isNewVersion()) return;
if (slabtype != null && block.getBlockData() instanceof org.bukkit.block.data.type.Slab) {
org.bukkit.block.data.type.Slab.Type type;
try {
type = org.bukkit.block.data.type.Slab.Type.valueOf(slabtype);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
org.bukkit.block.data.BlockData bd = block.getBlockData();
org.bukkit.block.data.type.Slab slab = (org.bukkit.block.data.type.Slab) bd;
slab.setType(type);
block.setBlockData(bd);
}
}
}

View file

@ -0,0 +1,173 @@
package nl.SBDeveloper.V10Lift.utils;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.Bisected;
import javax.annotation.Nonnull;
/* Openable codes sponsored by MrWouter <3 */
public class DoorUtil {
/**
* Open a door, with 1.12.x- and 1.13.x+ support
* @param b The block (door)
* @return true if opened, false if not opened
*/
public static boolean openDoor(@Nonnull Block b) {
if (b.getType() == XMaterial.IRON_DOOR.parseMaterial()) XSound.BLOCK_IRON_DOOR_OPEN.play(b.getLocation());
if (b.getType().toString().contains("DOOR") && b.getType() != XMaterial.IRON_DOOR.parseMaterial()) XSound.BLOCK_WOODEN_DOOR_OPEN.play(b.getLocation());
if (b.getType().toString().contains("GATE")) XSound.BLOCK_FENCE_GATE_OPEN.play(b.getLocation());
if (XMaterial.isNewVersion()) {
//1.13+
org.bukkit.block.data.BlockData blockData = b.getBlockData();
if (isOpenable(b)) {
org.bukkit.block.data.Openable op = (org.bukkit.block.data.Openable) blockData;
if (op.isOpen()) {
return false;
}
op.setOpen(true);
b.setBlockData(blockData);
return true;
}
} else {
//1.12-
BlockState state = b.getState();
if (isOpenable(b)) {
org.bukkit.material.Openable openable = (org.bukkit.material.Openable) state.getData();
if (openable.isOpen()) {
return false;
}
openable.setOpen(true);
state.setData((org.bukkit.material.MaterialData) openable);
state.update();
return true;
}
}
return false;
}
/**
* Close a door, with 1.12.x- and 1.13.x+ support
* @param b The block (door)
* @return true if opened, false if not opened
*/
public static boolean closeDoor(@Nonnull Block b) {
if (b.getType() == XMaterial.IRON_DOOR.parseMaterial()) XSound.BLOCK_IRON_DOOR_CLOSE.play(b.getLocation());
if (b.getType().toString().contains("DOOR") && b.getType() != XMaterial.IRON_DOOR.parseMaterial()) XSound.BLOCK_WOODEN_DOOR_CLOSE.play(b.getLocation());
if (b.getType().toString().contains("GATE")) XSound.BLOCK_FENCE_GATE_CLOSE.play(b.getLocation());
if (XMaterial.isNewVersion()) {
//1.13+
org.bukkit.block.data.BlockData blockData = b.getBlockData();
if (isOpenable(b)) {
org.bukkit.block.data.Openable op = (org.bukkit.block.data.Openable) blockData;
if (!op.isOpen()) {
return false;
}
op.setOpen(false);
b.setBlockData(blockData);
return true;
}
} else {
//1.12-
BlockState state = b.getState();
if (isOpenable(b)) {
org.bukkit.material.Openable openable = (org.bukkit.material.Openable) state.getData();
if (!openable.isOpen()) {
return false;
}
openable.setOpen(false);
state.setData((org.bukkit.material.MaterialData) openable);
state.update();
return true;
}
}
return false;
}
/**
* Check if a block instanceof Openable
*
* @param b The block
* @return true if Openable, false if not
*/
public static boolean isOpenable(Block b) {
if (b == null) {
return false;
}
if (XMaterial.isNewVersion()) {
//1.13+
return b.getBlockData() instanceof org.bukkit.block.data.Openable;
} else {
//1.12-
return b.getState().getData() instanceof org.bukkit.material.Openable;
}
}
/**
* Get the lower location of a door
*
* @param block The location of a door
* @return The lower location of a door
*/
public static Location getLowerLocationOfDoor(@Nonnull Block block) {
if (!isDoor(block)) return block.getLocation();
if (XMaterial.isNewVersion()) {
//1.13+
org.bukkit.block.data.type.Door door = (org.bukkit.block.data.type.Door) block.getBlockData();
Location lower;
if (door.getHalf() == Bisected.Half.TOP) {
lower = block.getLocation().subtract(0, 1, 0);
} else {
if (!door.isOpen()) {
lower = block.getLocation().subtract(0, 1, 0);
if (isOpenable(lower.getBlock()))
return lower;
else return block.getLocation();
}
lower = block.getLocation();
}
return lower;
} else {
//1.12-
org.bukkit.material.Door door = (org.bukkit.material.Door) block.getState().getData();
Location lower;
if (door.isTopHalf()) {
lower = block.getLocation().subtract(0, 1, 0);
} else {
if (!door.isOpen()) {
lower = block.getLocation().subtract(0, 1, 0);
if (isOpenable(lower.getBlock()))
return lower;
else return block.getLocation();
}
lower = block.getLocation();
}
return lower;
}
}
/**
* Check if a block instanceof Door
*
* @param b The block
* @return true if a Door, false if not
*/
public static boolean isDoor(Block b) {
if (b == null) {
return false;
}
if (XMaterial.isNewVersion()) {
//1.13+
return b.getBlockData() instanceof org.bukkit.block.data.type.Door;
} else {
//1.12-
return b.getState().getData() instanceof org.bukkit.material.Door;
}
}
}

View file

@ -0,0 +1,4 @@
/**
* The package with all the utils
*/
package nl.SBDeveloper.V10Lift.utils;