3
0
Fork 0

Fixed a lot of issues, removed sbutil, ...

This commit is contained in:
stijnb1234 2020-06-01 13:43:13 +02:00
parent 95cf389a69
commit 328b8d670f
29 changed files with 841 additions and 149 deletions

View file

@ -0,0 +1,257 @@
package nl.sbdeveloper.themeparkplus;
import club.minnced.discord.webhook.WebhookClient;
import club.minnced.discord.webhook.WebhookClientBuilder;
import net.milkbowl.vault.economy.Economy;
import nl.sbdeveloper.themeparkplus.commands.TPPCMD;
import nl.sbdeveloper.themeparkplus.listeners.AntiFreerunListener;
import nl.sbdeveloper.themeparkplus.listeners.DirectionalGateListener;
import nl.sbdeveloper.themeparkplus.listeners.FastpassListeners;
import nl.sbdeveloper.themeparkplus.listeners.StatusChangeListener;
import nl.sbdeveloper.themeparkplus.managers.DBManager;
import nl.sbdeveloper.themeparkplus.sbutils.UpdateManager;
import nl.sbdeveloper.themeparkplus.util.LGUtil;
import nl.sbdeveloper.themeparkplus.util.License;
import nl.sbdeveloper.themeparkplus.sbutils.YamlFile;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Objects;
public final class ThemeParkPlus extends JavaPlugin {
private static ThemeParkPlus instance;
private static YamlFile config;
private static DBManager data;
private static YamlFile messages;
private static Economy econ = null;
private static WebhookClient webhookClient;
private int configVersion = 2;
@Override
public void onEnable() {
instance = this;
Bukkit.getLogger().info("[ThemeParkPlus] -------------------------------");
Bukkit.getLogger().info("[ThemeParkPlus] ThemeParkPlus v" + this.getDescription().getVersion());
Bukkit.getLogger().info("[ThemeParkPlus] Made by SBDeveloper");
Bukkit.getLogger().info("[ThemeParkPlus] ");
Bukkit.getLogger().info("[ThemeParkPlus] Loading Files...");
config = new YamlFile("config");
config.loadDefaults();
data = new DBManager("data");
messages = new YamlFile("messages");
messages.loadDefaults();
Reader defConfigStream = new InputStreamReader(Objects.requireNonNull(getResource("config.yml")), StandardCharsets.UTF_8);
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
config.getFile().setDefaults(defConfig);
config.getFile().options().copyDefaults(true);
config.saveFile();
if (!config.getFile().contains("Version") || Objects.equals(config.getFile().getString("Version"), "")) {
config.getFile().set("Version", configVersion);
config.saveFile();
}
if (!Objects.equals(config.getFile().getString("Version"), String.valueOf(configVersion))) {
Bukkit.getLogger().info("[ThemeParkPlus] Updating outdated config...");
updateConfig();
}
Bukkit.getLogger().info("[ThemeParkPlus] Checking license...");
if (config.getFile().contains("License")) {
Bukkit.getLogger().info("[ThemeParkPlus] Licence code: " + config.getFile().getString("License"));
} else {
Bukkit.getLogger().severe("[ThemeParkPlus] Licence code unknown! Please change the config.yml!");
return;
}
new License(this, "TP", config.getFile().getString("License"));
if (getSConfig().getFile().getBoolean("UpdateChecker.Enabled")) {
UpdateManager updateManager = new UpdateManager(this, 7, UpdateManager.CheckType.SBDPLUGINS);
updateManager.handleResponse((versionResponse, version) -> {
if (versionResponse == UpdateManager.VersionResponse.FOUND_NEW) {
Bukkit.getLogger().warning("[ThemeParkPlus] There is a new version available! Curent: " + this.getDescription().getVersion() + " New: " + version);
if (getSConfig().getFile().getBoolean("UpdateChecker.Download")) {
Bukkit.getLogger().info("[ThemeParkPlus] Trying to download the update...");
updateManager.handleDownloadResponse((downloadResponse, fileName) -> {
if (downloadResponse == UpdateManager.DownloadResponse.DONE) {
Bukkit.getLogger().info("[ThemeParkPlus] Update downloaded! If you restart your server, it will be loaded. Filename: " + fileName);
} else if (downloadResponse == UpdateManager.DownloadResponse.ERROR) {
Bukkit.getLogger().severe("[ThemeParkPlus] Something went wrong when trying downloading the latest version.");
} else if (downloadResponse == UpdateManager.DownloadResponse.UNAVAILABLE) {
Bukkit.getLogger().warning("[ThemeParkPlus] Unable to download the latest version. The paid plugins will support this feature soon.");
}
}).runUpdate();
}
} else if (versionResponse == UpdateManager.VersionResponse.LATEST) {
Bukkit.getLogger().info("[ThemeParkPlus] You are running the latest version [" + this.getDescription().getVersion() + "]!");
} else if (versionResponse == UpdateManager.VersionResponse.UNAVAILABLE) {
Bukkit.getLogger().severe("[ThemeParkPlus] Unable to perform an update check.");
}
}).check();
}
if (Bukkit.getPluginManager().isPluginEnabled("ThemePark")) {
Bukkit.getLogger().severe("[ThemeParkPlus] Missing ThemePark! Please install it first.");
getServer().getPluginManager().disablePlugin(this);
return;
}
if (Bukkit.getPluginManager().isPluginEnabled("WorldEdit")) {
Bukkit.getLogger().severe("[ThemeParkPlus] Missing WorldEdit! Please install it first.");
getServer().getPluginManager().disablePlugin(this);
return;
}
if (!setupEconomy()) {
Bukkit.getLogger().severe("[ThemeParkPlus] Missing Vault! Please install it first.");
getServer().getPluginManager().disablePlugin(this);
return;
}
Bukkit.getLogger().info("[ThemeParkPlus] Loading commands...");
Objects.requireNonNull(getCommand("themeparkplus"), "Couldn't read command from plugin.yml!").setExecutor(new TPPCMD());
Bukkit.getLogger().info("[ThemeParkPlus] Loading listeners...");
Bukkit.getPluginManager().registerEvents(new DirectionalGateListener(), this);
Bukkit.getPluginManager().registerEvents(new FastpassListeners(), this);
if (getSConfig().getFile().getBoolean("AntiFreerun.Enabled")) {
Bukkit.getPluginManager().registerEvents(new AntiFreerunListener(), this);
}
if (getSConfig().getFile().getBoolean("DiscordWebhook.Enabled")) {
String URL = getSConfig().getFile().getString("DiscordWebhook.WebhookURL");
if (URL != null) {
Bukkit.getPluginManager().registerEvents(new StatusChangeListener(), this);
Bukkit.getLogger().info("[ThemeParkPlus] Loading Discord webhook...");
WebhookClientBuilder builder = new WebhookClientBuilder(URL);
builder.setThreadFactory((job) -> {
Thread thread = new Thread(job);
thread.setName("Hello");
thread.setDaemon(true);
return thread;
});
builder.setWait(true);
webhookClient = builder.build();
} else {
Bukkit.getLogger().severe("[ThemeParkPlus] Couldn't load the webhook builder! The URL is null.");
}
}
Bukkit.getLogger().info("[ThemeParkPlus] Loading Lamp & Gate utils...");
try {
new LGUtil();
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
Bukkit.getLogger().severe("[ThemeParkPlus] Couldn't find classes for Lamp & Gate util. The plugin won't work as intended.");
}
Bukkit.getLogger().info("[ThemeParkPlus] Loading data...");
try {
data.load();
} catch (SQLException e) {
e.printStackTrace();
Bukkit.getLogger().severe("[ThemeParkPlus] Couldn't load data! Something went wrong.");
}
Bukkit.getLogger().info("[ThemeParkPlus] Plugin enabled!");
Bukkit.getLogger().info("[ThemeParkPlus] -------------------------------");
}
@Override
public void onDisable() {
Bukkit.getLogger().info("[ThemeParkPlus] Saving data to data file...");
data.save();
if (getSConfig().getFile().getBoolean("DiscordWebhook.Enabled")) {
Bukkit.getLogger().info("[ThemeParkPlus] Breaking discord connection...");
webhookClient.close();
}
Bukkit.getLogger().info("[ThemeParkPlus] Plugin disabled!");
instance = null;
}
public static ThemeParkPlus getInstance() {
return instance;
}
public static YamlFile getSConfig() {
return config;
}
public static DBManager getData() {
return data;
}
public static YamlFile getMessages() {
return messages;
}
public static Economy getEconomy() {
return econ;
}
public static WebhookClient getWebhookClient() {
return webhookClient;
}
private boolean setupEconomy() {
if (getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return false;
}
econ = rsp.getProvider();
return econ != null;
}
private void updateConfig() {
HashMap< String, Object > newConfig = getConfigVals();
for (String var: config.getFile().getKeys(false)) {
newConfig.remove(var);
}
if (newConfig.size() != 0) {
for (String key: newConfig.keySet()) {
config.getFile().set(key, newConfig.get(key));
}
config.getFile().set("Version", configVersion);
config.saveFile();
}
}
@NotNull
private HashMap<String, Object> getConfigVals() {
HashMap<String, Object> var = new HashMap <>();
Reader defConfigStream = new InputStreamReader(Objects.requireNonNull(getResource("config.yml")), StandardCharsets.UTF_8);
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
for (String key : defConfig.getKeys(false)) {
var.put(key, defConfig.get(key));
}
return var;
}
}

View file

@ -0,0 +1,94 @@
package nl.sbdeveloper.themeparkplus.api;
import de.tr7zw.changeme.nbtapi.NBTItem;
import me.paradoxpixel.themepark.api.attraction.Attraction;
import nl.sbdeveloper.themeparkplus.ThemeParkPlus;
import nl.sbdeveloper.themeparkplus.api.objects.Gate;
import nl.sbdeveloper.themeparkplus.util.ConfigUtil;
import nl.sbdeveloper.themeparkplus.util.XMaterial;
import org.bukkit.Location;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class PlusAPI {
private static HashMap<Location, Gate> gates = new HashMap<>();
/**
* Add a gate
*
* @param gate The gate
*/
public static void addGate(Gate gate) {
gates.put(gate.getLoc(), gate);
}
/**
* Remove a gate
*
* @param gate The gate
*/
public static void removeGate(@NotNull Gate gate) {
gates.remove(gate.getLoc());
}
/**
* Check if a location is a gate
*
* @param loc The location
* @return true/false
*/
public static boolean isGate(Location loc) {
return gates.containsKey(loc);
}
/**
* Get a gate by the location
*
* @param loc The location
* @return The gate
*/
public static Gate getGate(Location loc) {
return gates.get(loc);
}
/**
* Get all the gates
*
* @return Map with location and gate
*/
public static HashMap<Location, Gate> getGates() {
return gates;
}
/**
* Get the ticket itemstack
*
* @param att The attraction
*
* @return The ticket as ItemStack
*/
@Nullable
public static ItemStack getFastpassTicket(Attraction att) {
String ticketName = ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("Fastpass.Item.DisplayName"));
ItemStack ticket = XMaterial.PAPER.parseItem();
if (ticket == null) return null;
ItemMeta meta = ticket.getItemMeta();
if (meta == null) return null;
meta.setDisplayName(ticketName);
List<String> ticketLores = ConfigUtil.getLore("Fastpass.Item.Lore", Collections.singletonMap("%ridename%", att.getName()));
meta.setLore(ticketLores);
ticket.setItemMeta(meta);
NBTItem item = new NBTItem(ticket);
item.setString("RideID", att.getId());
ticket = item.getItem();
return ticket;
}
}

View file

@ -0,0 +1,23 @@
package nl.sbdeveloper.themeparkplus.api.enums;
import org.bukkit.block.BlockFace;
public enum WalkingDirection {
/**
* The walking direction. Removed combinations because those can't be used in the commands.
*/
NORTH(BlockFace.NORTH),
EAST(BlockFace.EAST),
SOUTH(BlockFace.SOUTH),
WEST(BlockFace.WEST);
private BlockFace blockFace;
WalkingDirection(BlockFace blockFace) {
this.blockFace = blockFace;
}
public BlockFace getBlockFace() {
return blockFace;
}
}

View file

@ -0,0 +1,81 @@
package nl.sbdeveloper.themeparkplus.api.objects;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import nl.sbdeveloper.themeparkplus.api.enums.WalkingDirection;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
@Getter @Setter @NoArgsConstructor @AllArgsConstructor
public class Gate {
private String world;
private int x;
private int y;
private int z;
/* If max count */
private boolean hasMaxCount = false;
private int passedCount = 0;
private int maxCount;
/* If directional */
private boolean isDirectional = false;
private WalkingDirection direction;
/**
* Constructor for a directional gate.
*
* @param loc The gate location
* @param direction The walking direction
*/
public Gate(@NotNull Location loc, WalkingDirection direction) {
this.world = Objects.requireNonNull(loc.getWorld(), "World is null!").getName();
this.x = loc.getBlockX();
this.y = loc.getBlockY();
this.z = loc.getBlockZ();
this.isDirectional = true;
this.direction = direction;
}
/**
* Constructor for a max count gate.
*
* @param loc The gate location
* @param maxCount The max player count
*/
public Gate(@NotNull Location loc, int maxCount) {
this.world = Objects.requireNonNull(loc.getWorld(), "World is null!").getName();
this.x = loc.getBlockX();
this.y = loc.getBlockY();
this.z = loc.getBlockZ();
this.hasMaxCount = true;
this.maxCount = maxCount;
}
/**
* Constructor for a directional max count gate.
*
* @param loc The gate location
* @param maxCount The max player count
* @param direction The walking direction
*/
public Gate(@NotNull Location loc, int maxCount, WalkingDirection direction) {
this.world = Objects.requireNonNull(loc.getWorld(), "World is null!").getName();
this.x = loc.getBlockX();
this.y = loc.getBlockY();
this.z = loc.getBlockZ();
this.hasMaxCount = true;
this.isDirectional = true;
this.maxCount = maxCount;
this.direction = direction;
}
public Location getLoc() {
return new Location(Bukkit.getWorld(this.world), this.x, this.y, this.z);
}
}

View file

@ -0,0 +1,18 @@
package nl.sbdeveloper.themeparkplus.api.objects;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDateTime;
import java.util.UUID;
/** @deprecated Please don't use! It's not implemented yet. */
@Getter @Setter @NoArgsConstructor @AllArgsConstructor
public class MalfunctionReport {
private String rideID;
private UUID reporterUUID;
private LocalDateTime reportDate;
private String reason;
}

View file

@ -0,0 +1,38 @@
package nl.sbdeveloper.themeparkplus.api.objects;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import com.sk89q.worldedit.regions.AbstractRegion;
import com.sk89q.worldedit.regions.Region;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.bukkit.Location;
import java.util.ArrayList;
@NoArgsConstructor @AllArgsConstructor
public class WaitingRow {
@Getter @Setter private String rideID;
@Getter @Setter private Region region;
@Getter @Setter private int waitingPlayers = 0;
@Getter @Setter private int waitingTimeMinutes = 0;
private ArrayList<Location> signLocations = new ArrayList<>();
public WaitingRow(String rideID, Region region) {
this.rideID = rideID;
this.region = region;
}
public ArrayList<Location> getSignLocations() {
return signLocations;
}
public void addSignLocation(Location loc) {
this.signLocations.add(loc);
}
public void removeSignLocation(Location loc) {
this.signLocations.remove(loc);
}
}

View file

@ -0,0 +1,387 @@
package nl.sbdeveloper.themeparkplus.commands;
import me.paradoxpixel.themepark.api.API;
import me.paradoxpixel.themepark.api.attraction.Attraction;
import nl.sbdeveloper.themeparkplus.ThemeParkPlus;
import nl.sbdeveloper.themeparkplus.api.PlusAPI;
import nl.sbdeveloper.themeparkplus.api.enums.WalkingDirection;
import nl.sbdeveloper.themeparkplus.api.objects.Gate;
import nl.sbdeveloper.themeparkplus.util.ConfigUtil;
import nl.sbdeveloper.themeparkplus.util.Cuboid;
import nl.sbdeveloper.themeparkplus.util.LGUtil;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
public class TPPCMD implements CommandExecutor {
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {
if (args.length == 0) {
return helpCommand(sender);
} else if (args[0].equalsIgnoreCase("info") && args.length == 1) {
return infoCommand(sender);
} else if (args[0].equalsIgnoreCase("opengate") && args.length == 5) {
if (!sender.hasPermission("tpp.opengate")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
return openGate(sender, args, 0, null);
} else if (args[0].equalsIgnoreCase("opengate") && args.length == 6) {
if (!sender.hasPermission("tpp.opengate")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
try {
int amount = Integer.parseInt(args[5]);
return openGate(sender, args, amount, null);
} catch (NumberFormatException ex) {
try {
WalkingDirection dir = WalkingDirection.valueOf(args[5]);
return openGate(sender, args, 0, dir);
} catch (Exception ex2) {
sender.sendMessage(ConfigUtil.getMessage("Gates.UnknownDirAndAmount"));
return true;
}
}
} else if (args[0].equalsIgnoreCase("opengate") && args.length == 7) {
if (!sender.hasPermission("tpp.opengate")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
int amount;
WalkingDirection dir;
try {
amount = Integer.parseInt(args[5]);
} catch (NumberFormatException ex) {
sender.sendMessage(ConfigUtil.getMessage("General.IncorrectAmount"));
ex.printStackTrace();
return true;
}
try {
dir = WalkingDirection.valueOf(args[6]);
} catch (Exception ex2) {
sender.sendMessage(ConfigUtil.getMessage("Gates.UnknownDir"));
return true;
}
return openGate(sender, args, amount, dir);
} else if (args[0].equalsIgnoreCase("closegate") && args.length == 5) {
if (!sender.hasPermission("tpp.closegate")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
return closeGate(sender, args);
} else if (args[0].equalsIgnoreCase("lampon") && args.length == 5) {
if (!sender.hasPermission("tpp.lampon")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
return lampTurnOnCommand(sender, args, 0);
} else if (args[0].equalsIgnoreCase("lampon") && args.length == 6) {
if (!sender.hasPermission("tpp.lampon")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
int amount;
try {
amount = Integer.parseInt(args[5]);
} catch (NumberFormatException ex) {
sender.sendMessage(ConfigUtil.getMessage("General.IncorrectAmount"));
return true;
}
return lampTurnOnCommand(sender, args, amount);
} else if (args[0].equalsIgnoreCase("lampoff") && args.length == 5) {
if (!sender.hasPermission("tpp.lampoff")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
return lampTurnOffCommand(sender, args);
} else if (args[0].equalsIgnoreCase("lampson") && args.length == 8) {
if (!sender.hasPermission("tpp.lampson")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
return lampsTurnOnCommand(sender, args, 0);
} else if (args[0].equalsIgnoreCase("lampson") && args.length == 9) {
if (!sender.hasPermission("tpp.lampson")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
int amount;
try {
amount = Integer.parseInt(args[8]);
} catch (NumberFormatException ex) {
sender.sendMessage(ConfigUtil.getMessage("General.IncorrectAmount"));
return true;
}
return lampsTurnOnCommand(sender, args, amount);
} else if (args[0].equalsIgnoreCase("lampsoff") && args.length == 8) {
if (!sender.hasPermission("tpp.lampsoff")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
return lampsTurnOffCommand(sender, args);
} else if (args[0].equalsIgnoreCase("givefpticket") && (args.length == 2 || args.length == 3)) {
if (!sender.hasPermission("tpp.givefpticket")) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return true;
}
return giveFPTicketCommand(sender, args);
}
return helpCommand(sender);
}
private boolean giveFPTicketCommand(CommandSender sender, String[] args) {
if (args.length == 2 && !(sender instanceof Player)) {
sender.sendMessage(ConfigUtil.getMessage("General.NoPlayer"));
return true;
}
if (!API.isAttraction(args[1])) {
sender.sendMessage(ConfigUtil.getMessage("Fastpass.UnknownRide", Collections.singletonMap("%ridename%", args[1])));
return true;
}
Attraction att = API.getAttraction(args[1]);
Player target;
if (args.length == 3) {
target = Bukkit.getPlayer(args[2]);
if (target == null) {
sender.sendMessage(ConfigUtil.getMessage("Fastpass.UnknownPlayer", Collections.singletonMap("%playername%", args[2])));
return true;
}
} else {
target = (Player) sender;
}
ItemStack ticket = PlusAPI.getFastpassTicket(att);
if (ticket == null) return true;
target.getInventory().addItem(ticket);
sender.sendMessage(ConfigUtil.getMessage("Fastpass.Given"));
return true;
}
private boolean infoCommand(@NotNull CommandSender sender) {
sender.sendMessage("§1==================================");
sender.sendMessage("§6ThemeParkPlus plugin made by §aSBDeveloper");
sender.sendMessage("§6Version: " + ThemeParkPlus.getInstance().getDescription().getVersion());
sender.sendMessage("§6Type /themeparkplus help for more information!");
sender.sendMessage("§1==================================");
return true;
}
private boolean helpCommand(@NotNull CommandSender sender) {
sender.sendMessage("§8ThemeParkPlus commands:");
sender.sendMessage("§6/themeparkplus info§f: Gives you information about the plugin.");
sender.sendMessage("§6/themeparkplus help§f: Gives you this help page.");
sender.sendMessage(" ");
sender.sendMessage("§6/themeparkplus opengate <World> <X> <Y> <Z> [Player Count/Direction] [Direction]§f: Open a gate!");
sender.sendMessage("§6/themeparkplus closegate <World> <X> <Y> <Z>§f: Close a gate!");
sender.sendMessage(" ");
sender.sendMessage("§6/themeparkplus lampon <World> <X> <Y> <Z> [Seconds on] §f: Turn a lamp on!");
sender.sendMessage("§6/themeparkplus lampoff <World> <X> <Y> <Z>§f: Turn a lamp off!");
sender.sendMessage("§6/themeparkplus lampson <World> <X1> <Y1> <Z1> <X2> <Y2> <Z2> [Seconds on]§f: Turn multiple lamps on.");
sender.sendMessage("§6/themeparkplus lampsoff <World> <X1> <Y1> <Z1> <X2> <Y2> <Z2>§f: Turn multiple lamps off.");
sender.sendMessage(" ");
sender.sendMessage("§6/themeparkplus givefpticket <RideID> [Player]§f: Give yourself or someone else a Fastpass ticket (for free).");
return true;
}
private boolean openGate(CommandSender sender, @NotNull String[] args, int amount, WalkingDirection dir) {
World bworld = Bukkit.getWorld(args[1]);
double bx = Double.parseDouble(args[2]);
double by = Double.parseDouble(args[3]);
double bz = Double.parseDouble(args[4]);
Location loc = new Location(bworld, bx, by, bz);
Gate gate = null;
if (amount != 0 && dir == null) {
//GEEN ONEWAY MET WEL AANTAL
gate = new Gate(loc, amount);
} else if (amount == 0 && dir != null) {
//ONE WAY ZONDER AANTAL
gate = new Gate(loc, dir);
} else if (amount != 0) {
//WEL ONE WAY MET WEL AANTAL
gate = new Gate(loc, amount, dir);
}
if (gate != null) {
PlusAPI.addGate(gate);
}
Block b = loc.getBlock();
if (LGUtil.isOpenable(b)) {
if (LGUtil.isOpen(b)) {
sender.sendMessage(ConfigUtil.getMessage("Gates.AlreadyOpen"));
return true;
}
if (gate != null && gate.isDirectional()) {
LGUtil.openGate(b, gate.getDirection().getBlockFace());
} else {
LGUtil.openGate(b);
}
} else {
sender.sendMessage(ConfigUtil.getMessage("Gates.NoGate"));
return true;
}
if (amount == 0) {
if (ConfigUtil.sendConsole(sender)) sender.sendMessage(ConfigUtil.getMessage("Gates.Opened"));
} else {
if (ConfigUtil.sendConsole(sender)) sender.sendMessage(ConfigUtil.getMessage("Gates.OpenedAmount", Collections.singletonMap("%amount%", String.valueOf(amount))));
}
return true;
}
private boolean closeGate(CommandSender sender, @NotNull String[] args) {
World bworld = Bukkit.getWorld(args[1]);
double bx = Double.parseDouble(args[2]);
double by = Double.parseDouble(args[3]);
double bz = Double.parseDouble(args[4]);
Location loc = new Location(bworld, bx, by, bz);
Block b = loc.getBlock();
if (LGUtil.isOpenable(b)) {
Gate gate = PlusAPI.getGate(loc);
if (gate != null) {
PlusAPI.removeGate(gate);
}
if (!LGUtil.isOpen(b)) {
sender.sendMessage(ConfigUtil.getMessage("Gates.AlreadyClosed"));
return true;
}
LGUtil.closeGate(b);
} else {
sender.sendMessage(ConfigUtil.getMessage("Gates.NoGate"));
return true;
}
if (ConfigUtil.sendConsole(sender)) sender.sendMessage(ConfigUtil.getMessage("Gates.Closed"));
return true;
}
private boolean lampTurnOnCommand(CommandSender sender, @NotNull String[] args, int secOn) {
World bworld = Bukkit.getWorld(args[1]);
double bx = Double.parseDouble(args[2]);
double by = Double.parseDouble(args[3]);
double bz = Double.parseDouble(args[4]);
Location loc = new Location(bworld, bx, by, bz);
Block block = loc.getBlock();
if (secOn == 0) {
if (!LGUtil.zetLampAan(block)) {
sender.sendMessage(ConfigUtil.getMessage("Lamps.ErrorOn"));
return true;
}
if (ConfigUtil.sendConsole(sender)) sender.sendMessage(ConfigUtil.getMessage("Lamps.TurnedOn"));
} else {
if (!LGUtil.zetLampAan(block)) {
sender.sendMessage(ConfigUtil.getMessage("Lamps.ErrorOn"));
return true;
}
Bukkit.getScheduler().runTaskLater(ThemeParkPlus.getInstance(), () -> LGUtil.zetLampUit(block), secOn * 20);
if (ConfigUtil.sendConsole(sender)) sender.sendMessage(ConfigUtil.getMessage("Lamps.TurnedOnSec", Collections.singletonMap("%sec%", String.valueOf(secOn))));
}
return true;
}
private boolean lampTurnOffCommand(CommandSender sender, @NotNull String[] args) {
World bworld = Bukkit.getWorld(args[1]);
double bx = Double.parseDouble(args[2]);
double by = Double.parseDouble(args[3]);
double bz = Double.parseDouble(args[4]);
Location loc = new Location(bworld, bx, by, bz);
if (!LGUtil.zetLampUit(loc.getBlock())) {
sender.sendMessage(ConfigUtil.getMessage("Lamps.ErrorOn"));
return true;
}
if (ConfigUtil.sendConsole(sender)) sender.sendMessage(ConfigUtil.getMessage("Lamps.TurnedOff"));
return true;
}
private boolean lampsTurnOnCommand(CommandSender sender, @NotNull String[] args, int secOn) {
World bworld = Bukkit.getWorld(args[1]);
double bx = Double.parseDouble(args[2]);
double by = Double.parseDouble(args[3]);
double bz = Double.parseDouble(args[4]);
double bx2 = Double.parseDouble(args[5]);
double by2 = Double.parseDouble(args[6]);
double bz2 = Double.parseDouble(args[7]);
Location loc = new Location(bworld, bx, by, bz);
Location loc2 = new Location(bworld, bx2, by2, bz2);
Cuboid cub = new Cuboid(loc, loc2);
if (secOn == 0) {
Bukkit.getScheduler().runTaskAsynchronously(ThemeParkPlus.getInstance(), () -> cub.getBlocks().forEach(block -> {
if (block.getType().name().contains("REDSTONE_LAMP")) Bukkit.getScheduler().runTask(ThemeParkPlus.getInstance(), () -> LGUtil.zetLampAan(block));
}));
if (ConfigUtil.sendConsole(sender)) sender.sendMessage(ConfigUtil.getMessage("Lamps.TurnedOn"));
} else {
Bukkit.getScheduler().runTaskAsynchronously(ThemeParkPlus.getInstance(), () -> cub.getBlocks().forEach(block -> {
if (block.getType().name().contains("REDSTONE_LAMP")) Bukkit.getScheduler().runTask(ThemeParkPlus.getInstance(), () -> LGUtil.zetLampAan(block));
}));
Bukkit.getScheduler().runTaskLaterAsynchronously(ThemeParkPlus.getInstance(), () -> cub.getBlocks().forEach(block -> {
if (block.getType().name().contains("REDSTONE_LAMP")) Bukkit.getScheduler().runTask(ThemeParkPlus.getInstance(), () -> LGUtil.zetLampUit(block));
}), secOn * 20);
if (ConfigUtil.sendConsole(sender)) sender.sendMessage(ConfigUtil.getMessage("Lamps.TurnedOnSec", Collections.singletonMap("%sec%", String.valueOf(secOn))));
}
return true;
}
private boolean lampsTurnOffCommand(@NotNull CommandSender sender, @NotNull String[] args) {
World bworld = Bukkit.getWorld(args[1]);
double bx = Double.parseDouble(args[2]);
double by = Double.parseDouble(args[3]);
double bz = Double.parseDouble(args[4]);
double bx2 = Double.parseDouble(args[5]);
double by2 = Double.parseDouble(args[6]);
double bz2 = Double.parseDouble(args[7]);
Location loc = new Location(bworld, bx, by, bz);
Location loc2 = new Location(bworld, bx2, by2, bz2);
Cuboid cub = new Cuboid(loc, loc2);
Bukkit.getScheduler().runTaskAsynchronously(ThemeParkPlus.getInstance(), () -> cub.getBlocks().forEach(block -> {
if (block.getType().name().contains("REDSTONE_LAMP")) Bukkit.getScheduler().runTask(ThemeParkPlus.getInstance(), () -> LGUtil.zetLampUit(block));
}));
if (ConfigUtil.sendConsole(sender)) sender.sendMessage(ConfigUtil.getMessage("Lamps.TurnedOff"));
return true;
}
}

View file

@ -0,0 +1,22 @@
package nl.sbdeveloper.themeparkplus.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.NotNull;
/**
* Anti-Freerun effect
*/
public class AntiFreerunListener implements Listener {
@EventHandler
public void onJoin(@NotNull PlayerJoinEvent e) {
Player p = e.getPlayer();
if (!p.hasPermission("tpp.bypassantifreerun")) {
p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 1000000, -2, false, false));
}
}
}

View file

@ -0,0 +1,74 @@
package nl.sbdeveloper.themeparkplus.listeners;
import nl.sbdeveloper.themeparkplus.api.PlusAPI;
import nl.sbdeveloper.themeparkplus.api.enums.WalkingDirection;
import nl.sbdeveloper.themeparkplus.api.objects.Gate;
import nl.sbdeveloper.themeparkplus.util.ConfigUtil;
import nl.sbdeveloper.themeparkplus.util.DirectionUtil;
import nl.sbdeveloper.themeparkplus.util.LGUtil;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.jetbrains.annotations.NotNull;
/**
* Gate move listeners (directional and count checks)
*/
public class DirectionalGateListener implements Listener {
@EventHandler
public void onWalkThroughFenceGate(@NotNull PlayerMoveEvent e) {
if (e.getTo() != null
&& (e.getFrom().getBlockX() != e.getTo().getBlockX()
|| e.getFrom().getBlockY() != e.getTo().getBlockY()
|| e.getFrom().getBlockZ() != e.getTo().getBlockZ())) {
Location oldLoc = e.getFrom();
Location newLoc = e.getTo();
Block oldBlock = oldLoc.getBlock();
if (oldBlock.getType().name().contains("FENCE_GATE")) {
Gate gate = PlusAPI.getGate(oldBlock.getLocation());
if (gate == null) return;
if (!gate.isDirectional()) {
if (gate.getMaxCount() != 0) {
if (gate.getPassedCount() + 1 == gate.getMaxCount()) {
if (LGUtil.isOpenable(oldBlock)) {
LGUtil.closeGate(oldBlock);
} else {
PlusAPI.removeGate(gate);
return;
}
PlusAPI.removeGate(gate);
} else {
gate.setPassedCount(gate.getPassedCount() + 1);
}
}
} else {
WalkingDirection loopdir = DirectionUtil.getDirection(oldLoc.getBlockX(), oldLoc.getBlockZ(), newLoc.getBlockX(), newLoc.getBlockZ());
if (loopdir == null) return;
if (loopdir.getBlockFace() != gate.getDirection().getBlockFace()) {
e.getPlayer().teleport(oldLoc);
e.getPlayer().sendMessage(ConfigUtil.getMessage("Gates.WrongDir"));
return;
}
if (gate.getMaxCount() != 0) {
if (gate.getPassedCount() + 1 == gate.getMaxCount()) {
if (LGUtil.isOpenable(oldBlock)) {
LGUtil.closeGate(oldBlock);
} else {
PlusAPI.removeGate(gate);
return;
}
PlusAPI.removeGate(gate);
} else {
gate.setPassedCount(gate.getPassedCount() + 1);
}
}
}
}
}
}
}

View file

@ -0,0 +1,134 @@
package nl.sbdeveloper.themeparkplus.listeners;
import de.tr7zw.changeme.nbtapi.NBTItem;
import me.paradoxpixel.themepark.api.API;
import me.paradoxpixel.themepark.api.attraction.Attraction;
import me.paradoxpixel.themepark.api.attraction.component.Status;
import nl.sbdeveloper.themeparkplus.ThemeParkPlus;
import nl.sbdeveloper.themeparkplus.api.PlusAPI;
import nl.sbdeveloper.themeparkplus.util.ConfigUtil;
import nl.sbdeveloper.themeparkplus.util.LGUtil;
import nl.sbdeveloper.themeparkplus.util.XMaterial;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.HashMap;
/**
* Fastpass machine & scanner signs
*/
public class FastpassListeners implements Listener {
@EventHandler
public void onSignClick(@NotNull PlayerInteractEvent e) {
if (e.getClickedBlock() == null || e.getAction() != Action.RIGHT_CLICK_BLOCK || !(e.getClickedBlock().getState() instanceof Sign) || e.getHand() != EquipmentSlot.HAND) return;
String mLineOne = ChatColor.stripColor(ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("Fastpass.MachineSign.Row1")));
String mLineTwo = ChatColor.stripColor(ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("Fastpass.MachineSign.Row2")));
String sLineOne = ChatColor.stripColor(ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("Fastpass.ScannerSign.Row1")));
String sLineTwo = ChatColor.stripColor(ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("Fastpass.ScannerSign.Row2")));
Sign sign = (Sign) e.getClickedBlock().getState();
if (!ChatColor.stripColor(sign.getLine(0)).equalsIgnoreCase(mLineOne) && !ChatColor.stripColor(sign.getLine(0)).equalsIgnoreCase(sLineOne)) return;
if (ChatColor.stripColor(sign.getLine(1)).equalsIgnoreCase(mLineTwo)) {
//Buy a ticket
String attID = sign.getLine(2);
if (!API.isAttraction(attID)) return;
Attraction att = API.getAttraction(attID);
double price;
try {
price = Double.parseDouble(sign.getLine(3));
} catch (NumberFormatException ex) {
return;
}
ItemStack ticket = PlusAPI.getFastpassTicket(att);
if (ticket == null) return;
if (ThemeParkPlus.getEconomy().getBalance(e.getPlayer()) < price) {
e.getPlayer().sendMessage(ConfigUtil.getMessage("Fastpass.NotEnoughMoney"));
return;
}
for (ItemStack content : e.getPlayer().getInventory().getContents()) {
if (content == null || content.getType() == null || content.getType() == Material.AIR) continue;
NBTItem nbtContent = new NBTItem(content);
if (content.getType() == XMaterial.PAPER.parseMaterial() && content.hasItemMeta() && nbtContent.hasKey("RideID") && nbtContent.getString("RideID").equalsIgnoreCase(attID)) {
e.getPlayer().sendMessage(ConfigUtil.getMessage("Fastpass.AlreadyHaveTicket"));
return;
}
}
ThemeParkPlus.getEconomy().withdrawPlayer(e.getPlayer(), price);
e.getPlayer().getInventory().addItem(ticket);
e.getPlayer().updateInventory();
HashMap<String, String> vars = new HashMap<>();
vars.put("%ridename%", att.getName());
vars.put("%price%", String.format("%.2f", price));
e.getPlayer().sendMessage(ConfigUtil.getMessage("Fastpass.Bought", vars));
} else if (ChatColor.stripColor(sign.getLine(1)).equalsIgnoreCase(sLineTwo)) {
//Scan a ticket
if (!API.isAttraction(sign.getLine(2))) {
e.getPlayer().sendMessage(ConfigUtil.getMessage("Fastpass.UnknownRide", Collections.singletonMap("%ridename%", sign.getLine(2))));
return;
}
Attraction att = API.getAttraction(sign.getLine(2));
ItemStack content = e.getPlayer().getInventory().getItemInMainHand();
if (content.getType() == Material.AIR
|| !content.hasItemMeta()) {
e.getPlayer().sendMessage(ConfigUtil.getMessage("Fastpass.NoTicket"));
return;
}
NBTItem nbtContent = new NBTItem(content);
if (!nbtContent.hasKey("RideID")) {
e.getPlayer().sendMessage(ConfigUtil.getMessage("Fastpass.NoTicket"));
return;
}
if (att.getStatus() != Status.OPEN && att.getStatus() != Status.ACTIVE) {
e.getPlayer().sendMessage(ConfigUtil.getMessage("Fastpass.RideClosed"));
return;
}
try {
String[] locationString = sign.getLine(3).split(":");
int x = Integer.parseInt(locationString[0]);
int y = Integer.parseInt(locationString[1]);
int z = Integer.parseInt(locationString[2]);
Block b = e.getPlayer().getWorld().getBlockAt(x, y, z);
if (LGUtil.isOpenable(b)) {
LGUtil.openGate(b);
Bukkit.getScheduler().scheduleSyncDelayedTask(ThemeParkPlus.getInstance(), () -> LGUtil.closeGate(b), 60L);
} else {
Location tpLoc = new Location(e.getPlayer().getWorld(), x, y, z, e.getPlayer().getLocation().getYaw(), e.getPlayer().getLocation().getPitch());
e.getPlayer().teleport(tpLoc);
}
e.getPlayer().getInventory().remove(e.getPlayer().getInventory().getItemInMainHand());
e.getPlayer().updateInventory();
e.getPlayer().sendMessage(ConfigUtil.getMessage("Fastpass.Redeemed"));
} catch (NumberFormatException | ArrayIndexOutOfBoundsException ex) {
e.getPlayer().sendMessage(ConfigUtil.getMessage("Fastpass.IncorrectSign"));
}
}
}
}

View file

@ -0,0 +1,69 @@
package nl.sbdeveloper.themeparkplus.listeners;
import me.paradoxpixel.themepark.api.API;
import nl.sbdeveloper.themeparkplus.ThemeParkPlus;
import nl.sbdeveloper.themeparkplus.api.objects.WaitingRow;
import nl.sbdeveloper.themeparkplus.util.ConfigUtil;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
/**
* Sign setup listener
*/
public class SignListeners implements Listener {
/*
[ThemeParkPlus]
XXXX
<RideName>
XXXX
*/
@EventHandler
public void onCreate(@NotNull SignChangeEvent e) {
Player p = e.getPlayer();
String[] lines = e.getLines();
//Only check themeparkplus signs!
if (!lines[0].equalsIgnoreCase("[ThemeParkPlus]")) return;
if (!p.hasPermission("tpp.fastpass.create")) {
p.sendMessage(ConfigUtil.getMessage("General.NoPermission"));
return;
}
if (!API.isAttraction(e.getLine(2))) {
p.sendMessage(ConfigUtil.getMessage("Fastpass.UnknownRide", Collections.singletonMap("ridename", e.getLine(2))));
return;
}
String mLineOne = ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("Fastpass.MachineSign.Row1"));
String mLineTwo = ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("Fastpass.MachineSign.Row2"));
String sLineOne = ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("Fastpass.ScannerSign.Row1"));
String sLineTwo = ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("Fastpass.ScannerSign.Row2"));
String wrLineOne = ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("WaitingRow.Sign.Row1"));
String wrLineTwo = ConfigUtil.makecolored(ThemeParkPlus.getSConfig().getFile().getString("WaitingRow.Sign.Row2"));
if (lines[1].equalsIgnoreCase("Machine") && !lines[2].isEmpty() && !lines[3].isEmpty()) {
e.setLine(0, mLineOne);
e.setLine(1, mLineTwo);
} else if (lines[1].equalsIgnoreCase("Scanner") && !lines[2].isEmpty() && !lines[3].isEmpty()) {
e.setLine(0, sLineOne);
e.setLine(1, sLineTwo);
} else if (lines[1].equalsIgnoreCase("WaitingRow") && !lines[2].isEmpty() && !lines[3].isEmpty()) {
e.setLine(0, wrLineOne);
e.setLine(1, wrLineTwo);
//AND SETUP
WaitingRow row = new WaitingRow();
p.sendMessage(ConfigUtil.getMessage("WaitingRow.SignCreated"));
} else {
p.sendMessage(ConfigUtil.getMessage("General.IncorrectSign"));
}
}
}

View file

@ -0,0 +1,44 @@
package nl.sbdeveloper.themeparkplus.listeners;
import club.minnced.discord.webhook.send.WebhookEmbed;
import club.minnced.discord.webhook.send.WebhookEmbedBuilder;
import me.paradoxpixel.themepark.api.attraction.component.Status;
import me.paradoxpixel.themepark.api.event.attraction.StatusChangeEvent;
import me.paradoxpixel.themepark.attraction.status.StatusManager;
import nl.sbdeveloper.themeparkplus.ThemeParkPlus;
import nl.sbdeveloper.themeparkplus.util.ConfigUtil;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;
/**
* Status change listener for discord webhook
*/
public class StatusChangeListener implements Listener {
@EventHandler
public void onStatusChange(@NotNull StatusChangeEvent e) {
if (e.getStatusAfter() != Status.GLOBAL) {
String title = ThemeParkPlus.getSConfig().getFile().getString("DiscordWebhook.Embed.Title");
if (title == null) return;
String rideName = ChatColor.stripColor(ConfigUtil.makecolored(e.getAttraction().getName()));
String statusAfter = ChatColor.stripColor(ConfigUtil.makecolored(StatusManager.getName(e.getStatusAfter())));
title = title.replaceAll("%RideName%", rideName);
String copy = ThemeParkPlus.getSConfig().getFile().getString("DiscordWebhook.Embed.Copyright");
String copyimg = ThemeParkPlus.getSConfig().getFile().getString("DiscordWebhook.Embed.CopyrightImage");
Integer color = ThemeParkPlus.getSConfig().getFile().getInt("DiscordWebhook.Embed.Colors." + e.getStatusAfter().toString());
if (copy == null || copyimg == null) return;
WebhookEmbed embed = new WebhookEmbedBuilder()
.setTitle(new WebhookEmbed.EmbedTitle(title, ""))
.setFooter(new WebhookEmbed.EmbedFooter(copy, copyimg))
.setColor(color)
.addField(new WebhookEmbed.EmbedField(false, rideName, statusAfter))
.build();
ThemeParkPlus.getWebhookClient().send(embed);
}
}
}

View file

@ -0,0 +1,81 @@
package nl.sbdeveloper.themeparkplus.managers;
import com.google.gson.Gson;
import nl.sbdeveloper.themeparkplus.api.PlusAPI;
import nl.sbdeveloper.themeparkplus.api.objects.Gate;
import nl.sbdeveloper.themeparkplus.sbutils.LocationSerializer;
import nl.sbdeveloper.themeparkplus.sbutils.SQLiteDB;
import org.bukkit.Location;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
public class DBManager {
private static SQLiteDB data;
private static Connection con;
public DBManager(String name) {
data = new SQLiteDB(name);
try {
con = data.getConnection();
String query = "CREATE TABLE IF NOT EXISTS gates (gateLocation varchar(255) NOT NULL, gateData blob NOT NULL, UNIQUE (gateLocation))";
PreparedStatement statement = con.prepareStatement(query);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void load() throws SQLException {
/* Load gates */
String query = "SELECT * FROM gates";
PreparedStatement statement = con.prepareStatement(query);
ResultSet gateSet = statement.executeQuery();
while (gateSet.next()) {
//Loading a gates...
byte[] blob = gateSet.getBytes("gateData");
String json = new String(blob);
Gson gson = new Gson();
Gate gate = gson.fromJson(json, Gate.class);
PlusAPI.addGate(gate);
}
}
public void save() {
for (Map.Entry<Location, Gate> entry : PlusAPI.getGates().entrySet()) {
Gson gson = new Gson();
byte[] blob = gson.toJson(entry.getValue()).getBytes();
try {
String query = "INSERT INTO gates (gateLocation, gateData) VALUES (?, ?)";
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, LocationSerializer.serialize(entry.getKey()));
statement.setBytes(2, blob);
statement.executeUpdate();
} catch (SQLException ignored) {}
try {
String query2 = "UPDATE gates SET gateData = ? WHERE gateLocation = ?";
PreparedStatement statement2 = con.prepareStatement(query2);
statement2.setBytes(1, blob);
statement2.setString(2, LocationSerializer.serialize(entry.getKey()));
statement2.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void closeConnection() {
data.closeSource();
}
}

View file

@ -0,0 +1,81 @@
package nl.sbdeveloper.themeparkplus.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,90 @@
package nl.sbdeveloper.themeparkplus.sbutils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import nl.sbdeveloper.themeparkplus.ThemeParkPlus;
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 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(ThemeParkPlus.getInstance().getDataFolder(), dbName + ".db");
if (!dbFile.exists()) {
try {
Bukkit.getLogger().info("[ThemeParkPlus] Generating the " + dbName + ".db!");
if (!dbFile.createNewFile()) {
Bukkit.getLogger().severe("[ThemeParkPlus] Couldn't generate the " + dbName + ".db!");
return;
}
} catch (IOException e) {
Bukkit.getLogger().severe("[ThemeParkPlus] Couldn't generate the " + dbName + ".db!");
return;
}
}
HikariConfig config = new HikariConfig();
config.setPoolName("ThemeParkPlus");
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("[ThemeParkPlus] Closing the database connection for " + dbName + ".db!");
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
this.source.close();
}
}

View file

@ -0,0 +1,205 @@
package nl.sbdeveloper.themeparkplus.sbutils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.function.BiConsumer;
/**
* Update class for SBDevelopment
* @author Stijn [SBDeveloper]
* @since 05-03-2020
* @version 1.2
*
* © Stijn Bannink <stijnbannink23@gmail.com> - All rights reserved.
*/
public class UpdateManager {
private static final String SPIGOT_API = "https://api.spigotmc.org/legacy/update.php?resource=%d";
/* Port 4000 is now legacy, 4443 has a SSL cert */
/* As of 24-05-2020, using the legacy port because of SSL errors */
private static final String SBDPLUGINS_API = "http://updates.sbdplugins.nl:4000/api/resources/%d";
private static final String RESOURCE_DOWNLOAD = "http://api.spiget.org/v2/resources/%s/download";
private Plugin plugin;
private double currentVersion;
private int resourceID;
private CheckType type;
private BiConsumer<VersionResponse, Double> versionResponse;
private BiConsumer<DownloadResponse, String> downloadResponse;
/**
* Construct a new UpdateManager
*
* @param plugin The javaplugin (Main class)
* @param resourceID The resourceID on spigot/sbdplugins
* @param type The check type
*/
public UpdateManager(@NotNull Plugin plugin, int resourceID, CheckType type) {
this.plugin = plugin;
this.currentVersion = Double.parseDouble(plugin.getDescription().getVersion());
this.resourceID = resourceID;
this.type = type;
}
/**
* Handle the response given by check();
* @param versionResponse The response
* @return The updatemanager
*/
public UpdateManager handleResponse(BiConsumer<VersionResponse, Double> 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) {
HttpURLConnection con = (HttpURLConnection) 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 version = null;
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JsonParser parser = new JsonParser();
if (type == CheckType.SPIGOT) {
JsonArray array = parser.parse(response.toString()).getAsJsonArray();
version = array.get(0).getAsJsonObject().get("name").getAsString();
} else if (type == CheckType.SBDPLUGINS) {
JsonObject object = parser.parse(response.toString()).getAsJsonObject();
version = object.get("data").getAsJsonObject().get("version").getAsString();
}
if (version == null) return;
boolean latestVersion = Double.parseDouble(version) >= this.currentVersion;
double versionDouble = Double.parseDouble(version);
Bukkit.getScheduler().runTask(this.plugin, () -> this.versionResponse.accept(latestVersion ? VersionResponse.LATEST : VersionResponse.FOUND_NEW, latestVersion ? this.currentVersion : versionDouble));
} 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);
return;
}
File updateFolder = Bukkit.getUpdateFolderFile();
if (!updateFolder.exists()) {
if (!updateFolder.mkdirs()) {
this.downloadResponse.accept(DownloadResponse.ERROR, null);
return;
}
}
final File updateFile = new File(updateFolder, pluginFile.getName());
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
if (this.type == CheckType.SBDPLUGINS) {
Bukkit.getScheduler().runTask(this.plugin, () -> this.downloadResponse.accept(DownloadResponse.UNAVAILABLE, null));
return;
}
ReadableByteChannel channel;
try {
//https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java
HttpURLConnection connection = (HttpURLConnection) new URL(String.format(RESOURCE_DOWNLOAD, this.resourceID)).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Download returned status #" + connection.getResponseCode());
}
channel = Channels.newChannel(connection.getInputStream());
} catch (IOException e) {
Bukkit.getScheduler().runTask(this.plugin, () -> this.downloadResponse.accept(DownloadResponse.ERROR, null));
return;
}
try {
FileOutputStream output = new FileOutputStream(updateFile);
output.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);
output.flush();
output.close();
} catch (IOException e) {
Bukkit.getScheduler().runTask(this.plugin, () -> this.downloadResponse.accept(DownloadResponse.ERROR, null));
return;
}
Bukkit.getScheduler().runTask(this.plugin, () -> this.downloadResponse.accept(DownloadResponse.DONE, updateFile.getPath()));
});
}
@Nullable
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);
}
}
public enum CheckType {
SPIGOT, SBDPLUGINS
}
public enum VersionResponse {
LATEST, FOUND_NEW, UNAVAILABLE
}
public enum DownloadResponse {
DONE, ERROR, UNAVAILABLE
}
}

View file

@ -0,0 +1,71 @@
package nl.sbdeveloper.themeparkplus.sbutils;
import nl.sbdeveloper.themeparkplus.ThemeParkPlus;
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 {
//SBYamlFile file = new SBYamlFile(this, "data");
private FileConfiguration fileConfiguration;
private File file;
private String name;
public YamlFile(String name) {
this.name = name;
if (!ThemeParkPlus.getInstance().getDataFolder().exists()) {
if (!ThemeParkPlus.getInstance().getDataFolder().mkdir()) {
Bukkit.getLogger().severe("[ThemeParkPlus] Couldn't generate the pluginfolder!");
return;
}
}
this.file = new File(ThemeParkPlus.getInstance().getDataFolder(), name + ".yml");
if (!this.file.exists()) {
try {
if (!this.file.createNewFile()) {
Bukkit.getLogger().severe("[ThemeParkPlus] Couldn't generate the " + name + ".yml!");
return;
}
Bukkit.getLogger().info("[ThemeParkPlus] Generating the " + name + ".yml!");
} catch (IOException e) {
Bukkit.getLogger().severe("[ThemeParkPlus] Couldn't generate the " + name + ".yml!");
return;
}
}
this.fileConfiguration = YamlConfiguration.loadConfiguration(this.file);
}
public void loadDefaults() {
Reader defConfigStream1 = new InputStreamReader(Objects.requireNonNull(ThemeParkPlus.getInstance().getResource(name + ".yml"), "Resource is null"), StandardCharsets.UTF_8);
YamlConfiguration defConfig1 = YamlConfiguration.loadConfiguration(defConfigStream1);
getFile().setDefaults(defConfig1);
getFile().options().copyDefaults(true);
saveFile();
}
public FileConfiguration getFile() {
return this.fileConfiguration;
}
public void saveFile() {
try {
this.fileConfiguration.save(this.file);
} catch (IOException e) {
Bukkit.getLogger().severe("[ThemeParkPlus] Couldn't save the " + name + ".yml!");
}
}
public void reloadConfig() {
this.fileConfiguration = YamlConfiguration.loadConfiguration(this.file);
}
}

View file

@ -0,0 +1,54 @@
package nl.sbdeveloper.themeparkplus.util;
import nl.sbdeveloper.themeparkplus.ThemeParkPlus;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ConfigUtil {
@NotNull
public static String makecolored(String str) {
return ChatColor.translateAlternateColorCodes('&', str);
}
@NotNull
public static List<String> getLore(String path, Map<String, String> vars) {
ArrayList<String> response = new ArrayList<>();
for (String str : ThemeParkPlus.getSConfig().getFile().getStringList(path)) {
for (Map.Entry<String, String> entry : vars.entrySet()) {
str = str.replaceAll(entry.getKey(), entry.getValue());
}
response.add(makecolored(str));
}
return response;
}
@NotNull
public static String getMessage(String path) {
return getMessage(path, new HashMap<>());
}
@NotNull
public static String getMessage(String path, Map<String, String> vars) {
String message = ThemeParkPlus.getMessages().getFile().getString(path);
if (message == null) return "";
for (Map.Entry<String, String> entry : vars.entrySet()) {
message = message.replaceAll(entry.getKey(), entry.getValue());
}
return makecolored(message);
}
public static boolean sendConsole(CommandSender sender) {
if (sender instanceof ConsoleCommandSender) {
return ThemeParkPlus.getSConfig().getFile().getBoolean("MessageInConsole");
} else {
return true;
}
}
}

View file

@ -0,0 +1,177 @@
package nl.sbdeveloper.themeparkplus.util;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class Cuboid implements Cloneable, ConfigurationSerializable, Iterable<Block> {
protected String worldName;
protected final Vector minimumPoint, maximumPoint;
public Cuboid(@NotNull Cuboid cuboid) {
this(cuboid.worldName, cuboid.minimumPoint.getX(), cuboid.minimumPoint.getY(), cuboid.minimumPoint.getZ(), cuboid.maximumPoint.getX(), cuboid.maximumPoint.getY(), cuboid.maximumPoint.getZ());
}
public Cuboid(Location loc) {
this(loc, loc);
}
public Cuboid(Location loc1, Location loc2) {
if (loc1 != null && loc2 != null) {
if (loc1.getWorld() != null && loc2.getWorld() != null) {
if (!loc1.getWorld().getUID().equals(loc2.getWorld().getUID()))
throw new IllegalStateException("The 2 locations of the cuboid must be in the same world!");
} else {
throw new NullPointerException("One/both of the worlds is/are null!");
}
this.worldName = loc1.getWorld().getName();
double xPos1 = Math.min(loc1.getX(), loc2.getX());
double yPos1 = Math.min(loc1.getY(), loc2.getY());
double zPos1 = Math.min(loc1.getZ(), loc2.getZ());
double xPos2 = Math.max(loc1.getX(), loc2.getX());
double yPos2 = Math.max(loc1.getY(), loc2.getY());
double zPos2 = Math.max(loc1.getZ(), loc2.getZ());
this.minimumPoint = new Vector(xPos1, yPos1, zPos1);
this.maximumPoint = new Vector(xPos2, yPos2, zPos2);
} else {
throw new NullPointerException("One/both of the locations is/are null!");
}
}
public Cuboid(String worldName, double x1, double y1, double z1, double x2, double y2, double z2) {
if (worldName == null || Bukkit.getServer().getWorld(worldName) == null)
throw new NullPointerException("One/both of the worlds is/are null!");
this.worldName = worldName;
double xPos1 = Math.min(x1, x2);
double xPos2 = Math.max(x1, x2);
double yPos1 = Math.min(y1, y2);
double yPos2 = Math.max(y1, y2);
double zPos1 = Math.min(z1, z2);
double zPos2 = Math.max(z1, z2);
this.minimumPoint = new Vector(xPos1, yPos1, zPos1);
this.maximumPoint = new Vector(xPos2, yPos2, zPos2);
}
public boolean containsLocation(Location location) {
return location != null && location.getWorld().getName().equals(this.worldName) && location.toVector().isInAABB(this.minimumPoint, this.maximumPoint);
}
public boolean containsVector(Vector vector) {
return vector != null && vector.isInAABB(this.minimumPoint, this.maximumPoint);
}
public List<Block> getBlocks() {
List<Block> blockList = new ArrayList<>();
World world = this.getWorld();
if (world != null) {
for (int x = this.minimumPoint.getBlockX(); x <= this.maximumPoint.getBlockX(); x++) {
for (int y = this.minimumPoint.getBlockY(); y <= this.maximumPoint.getBlockY() && y <= world.getMaxHeight(); y++) {
for (int z = this.minimumPoint.getBlockZ(); z <= this.maximumPoint.getBlockZ(); z++) {
blockList.add(world.getBlockAt(x, y, z));
}
}
}
}
return blockList;
}
public Location getLowerLocation() {
return this.minimumPoint.toLocation(this.getWorld());
}
public double getLowerX() {
return this.minimumPoint.getX();
}
public double getLowerY() {
return this.minimumPoint.getY();
}
public double getLowerZ() {
return this.minimumPoint.getZ();
}
public Location getUpperLocation() {
return this.maximumPoint.toLocation(this.getWorld());
}
public double getUpperX() {
return this.maximumPoint.getX();
}
public double getUpperY() {
return this.maximumPoint.getY();
}
public double getUpperZ() {
return this.maximumPoint.getZ();
}
public double getVolume() {
return (this.getUpperX() - this.getLowerX() + 1) * (this.getUpperY() - this.getLowerY() + 1) * (this.getUpperZ() - this.getLowerZ() + 1);
}
public World getWorld() {
World world = Bukkit.getServer().getWorld(this.worldName);
if (world == null) throw new NullPointerException("World '" + this.worldName + "' is not loaded.");
return world;
}
public void setWorld(World world) {
if (world != null) this.worldName = world.getName();
else throw new NullPointerException("The world cannot be null.");
}
@Override
public Cuboid clone() {
return new Cuboid(this);
}
@Override
public ListIterator<Block> iterator() {
return this.getBlocks().listIterator();
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> serializedCuboid = new HashMap<>();
serializedCuboid.put("worldName", this.worldName);
serializedCuboid.put("x1", this.minimumPoint.getX());
serializedCuboid.put("x2", this.maximumPoint.getX());
serializedCuboid.put("y1", this.minimumPoint.getY());
serializedCuboid.put("y2", this.maximumPoint.getY());
serializedCuboid.put("z1", this.minimumPoint.getZ());
serializedCuboid.put("z2", this.maximumPoint.getZ());
return serializedCuboid;
}
@Nullable
public static Cuboid deserialize(Map<String, Object> serializedCuboid) {
try {
String worldName = (String) serializedCuboid.get("worldName");
double xPos1 = (Double) serializedCuboid.get("x1");
double xPos2 = (Double) serializedCuboid.get("x2");
double yPos1 = (Double) serializedCuboid.get("y1");
double yPos2 = (Double) serializedCuboid.get("y2");
double zPos1 = (Double) serializedCuboid.get("z1");
double zPos2 = (Double) serializedCuboid.get("z2");
return new Cuboid(worldName, xPos1, yPos1, zPos1, xPos2, yPos2, zPos2);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}

View file

@ -0,0 +1,28 @@
package nl.sbdeveloper.themeparkplus.util;
import nl.sbdeveloper.themeparkplus.api.enums.WalkingDirection;
import org.jetbrains.annotations.Nullable;
public class DirectionUtil {
@Nullable
public static WalkingDirection getDirection(int xoud, int zoud, int xnieuw, int znieuw) {
int changeInX = xnieuw - xoud;
int changeInZ = znieuw - zoud;
if (changeInZ != 0 && changeInX == 0) {
if (changeInZ < 0) {
return WalkingDirection.NORTH;
} else {
return WalkingDirection.SOUTH;
}
} else if (changeInX != 0 && changeInZ == 0) {
if (changeInX < 0) {
return WalkingDirection.WEST;
} else {
return WalkingDirection.EAST;
}
}
return null;
}
}

View file

@ -0,0 +1,291 @@
package nl.sbdeveloper.themeparkplus.util;
import nl.sbdeveloper.themeparkplus.ThemeParkPlus;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class LGUtil {
private static List<Vector> offsets = new ArrayList<>();
private static List <Block> nearbyBlocks = new ArrayList<>();
private static boolean nieuweVersie = false;
private static Method getBlockDataMethod;
private static Method setBlockDataMethod;
private static Method getAsStringMethod;
private static Object lampAanData;
private static Object lampUitData;
public LGUtil() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
offsets.add(new Vector(1, 0, 0));
offsets.add(new Vector(-1, 0, 0));
offsets.add(new Vector(0, 1, 0));
offsets.add(new Vector(0, -1, 0));
offsets.add(new Vector(0, 0, 1));
offsets.add(new Vector(0, 0, -1));
Class<?> blockDataClass = Class.forName("org.bukkit.block.data.BlockData");
Method methodCreateBlockData = Bukkit.class.getMethod("createBlockData", String.class);
getBlockDataMethod = Block.class.getMethod("getBlockData");
setBlockDataMethod = Block.class.getMethod("setBlockData", blockDataClass,
Boolean.TYPE);
getAsStringMethod = blockDataClass.getMethod("getAsString");
lampAanData = methodCreateBlockData.invoke(null, "minecraft:redstone_lamp[lit=true]");
lampUitData = methodCreateBlockData.invoke(null, "minecraft:redstone_lamp[lit=false]");
nieuweVersie = true;
}
public static boolean zetLampAan(Block lampBlock) {
if (nieuweVersie) {
if ((isLamp(lampBlock)) && (!isAan(lampBlock))) {
setBlockData(lampBlock, lampAanData);
return true;
}
return false;
}
if (!isAan(lampBlock)) {
final Block neighbor = getNeighbor(lampBlock);
if (neighbor != null) {
BlockState neighborState = neighbor.getState();
try {
for (org.bukkit.util.Vector offset: offsets) {
Block neighborOfNeighbor = neighbor.getLocation().add(offset).getBlock();
if ((neighborOfNeighbor.getX() != lampBlock.getX()) || (neighborOfNeighbor.getY() != lampBlock.getY()) || (neighborOfNeighbor.getZ() != lampBlock.getZ())) {
nearbyBlocks.add(neighborOfNeighbor);
}
}
neighbor.setType(Material.REDSTONE_BLOCK);
} catch (Exception e) {
e.printStackTrace();
} finally {
neighborState.update(true, false);
Bukkit.getScheduler().runTaskLater(ThemeParkPlus.getInstance(), () -> {
for (Vector offset: offsets) {
Block neighborOfNeighbor = neighbor.getLocation().add(offset).getBlock();
nearbyBlocks.remove(neighborOfNeighbor);
}
}, 1L);
}
return true;
}
}
return false;
}
public static boolean zetLampUit(Block lampBlock) {
if (nieuweVersie) {
if ((isLamp(lampBlock)) && (isAan(lampBlock))) {
setBlockData(lampBlock, lampUitData);
return true;
}
return false;
}
if (isAan(lampBlock)) {
lampBlock.setType(Objects.requireNonNull(Material.matchMaterial(XMaterial.REDSTONE_LAMP.getLegacy()[0])));
return true;
}
return false;
}
public static boolean openGate(Block b) {
return openGate(b, getDirection(b));
}
public static boolean openGate(Block b, BlockFace openFace) {
if (nieuweVersie) {
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);
org.bukkit.block.data.Directional dir = (org.bukkit.block.data.Directional) blockData;
dir.setFacing(openFace);
b.setBlockData(blockData);
return true;
}
} else {
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();
org.bukkit.material.Directional dir = (org.bukkit.material.Directional) state.getData();
dir.setFacingDirection(openFace);
state.setData((org.bukkit.material.MaterialData) dir);
state.update();
return true;
}
}
return false;
}
public static boolean closeGate(Block b) {
if (nieuweVersie) {
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 {
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;
}
@Nullable
public static BlockFace getDirection(Block b) {
if (nieuweVersie) {
org.bukkit.block.data.BlockData blockData = b.getBlockData();
if (isOpenable(b)) {
org.bukkit.block.data.Directional dir = (org.bukkit.block.data.Directional) blockData;
return dir.getFacing();
}
} else {
BlockState state = b.getState();
if (isOpenable(b)) {
org.bukkit.material.Directional dir = (org.bukkit.material.Directional) state.getData();
return dir.getFacing();
}
}
return null;
}
public static boolean isOpen(Block b) {
if (nieuweVersie) {
org.bukkit.block.data.BlockData blockData = b.getBlockData();
if (isOpenable(b)) {
org.bukkit.block.data.Openable op = (org.bukkit.block.data.Openable) blockData;
return op.isOpen();
}
} else {
BlockState state = b.getState();
if (isOpenable(b)) {
org.bukkit.material.Openable openable = (org.bukkit.material.Openable) state.getData();
return openable.isOpen();
}
}
return false;
}
/* Gate codes sponsored by MrWouter <3 */
public static boolean isOpenable(Block b) {
if (b == null) {
return false;
}
if (nieuweVersie) {
return b.getBlockData() instanceof org.bukkit.block.data.Openable;
} else {
return b.getState().getData() instanceof org.bukkit.material.Openable;
}
}
private static Block getNeighbor(Block lampBlock) {
List<Block> possibleNeighbors = new ArrayList<>();
if (lampBlock.getLocation().getY() > 0.0D) {
possibleNeighbors.add(lampBlock.getLocation().add(0.0D, -1.0D, 0.0D).getBlock());
}
if (lampBlock.getLocation().getY() < 255.0D) {
possibleNeighbors.add(lampBlock.getLocation().add(0.0D, 1.0D, 0.0D).getBlock());
}
possibleNeighbors.add(lampBlock.getLocation().add(0.0D, 0.0D, 1.0D).getBlock());
possibleNeighbors.add(lampBlock.getLocation().add(0.0D, 0.0D, -1.0D).getBlock());
possibleNeighbors.add(lampBlock.getLocation().add(1.0D, 0.0D, 0.0D).getBlock());
possibleNeighbors.add(lampBlock.getLocation().add(-1.0D, 0.0D, 0.0D).getBlock());
for (Block neighbor: possibleNeighbors) {
if (neighbor.getType() == Material.AIR) {
return neighbor;
}
}
for (Block neighbor: possibleNeighbors) {
if ((neighbor.getState().getClass().getSimpleName().equals("CraftBlockState")) && (neighbor.getType() != Material.valueOf(XMaterial.PISTON_HEAD.getLegacy()[0]) && neighbor.getType() != Material.valueOf(XMaterial.MOVING_PISTON.getLegacy()[1])) && (neighbor.getType() != Material.valueOf("REDSTONE_LAMP_ON"))) {
return neighbor;
}
}
for (Block neighbor: possibleNeighbors) {
if ((neighbor.getState().getClass().getSimpleName().equals("CraftBlockState")) && (neighbor.getType() != Material.valueOf(XMaterial.PISTON_HEAD.getLegacy()[0]) && neighbor.getType() != Material.valueOf(XMaterial.MOVING_PISTON.getLegacy()[1]))) {
return neighbor;
}
}
return null;
}
private static boolean isAan(Block lamp) {
return ((nieuweVersie) && (Objects.requireNonNull(getAsString(getBlockData(lamp))).contains("lit=true"))) || ((!nieuweVersie) && (lamp.getType() == Material.matchMaterial(XMaterial.REDSTONE_LAMP.getLegacy()[1])));
}
private static boolean isLamp(Block lamp) {
if (nieuweVersie) {
return lamp.getType() == XMaterial.REDSTONE_LAMP.parseMaterial();
} else {
return lamp.getType() == Material.matchMaterial(XMaterial.REDSTONE_LAMP.getLegacy()[1])
|| lamp.getType() == Material.matchMaterial(XMaterial.REDSTONE_LAMP.getLegacy()[0]);
}
}
private static void setBlockData(Block lamp, Object blockData) {
try {
setBlockDataMethod.invoke(lamp, blockData,
Boolean.FALSE);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Object getBlockData(Block lamp) {
try {
return getBlockDataMethod.invoke(lamp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String getAsString(Object blockData) {
try {
return (String) getAsStringMethod.invoke(blockData, new Object[0]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View file

@ -0,0 +1,264 @@
package nl.sbdeveloper.themeparkplus.util;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
/**
* License class for SBDevelopment
*
* v1.3 - Changed in 03-03-2020
*
* @author Stijn [SBDeveloper]
* @since 23-12-2019
*/
public class License {
/*
This file is part of ActionFoto.
Copyright (c) 2018-2020 SBDevelopment - All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
Written by Stijn Bannink <stijnbannink23@gmail.com>, January 2020
*/
private Plugin plugin;
private String license;
private String prefix;
/**
* Construct a new license
* @param plugin The Main class [Javaplugin]
* @param prefix The prefix, like TPP or AF
* @param license The license from the config
*/
public License(Plugin plugin, String prefix, String license) {
this.prefix = prefix;
this.plugin = plugin;
this.license = license;
startTimer();
}
private void startTimer() {
Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, () -> {
if (!validateLicense()) {
Bukkit.getLogger().severe("[" + prefix + "] License is incorrect!");
}
}, 0, 20 * 60 * 60);
}
/**
* Check a license
*
* @return true/false
*/
private boolean validateLicense() {
String url = "https://sbdplugins.nl/wp-json/lmfwc/v2/licenses/" + this.license;
@Nullable JsonObject res;
try {
res = sendGETRequestJSON(url);
} catch (IOException e) {
disable("GET_request_error");
return false;
}
if (res == null) {
disable("GET_request_error_2");
return false;
}
JsonObject dat = res.get("data").getAsJsonObject();
int stat = dat.get("status").getAsInt();
if (stat == 404) {
disable("status_404_error");
return false;
}
if (dat.get("licenseKey").isJsonNull()) {
disable("license_null_error");
return false;
}
if (!dat.get("licenseKey").getAsString().split("-")[0].contains(prefix)) {
disable("prefix_error");
return false;
}
switch(dat.get("status").getAsString()) {
case "2":
//activate?
break;
case "3":
//it's good
break;
default:
disable("status_error");
return false;
}
//Not activated? Activate it!
if (dat.get("timesActivated").isJsonNull() || dat.get("timesActivated").getAsString().equalsIgnoreCase("0")) {
return activate();
}
if (dat.get("expiresAt").isJsonNull()) {
disable("null_error");
return false;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date;
try {
date = format.parse(dat.get("expiresAt").getAsString());
} catch (ParseException e) {
e.printStackTrace();
disable("null_error");
return false;
}
if (!(Objects.requireNonNull(date).after(new Date()))) {
disable("expired_error");
return false;
}
if (!dat.get("ipcheck").getAsBoolean()) {
disable("ip_error");
return false;
}
if (dat.get("port").isJsonNull()) {
disable("null_error");
return false;
}
try {
int por = dat.get("port").getAsInt();
if (por != Bukkit.getServer().getPort()) {
disable("port_error");
return false;
}
} catch(NumberFormatException e) {
disable("null_error");
return false;
}
return true;
}
/**
* Activate the license (private)
*
* @return true/false
*/
private boolean activate() {
String url = "https://sbdplugins.nl/wp-json/lmfwc/v2/licenses/activate/" + this.license + "?port=" + Bukkit.getServer().getPort();
@Nullable JsonObject res;
try {
res = sendGETRequestJSON(url);
} catch (IOException e) {
e.printStackTrace();
disable("GET_request_error");
return false;
}
if (res == null) {
disable("GET_request_error_2");
return false;
}
JsonObject dat = res.get("data").getAsJsonObject();
int stat = dat.get("status").getAsInt();
if (stat == 404) {
disable("status_404_error");
return false;
}
if (dat.get("licenseKey").isJsonNull()) {
disable("license_null_error");
return false;
}
if (!dat.get("licenseKey").getAsString().split("-")[0].contains(prefix)) {
disable("prefix_error");
return false;
}
switch(dat.get("status").getAsString()) {
case "2":
//activate?
break;
case "3":
//it's good
break;
default:
disable("status_error");
return false;
}
//Still not activated? Something is wrong...
return !dat.get("timesActivated").isJsonNull() && !dat.get("timesActivated").getAsString().equalsIgnoreCase("0");
}
/**
* Disable the plugin (private)
*
* @param reason The disabling reason
*/
private void disable(String reason) {
Bukkit.getScheduler().runTask(plugin, () -> {
Bukkit.getLogger().severe("[" + plugin.getName() + "] " + "Stopping plugin because licensing system check failed.");
Bukkit.getLogger().severe("[" + plugin.getName() + "] " + "Reason: " + reason);
Bukkit.getPluginManager().disablePlugin(plugin);
});
}
/**
* Send an GET request with JSONObject response
*
* @param uri The URL
*
* @return The JSONObject
* @throws IOException URL errors
*/
@Nullable
private JsonObject sendGETRequestJSON(String uri) throws IOException {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
String authStringEnc = "Y2tfMGEzNWEzMWE2NzExNmM3NDg2MGEwYTJhNjUxNGVjZjM4NTBmM2JmMDpjc185NmYxZGNlYjI4MWRkZDExOTBjMzQ3ZjJjYzMwMGNjZTIzYWNhODI1";
con.setRequestProperty("Authorization", "Basic " + authStringEnc);
int code = con.getResponseCode();
if (code == 404) {
disable("404_error");
return null;
}
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JsonParser parser = new JsonParser();
return parser.parse(response.toString()).getAsJsonObject();
}
}

View file

@ -0,0 +1,52 @@
package nl.sbdeveloper.themeparkplus.util;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import com.sk89q.worldedit.bukkit.selections.Selection;
import com.sk89q.worldedit.regions.Polygonal2DRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.World;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;
public class WEUtil {
private static boolean newVersion;
private static WorldEditPlugin wep;
public WEUtil() {
newVersion = XMaterial.isNewVersion();
wep = (WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit");
}
@Nullable
public static Region getSelection(Player p) {
if (newVersion) {
LocalSession l = WorldEdit.getInstance().getSessionManager().get(BukkitAdapter.adapt(p));
Region s;
try {
s = l.getSelection(l.getSelectionWorld());
} catch (IncompleteRegionException e) {
return null;
}
if (s instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) s;
int minY = polySel.getNativeMinimumPoint().getBlockY();
int maxY = polySel.getNativeMaximumPoint().getBlockY();
return new Polygonal2DRegion((World) polySel.getWorld(), polySel.getNativePoints(), minY, maxY);
}
} else {
Selection sel = wep.getSelection(p);
if (sel instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) sel;
int minY = polySel.getNativeMinimumPoint().getBlockY();
int maxY = polySel.getNativeMaximumPoint().getBlockY();
return new Polygonal2DRegion((World) polySel.getWorld(), polySel.getNativePoints(), minY, maxY);
}
}
return null;
}
}

File diff suppressed because it is too large Load diff