More code cleanup

This commit is contained in:
Kristian Knarvik 2021-08-27 18:26:14 +02:00
parent 0c9f4c431e
commit 47301058ba
2 changed files with 154 additions and 122 deletions

View File

@ -32,28 +32,33 @@ import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
public class BooksWithoutBorders extends JavaPlugin { public class BooksWithoutBorders extends JavaPlugin {
protected static int dlimit; protected static int bookDuplicateLimit;
//The separating string between the book title and the book author //The separating string between the book title and the book author
protected static String titleAuthorSeparator; protected static String titleAuthorSeparator;
protected static String loreSep; protected static String loreSep;
protected static final String SLASH = System.getProperty("file.separator"); protected static final String SLASH = System.getProperty("file.separator");
protected static List<String> firstBooks = new ArrayList<>(); protected static List<String> firstBooks;
protected static String fBMessage; protected static String welcomeMessage;
protected static List<String> existingPlayers; protected static List<String> existingPlayers;
protected static Economy eco; protected static Economy eco;
protected static Material bookPriceType = null; protected static Material bookPriceType = null;
protected static double bookPriceQuantity; protected static double bookPriceQuantity;
protected static boolean authorOnlyCopy, useYml, adminDecrypt; protected static boolean authorOnlyCopy, useYml, adminDecrypt;
protected static ItemFactory iF; protected static ItemFactory iF;
protected static final Map<String, List<String>> loadList = new HashMap<>(); protected static Map<String, List<String>> loadList;
protected static BooksWithoutBorders bwb; protected static BooksWithoutBorders bwb;
protected static final BooksWithoutBordersListener bL = new BooksWithoutBordersListener(); protected static BooksWithoutBordersListener bL;
protected static ConsoleCommandSender consoleSender; protected static ConsoleCommandSender consoleSender;
protected static String bookFolder;
@Override @Override
public void onEnable() { public void onEnable() {
bwb = this; bwb = this;
consoleSender = this.getServer().getConsoleSender(); consoleSender = this.getServer().getConsoleSender();
bookFolder = this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH;
bL = new BooksWithoutBordersListener();
loadList = new HashMap<>();
firstBooks = new ArrayList<>();
if (SLASH != null && init()) { if (SLASH != null && init()) {
this.getServer().getPluginManager().registerEvents(bL, this); this.getServer().getPluginManager().registerEvents(bL, this);
@ -79,11 +84,11 @@ public class BooksWithoutBorders extends JavaPlugin {
} }
this.getConfig().set("Options.Save_Books_in_Yaml_Format", useYml); this.getConfig().set("Options.Save_Books_in_Yaml_Format", useYml);
this.getConfig().set("Options.Max_Number_of_Duplicates", dlimit); this.getConfig().set("Options.Max_Number_of_Duplicates", bookDuplicateLimit);
this.getConfig().set("Options.Title-Author_Separator", titleAuthorSeparator); this.getConfig().set("Options.Title-Author_Separator", titleAuthorSeparator);
this.getConfig().set("Options.Lore_line_separator", loreSep); this.getConfig().set("Options.Lore_line_separator", loreSep);
this.getConfig().set("Options.Books_for_new_players", firstBooks); this.getConfig().set("Options.Books_for_new_players", firstBooks);
this.getConfig().set("Options.Message_for_new_players", fBMessage); this.getConfig().set("Options.Message_for_new_players", welcomeMessage);
if (bookPriceType != null) { if (bookPriceType != null) {
if (bookPriceType != Material.AIR) if (bookPriceType != Material.AIR)
this.getConfig().set("Options.Price_to_create_book.Item_type", bookPriceType.toString()); this.getConfig().set("Options.Price_to_create_book.Item_type", bookPriceType.toString());
@ -112,8 +117,8 @@ public class BooksWithoutBorders extends JavaPlugin {
this.saveConfig(); this.saveConfig();
File fTest = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH); File fTest = new File(bookFolder);
File efTest = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + "Encrypted" + SLASH); File efTest = new File(bookFolder + "Encrypted" + SLASH);
if (!fTest.exists()) { if (!fTest.exists()) {
try { try {
@ -145,7 +150,7 @@ public class BooksWithoutBorders extends JavaPlugin {
this.reloadConfig(); this.reloadConfig();
try { try {
useYml = this.getConfig().getBoolean("Options.Save_Books_in_Yaml_Format", true); useYml = this.getConfig().getBoolean("Options.Save_Books_in_Yaml_Format", true);
dlimit = this.getConfig().getInt("Options.Max_Number_of_Duplicates", 5); bookDuplicateLimit = this.getConfig().getInt("Options.Max_Number_of_Duplicates", 5);
titleAuthorSeparator = this.getConfig().getString("Options.Title-Author_Separator", ","); titleAuthorSeparator = this.getConfig().getString("Options.Title-Author_Separator", ",");
loreSep = this.getConfig().getString("Options.Lore_line_separator", "~"); loreSep = this.getConfig().getString("Options.Lore_line_separator", "~");
adminDecrypt = this.getConfig().getBoolean("Options.Admin_Auto_Decrypt", false); adminDecrypt = this.getConfig().getBoolean("Options.Admin_Auto_Decrypt", false);
@ -157,7 +162,7 @@ public class BooksWithoutBorders extends JavaPlugin {
if (firstBooks.isEmpty()) if (firstBooks.isEmpty())
firstBooks.add(" "); firstBooks.add(" ");
fBMessage = this.getConfig().getString("Options.Message_for_new_players", " "); welcomeMessage = this.getConfig().getString("Options.Message_for_new_players", " ");
//Converts string into material //Converts string into material
String sMaterial = this.getConfig().getString("Options.Price_to_create_book.Item_type", " "); String sMaterial = this.getConfig().getString("Options.Price_to_create_book.Item_type", " ");
@ -360,7 +365,7 @@ public class BooksWithoutBorders extends JavaPlugin {
return true; return true;
} }
if (args.length == 0 && !(sender instanceof Player)) { if (args.length == 0) {
//lists commands from console //lists commands from console
sender.sendMessage(ChatColor.YELLOW + "Use: /bwb [Command]"); sender.sendMessage(ChatColor.YELLOW + "Use: /bwb [Command]");
sender.sendMessage(ChatColor.YELLOW + "[] denote parameters"); sender.sendMessage(ChatColor.YELLOW + "[] denote parameters");
@ -781,7 +786,7 @@ public class BooksWithoutBorders extends JavaPlugin {
} }
if (args.length == 1 && adminDecrypt && sender.hasPermission("bookswithoutborders.admin") && sender instanceof Player) { if (args.length == 1 && adminDecrypt && sender.hasPermission("bookswithoutborders.admin") && sender instanceof Player) {
String path = this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + "Encrypted" + SLASH; String path = bookFolder + "Encrypted" + SLASH;
String fname = (!((BookMeta) ((Player) sender).getItemInHand().getItemMeta()).hasTitle()) ? "Untitled," + sender.getName() : String fname = (!((BookMeta) ((Player) sender).getItemInHand().getItemMeta()).hasTitle()) ? "Untitled," + sender.getName() :
((BookMeta) ((Player) sender).getItemInHand().getItemMeta()).getTitle() + titleAuthorSeparator + ((BookMeta) ((Player) sender).getItemInHand().getItemMeta()).getAuthor(); ((BookMeta) ((Player) sender).getItemInHand().getItemMeta()).getTitle() + titleAuthorSeparator + ((BookMeta) ((Player) sender).getItemInHand().getItemMeta()).getAuthor();
File eDir = new File(path); File eDir = new File(path);
@ -1244,9 +1249,9 @@ public class BooksWithoutBorders extends JavaPlugin {
BookMeta book = (BookMeta) player.getItemInHand().getItemMeta(); BookMeta book = (BookMeta) player.getItemInHand().getItemMeta();
String path; String path;
if (pub) { if (pub) {
path = this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH; path = bookFolder;
} else { } else {
path = this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + cleanString(player.getName()) + SLASH; path = bookFolder + cleanString(player.getName()) + SLASH;
} }
String fname; String fname;
if (!book.hasTitle()) { if (!book.hasTitle()) {
@ -1292,7 +1297,7 @@ public class BooksWithoutBorders extends JavaPlugin {
return; return;
} }
if (dupes > dlimit) { if (dupes > bookDuplicateLimit) {
player.sendMessage(ChatColor.RED + "Maximum amount of " + fname + " duplicates reached!"); player.sendMessage(ChatColor.RED + "Maximum amount of " + fname + " duplicates reached!");
player.sendMessage(ChatColor.RED + "Use " + ChatColor.YELLOW + "/bwb Save true " + ChatColor.RED + "to overwrite!"); player.sendMessage(ChatColor.RED + "Use " + ChatColor.YELLOW + "/bwb Save true " + ChatColor.RED + "to overwrite!");
return; return;
@ -1340,13 +1345,13 @@ public class BooksWithoutBorders extends JavaPlugin {
if (fname.lastIndexOf(".") != -1) { if (fname.lastIndexOf(".") != -1) {
if (fname.substring(fname.lastIndexOf(".")).equals(".yml") || fname.substring(fname.lastIndexOf(".")).equals(".txt")) { if (fname.substring(fname.lastIndexOf(".")).equals(".yml") || fname.substring(fname.lastIndexOf(".")).equals(".txt")) {
if (dir.equalsIgnoreCase("public")) if (dir.equalsIgnoreCase("public"))
file = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + fname); file = new File(bookFolder + fname);
else if (dir.equalsIgnoreCase("player")) else if (dir.equalsIgnoreCase("player"))
file = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + cleanString(sender.getName()) + SLASH + fname); file = new File(bookFolder + cleanString(sender.getName()) + SLASH + fname);
else if (!dir.equalsIgnoreCase("")) else if (!dir.equalsIgnoreCase(""))
file = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + "Encrypted" + SLASH + dir + SLASH + fname); file = new File(bookFolder + "Encrypted" + SLASH + dir + SLASH + fname);
else else
file = null; file = null;
@ -1360,26 +1365,26 @@ public class BooksWithoutBorders extends JavaPlugin {
} }
//No extension present //No extension present
if (dir.equalsIgnoreCase("public")) if (dir.equalsIgnoreCase("public"))
file = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + fname + ".yml"); file = new File(bookFolder + fname + ".yml");
else if (dir.equalsIgnoreCase("player")) else if (dir.equalsIgnoreCase("player"))
file = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + cleanString(sender.getName()) + SLASH + fname + ".yml"); file = new File(bookFolder + cleanString(sender.getName()) + SLASH + fname + ".yml");
else if (!dir.equalsIgnoreCase("")) else if (!dir.equalsIgnoreCase(""))
file = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + "Encrypted" + SLASH + dir + SLASH + fname + ".yml"); file = new File(bookFolder + "Encrypted" + SLASH + dir + SLASH + fname + ".yml");
else else
file = null; file = null;
if (!file.isFile()) { if (!file.isFile()) {
if (dir.equalsIgnoreCase("public")) if (dir.equalsIgnoreCase("public"))
file = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + fname + ".txt"); file = new File(bookFolder + fname + ".txt");
else if (dir.equalsIgnoreCase("player")) else if (dir.equalsIgnoreCase("player"))
file = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + cleanString(sender.getName()) + SLASH + fname + ".txt"); file = new File(bookFolder + cleanString(sender.getName()) + SLASH + fname + ".txt");
else if (!dir.equalsIgnoreCase("")) else if (!dir.equalsIgnoreCase(""))
file = new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + "Encrypted" + SLASH + dir + SLASH + fname + ".txt"); file = new File(bookFolder + "Encrypted" + SLASH + dir + SLASH + fname + ".txt");
else else
file = null; file = null;
@ -1424,7 +1429,7 @@ public class BooksWithoutBorders extends JavaPlugin {
} }
protected Boolean eSave(Player player, BookMeta book, String key) { protected Boolean eSave(Player player, BookMeta book, String key) {
String path = this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + "Encrypted" + SLASH; String path = bookFolder + "Encrypted" + SLASH;
String fname = (!book.hasTitle()) ? "Untitled," + player.getName() : String fname = (!book.hasTitle()) ? "Untitled," + player.getName() :
book.getTitle() + titleAuthorSeparator + book.getAuthor(); book.getTitle() + titleAuthorSeparator + book.getAuthor();
@ -1449,7 +1454,7 @@ public class BooksWithoutBorders extends JavaPlugin {
} }
protected BookMeta groupESave(Player player, BookMeta book, String key, String groupName) { protected BookMeta groupESave(Player player, BookMeta book, String key, String groupName) {
String path = this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + "Encrypted" + SLASH + cleanString(groupName) + SLASH; String path = bookFolder + "Encrypted" + SLASH + cleanString(groupName) + SLASH;
File dirTest = new File(path); File dirTest = new File(path);
//Creates group dir //Creates group dir
if (!dirTest.exists()) { if (!dirTest.exists()) {
@ -1493,7 +1498,7 @@ public class BooksWithoutBorders extends JavaPlugin {
protected ItemStack eLoad(Player player, String key, boolean deleteEncryptedFile) { protected ItemStack eLoad(Player player, String key, boolean deleteEncryptedFile) {
BookMeta book = (BookMeta) player.getItemInHand().getItemMeta(); BookMeta book = (BookMeta) player.getItemInHand().getItemMeta();
String path = this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + "Encrypted" + SLASH; String path = bookFolder + "Encrypted" + SLASH;
String fname = (!book.hasTitle()) ? "Untitled," + player.getName() : book.getTitle() + titleAuthorSeparator + book.getAuthor(); String fname = (!book.hasTitle()) ? "Untitled," + player.getName() : book.getTitle() + titleAuthorSeparator + book.getAuthor();
fname = "[" + key + "]" + fname; fname = "[" + key + "]" + fname;
@ -1533,9 +1538,9 @@ public class BooksWithoutBorders extends JavaPlugin {
} }
protected List<String> listFiles(CommandSender sender, Boolean pub, int offset, boolean silent) { protected List<String> listFiles(CommandSender sender, Boolean pub, int offset, boolean silent) {
List<String> fList = new ArrayList<>(); List<String> fileList = new ArrayList<>();
File file = (pub) ? new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH) : File file = (pub) ? new File(bookFolder) :
new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + cleanString(sender.getName()) + SLASH); new File(bookFolder + cleanString(sender.getName()) + SLASH);
File[] fl = file.listFiles(); File[] fl = file.listFiles();
if (!file.exists()) { if (!file.exists()) {
@ -1552,13 +1557,13 @@ public class BooksWithoutBorders extends JavaPlugin {
sender.sendMessage(ChatColor.GREEN + "Available Books:"); sender.sendMessage(ChatColor.GREEN + "Available Books:");
for (File value : fl) { for (File value : fl) {
if (value.isFile()) { if (value.isFile()) {
fList.add(value.getName()); fileList.add(value.getName());
if (!silent) if (!silent)
sender.sendMessage(ChatColor.GRAY + "[" + (fList.size() + offset) + "] " + value.getName()/*.substring(0, fl[x].getName().length()-4)*/); sender.sendMessage(ChatColor.GRAY + "[" + (fileList.size() + offset) + "] " + value.getName()/*.substring(0, fl[x].getName().length()-4)*/);
} }
} }
return fList; return fileList;
} }
protected List<String> pageFormat(List<String> rawPages) { protected List<String> pageFormat(List<String> rawPages) {
@ -1702,8 +1707,8 @@ public class BooksWithoutBorders extends JavaPlugin {
//Extension is already present //Extension is already present
if (fname.lastIndexOf(".") != -1) { if (fname.lastIndexOf(".") != -1) {
if (fname.substring(fname.lastIndexOf(".")).equals(".yml") || fname.substring(fname.lastIndexOf(".")).equals(".txt")) { if (fname.substring(fname.lastIndexOf(".")).equals(".yml") || fname.substring(fname.lastIndexOf(".")).equals(".txt")) {
file = (ispub) ? new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + fname) : file = (ispub) ? new File(bookFolder + fname) :
new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + cleanString(sender.getName()) + SLASH + fname); new File(bookFolder + cleanString(sender.getName()) + SLASH + fname);
if (!file.isFile()) { if (!file.isFile()) {
sender.sendMessage(ChatColor.RED + "Incorrect file name!"); sender.sendMessage(ChatColor.RED + "Incorrect file name!");
@ -1714,12 +1719,12 @@ public class BooksWithoutBorders extends JavaPlugin {
} }
//No extension present //No extension present
file = (ispub) ? new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + fname + ".yml") : file = (ispub) ? new File(bookFolder + fname + ".yml") :
new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + cleanString(sender.getName()) + SLASH + fname + ".yml"); new File(bookFolder + cleanString(sender.getName()) + SLASH + fname + ".yml");
if (!file.isFile()) { if (!file.isFile()) {
file = (ispub) ? new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + fname + ".txt") : file = (ispub) ? new File(bookFolder + fname + ".txt") :
new File(this.getDataFolder().getAbsolutePath() + SLASH + "Books" + SLASH + cleanString(sender.getName()) + SLASH + fname + ".txt"); new File(bookFolder + cleanString(sender.getName()) + SLASH + fname + ".txt");
if (!file.isFile()) { if (!file.isFile()) {
sender.sendMessage(ChatColor.RED + "Incorrect file name!"); sender.sendMessage(ChatColor.RED + "Incorrect file name!");
@ -1785,8 +1790,10 @@ public class BooksWithoutBorders extends JavaPlugin {
} }
protected boolean isAuthor(Player player, BookMeta book) { protected boolean isAuthor(Player player, BookMeta book) {
if (cleanString(player.getName()).equalsIgnoreCase(cleanString(book.getAuthor()))) String author = book.getAuthor();
if (author != null && cleanString(player.getName()).equalsIgnoreCase(cleanString(author))) {
return true; return true;
}
player.sendMessage(ChatColor.RED + "You must be the author of this book to use this command!"); player.sendMessage(ChatColor.RED + "You must be the author of this book to use this command!");
return false; return false;

View File

@ -28,7 +28,8 @@ import org.bukkit.inventory.meta.ItemMeta;
public class BooksWithoutBordersListener implements Listener { public class BooksWithoutBordersListener implements Listener {
private final String slash = BooksWithoutBorders.SLASH; private final String slash = BooksWithoutBorders.SLASH;
private final String bookFolder = BooksWithoutBorders.bwb.getDataFolder().getAbsolutePath() + slash + "Books" + slash; private final String bookFolderPath = BooksWithoutBorders.bwb.getDataFolder().getAbsolutePath() + slash + "Books";
private final String bookFolder = bookFolderPath + slash;
/** /**
* Updates old books to a newer format * Updates old books to a newer format
@ -76,6 +77,10 @@ public class BooksWithoutBordersListener implements Listener {
@EventHandler @EventHandler
public void onHold(PlayerItemHeldEvent e) { public void onHold(PlayerItemHeldEvent e) {
if (e.isCancelled()) {
return;
}
Player player = e.getPlayer(); Player player = e.getPlayer();
int selectedSlot = e.getNewSlot(); int selectedSlot = e.getNewSlot();
PlayerInventory playerInventory = player.getInventory(); PlayerInventory playerInventory = player.getInventory();
@ -97,9 +102,10 @@ public class BooksWithoutBordersListener implements Listener {
@EventHandler @EventHandler
public void onPlayerJoin(PlayerJoinEvent e) { public void onPlayerJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
//Handle new players //Handle new players
if (!BooksWithoutBorders.bwb.hasPlayedBefore(e.getPlayer().getName())) { if (!BooksWithoutBorders.bwb.hasPlayedBefore(player.getName())) {
Player player = e.getPlayer();
boolean sendMessage = true; boolean sendMessage = true;
//Gives new players necessary books //Gives new players necessary books
@ -109,49 +115,49 @@ public class BooksWithoutBordersListener implements Listener {
} }
//Updates any books in either hand //Updates any books in either hand
ItemStack mainHandItem = e.getPlayer().getInventory().getItemInMainHand(); ItemStack mainHandItem = player.getInventory().getItemInMainHand();
ItemStack offHandItem = e.getPlayer().getInventory().getItemInOffHand(); ItemStack offHandItem = player.getInventory().getItemInOffHand();
if (mainHandItem.getType() == Material.WRITTEN_BOOK) { if (mainHandItem.getType() == Material.WRITTEN_BOOK) {
ItemMeta itemMetadata = mainHandItem.getItemMeta(); ItemMeta itemMetadata = mainHandItem.getItemMeta();
updateBookInHand(e.getPlayer(), itemMetadata, true); updateBookInHand(player, itemMetadata, true);
} }
if (offHandItem.getType() == Material.WRITTEN_BOOK) { if (offHandItem.getType() == Material.WRITTEN_BOOK) {
ItemMeta itemMetadata = offHandItem.getItemMeta(); ItemMeta itemMetadata = offHandItem.getItemMeta();
updateBookInHand(e.getPlayer(), itemMetadata, false); updateBookInHand(player, itemMetadata, false);
} }
} }
/** /**
* Gives a book to a player joining for the first time * Gives a book to a player joining for the first time
* @param bookName <p>The name of the book to give</p> *
* @param player <p>The player which just joined</p> * @param bookName <p>The name of the book to give</p>
* @param player <p>The player which just joined</p>
* @param sendMessage <p>Whether to send a message to the joining player</p> * @param sendMessage <p>Whether to send a message to the joining player</p>
* @return <p>True if a message has yet to be sent</p> * @return <p>True if a message has yet to be sent</p>
*/ */
private boolean giveBookToNewPlayer(String bookName, Player player, boolean sendMessage) { private boolean giveBookToNewPlayer(String bookName, Player player, boolean sendMessage) {
if (!bookName.trim().isEmpty()) {
if (!bookName.equalsIgnoreCase(" ")) { //Handles loadList numbers
//handles loadlist numbers try {
for (int x = 0; x < bookName.length(); x++) { Integer.parseInt(bookName);
if (!Character.isDigit(bookName.charAt(x))) { //Load public books for the player
break; List<String> availableFiles = BooksWithoutBorders.bwb.listFiles(player, true, 0, true);
} BooksWithoutBorders.loadList.put(player.getName(), availableFiles);
if (x == bookName.length() - 1) { } catch (NumberFormatException ignored) {
BooksWithoutBorders.loadList.put(player.getName(), BooksWithoutBorders.bwb.listFiles(player, true, 0, true));
}
} }
//Give the book to the player if it exists
ItemStack newBook = BooksWithoutBorders.bwb.loadBook(player, bookName, "true", "public"); ItemStack newBook = BooksWithoutBorders.bwb.loadBook(player, bookName, "true", "public");
if (newBook != null) { if (newBook != null) {
player.getInventory().addItem(newBook); player.getInventory().addItem(newBook);
} }
if (!BooksWithoutBorders.fBMessage.equalsIgnoreCase(" ") && newBook != null && sendMessage) { //Send the player a welcome message if it exists
if (!BooksWithoutBorders.welcomeMessage.trim().isEmpty() && newBook != null && sendMessage) {
sendMessage = false; sendMessage = false;
final Player fp = player;
BooksWithoutBorders.bwb.getServer().getScheduler().scheduleSyncDelayedTask(BooksWithoutBorders.bwb, BooksWithoutBorders.bwb.getServer().getScheduler().scheduleSyncDelayedTask(BooksWithoutBorders.bwb,
() -> fp.sendMessage(BooksWithoutBorders.fBMessage), 40L); () -> player.sendMessage(BooksWithoutBorders.welcomeMessage), 40L);
} }
} }
return sendMessage; return sendMessage;
@ -178,89 +184,107 @@ public class BooksWithoutBordersListener implements Listener {
@EventHandler @EventHandler
public void onSignChange(SignChangeEvent e) { public void onSignChange(SignChangeEvent e) {
if (e.getLine(0).equalsIgnoreCase("[BwB]") && e.getPlayer().hasPermission("bookswithoutborders.signs")) { if (e.isCancelled()) {
e.setLine(0, ChatColor.DARK_GREEN + "[BwB]"); return;
}
if ((e.getLine(1).equalsIgnoreCase("[Encrypt]") || e.getLine(1).equalsIgnoreCase("[Decrypt]") || e.getLine(1).equalsIgnoreCase("[Give]")) && e.getLine(2).replace(" ", "").length() > 0) { String[] lines = e.getLines();
e.setLine(1, ChatColor.DARK_BLUE + e.getLine(1)); Player player = e.getPlayer();
if (e.getLine(1).equalsIgnoreCase(ChatColor.DARK_BLUE + "[Encrypt]") || e.getLine(1).equalsIgnoreCase(ChatColor.DARK_BLUE + "[Decrypt]")) {
e.setLine(2, ChatColor.MAGIC + e.getLine(2)); //Check if creating a Books Without Borders Sign and if the player has permission
e.setLine(3, ChatColor.DARK_BLUE + e.getLine(3)); if (!lines[0].equalsIgnoreCase("[BwB]") || !player.hasPermission("bookswithoutborders.signs")) {
return;
}
//Mark the sign as active
e.setLine(0, ChatColor.DARK_GREEN + "[BwB]");
if ((lines[1].equalsIgnoreCase("[Encrypt]") || lines[1].equalsIgnoreCase("[Decrypt]") ||
lines[1].equalsIgnoreCase("[Give]")) && lines[2].trim().length() > 0) {
//Mark the second line as valid
e.setLine(1, ChatColor.DARK_BLUE + lines[1]);
//Mark valid encryption/decryption sign
if (lines[1].equalsIgnoreCase(ChatColor.DARK_BLUE + "[Encrypt]") ||
lines[1].equalsIgnoreCase(ChatColor.DARK_BLUE + "[Decrypt]")) {
e.setLine(2, ChatColor.MAGIC + lines[2]);
e.setLine(3, ChatColor.DARK_BLUE + lines[3]);
}
//Generate book giving sign
if (lines[1].equalsIgnoreCase(ChatColor.DARK_BLUE + "[Give]")) {
if (lines[2].length() > 13 || lines[3].length() > 13) {
player.sendMessage(ChatColor.RED + "[Give] signs' 3rd and 4th lines must be 13 characters or less!");
e.setLine(2, ChatColor.DARK_RED + lines[2]);
e.setLine(3, ChatColor.DARK_RED + lines[3]);
return;
} }
if (e.getLine(1).equalsIgnoreCase(ChatColor.DARK_BLUE + "[Give]")) { //Tests if a full file name has been supplied
if (e.getLine(2).length() > 13 || e.getLine(3).length() > 13) { if ((new File(bookFolder + lines[2] + lines[3]).isFile()) ||
e.getPlayer().sendMessage(ChatColor.RED + "[Give] signs' 3rd and 4th lines must be 13 characters or less!"); (new File(bookFolder + lines[2] + lines[3] + ".txt").isFile()) ||
e.setLine(2, ChatColor.DARK_RED + e.getLine(2)); (new File(bookFolder + lines[2] + lines[3] + ".yml").isFile())) {
e.setLine(3, ChatColor.DARK_RED + e.getLine(3)); e.setLine(2, ChatColor.DARK_GREEN + lines[2]);
return; e.setLine(3, ChatColor.DARK_GREEN + lines[3]);
} } else {
//Tests if a full file name has been supplied
if ((new File(BooksWithoutBorders.bwb.getDataFolder().getAbsolutePath() + BooksWithoutBorders.SLASH + "Books" + BooksWithoutBorders.SLASH + e.getLine(2) + e.getLine(3)).isFile()) ||
(new File(BooksWithoutBorders.bwb.getDataFolder().getAbsolutePath() + BooksWithoutBorders.SLASH + "Books" + BooksWithoutBorders.SLASH + e.getLine(2) + e.getLine(3) + ".txt").isFile()) ||
(new File(BooksWithoutBorders.bwb.getDataFolder().getAbsolutePath() + BooksWithoutBorders.SLASH + "Books" + BooksWithoutBorders.SLASH + e.getLine(2) + e.getLine(3) + ".yml").isFile())) {
e.setLine(2, ChatColor.DARK_GREEN + e.getLine(2));
e.setLine(3, ChatColor.DARK_GREEN + e.getLine(3));
}
//Tests if a load list number has been supplied //Tests if a load list number has been supplied
else { File dirFile = new File(bookFolderPath);
File dirFile = new File(BooksWithoutBorders.bwb.getDataFolder().getAbsolutePath() + BooksWithoutBorders.SLASH + "Books"); for (int x = 0; x < lines[2].length(); x++) {
for (int x = 0; x < e.getLine(2).length(); x++) { if (!Character.isDigit(lines[2].charAt(x))) {
if (!Character.isDigit(e.getLine(2).charAt(x))) { e.setLine(2, ChatColor.DARK_RED + lines[2]);
e.setLine(2, ChatColor.DARK_RED + e.getLine(2)); e.setLine(3, ChatColor.DARK_RED + lines[3]);
e.setLine(3, ChatColor.DARK_RED + e.getLine(3)); break;
break; }
if (x == lines[2].length() - 1) {
List<String> fList = new ArrayList<>();
for (int y = 0; y < dirFile.list().length; y++) {
if (dirFile.listFiles()[y].isFile()) {
fList.add(dirFile.listFiles()[y].getName());
}
} }
if (x == e.getLine(2).length() - 1) {
List<String> fList = new ArrayList<>();
for (int y = 0; y < dirFile.list().length; y++) {
if (dirFile.listFiles()[y].isFile()) {
fList.add(dirFile.listFiles()[y].getName());
}
}
try { try {
if (Integer.parseInt(e.getLine(2)) >= 0 && Integer.parseInt(e.getLine(2)) <= fList.size()) { if (Integer.parseInt(lines[2]) >= 0 && Integer.parseInt(lines[2]) <= fList.size()) {
BooksWithoutBorders.loadList.put(e.getPlayer().getName(), BooksWithoutBorders.bwb.listFiles(e.getPlayer(), true, 0, true)); BooksWithoutBorders.loadList.put(player.getName(), BooksWithoutBorders.bwb.listFiles(player, true, 0, true));
e.setLine(2, ChatColor.DARK_GREEN + e.getLine(2)); e.setLine(2, ChatColor.DARK_GREEN + lines[2]);
e.setLine(3, ChatColor.DARK_GREEN + e.getLine(3)); e.setLine(3, ChatColor.DARK_GREEN + lines[3]);
} else { } else {
e.setLine(2, ChatColor.DARK_RED + e.getLine(2)); e.setLine(2, ChatColor.DARK_RED + lines[2]);
e.setLine(3, ChatColor.DARK_RED + e.getLine(3)); e.setLine(3, ChatColor.DARK_RED + lines[3]);
}
} catch (NumberFormatException ignored) {
} }
} catch (NumberFormatException ignored) {
} }
} }
} }
} }
} else {
e.setLine(1, ChatColor.DARK_RED + e.getLine(1));
} }
} else {
//Mark the second line as invalid
e.setLine(1, ChatColor.DARK_RED + lines[1]);
} }
} }
@EventHandler @EventHandler
public void onClick(PlayerInteractEvent e) { public void onClick(PlayerInteractEvent event) {
if (e.getClickedBlock() == null) { if (event.getClickedBlock() == null) {
return; return;
} }
Material clickedBlockType = e.getClickedBlock().getType(); Material clickedBlockType = event.getClickedBlock().getType();
Player player = e.getPlayer(); Player player = event.getPlayer();
PlayerInventory playerInventory = player.getInventory(); PlayerInventory playerInventory = player.getInventory();
EquipmentSlot hand = e.getHand(); EquipmentSlot hand = event.getHand();
if (hand == null) { if (hand == null) {
return; return;
} }
ItemStack heldItem = playerInventory.getItem(hand); ItemStack heldItem = playerInventory.getItem(hand);
Material heldItemType = heldItem.getType(); Material heldItemType = heldItem.getType();
if (e.getAction() == Action.RIGHT_CLICK_BLOCK && (Tag.SIGNS.isTagged(clickedBlockType) || Tag.WALL_SIGNS.isTagged(clickedBlockType))) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK && (Tag.SIGNS.isTagged(clickedBlockType) ||
Tag.WALL_SIGNS.isTagged(clickedBlockType))) {
//The player right-clicked a sign //The player right-clicked a sign
Sign sign = (Sign) e.getClickedBlock().getState(); Sign sign = (Sign) event.getClickedBlock().getState();
if (signLineEquals(sign, 0, "[BooksWithoutBorders]", ChatColor.DARK_GREEN)) { if (signLineEquals(sign, 0, "[BooksWithoutBorders]", ChatColor.DARK_GREEN)) {
if (signLineEquals(sign, 1, "[Encrypt]", ChatColor.DARK_BLUE)) { if (signLineEquals(sign, 1, "[Encrypt]", ChatColor.DARK_BLUE)) {
@ -272,8 +296,8 @@ public class BooksWithoutBordersListener implements Listener {
giveBook(sign, player); giveBook(sign, player);
} }
} }
} else if (heldItemType == Material.WRITTEN_BOOK && (e.getAction() == Action.LEFT_CLICK_AIR } else if (heldItemType == Material.WRITTEN_BOOK && (event.getAction() == Action.LEFT_CLICK_AIR
|| e.getAction() == Action.LEFT_CLICK_BLOCK)) { || event.getAction() == Action.LEFT_CLICK_BLOCK)) {
BookMeta oldBook = (BookMeta) heldItem.getItemMeta(); BookMeta oldBook = (BookMeta) heldItem.getItemMeta();
if (oldBook == null) { if (oldBook == null) {
return; return;
@ -335,9 +359,10 @@ public class BooksWithoutBordersListener implements Listener {
*/ */
private void encryptHeldBookUsingSign(Sign sign, Material heldItemType, Player player, EquipmentSlot hand) { private void encryptHeldBookUsingSign(Sign sign, Material heldItemType, Player player, EquipmentSlot hand) {
ItemStack eBook; ItemStack eBook;
String[] lines = sign.getLines();
if (heldItemType == Material.WRITTEN_BOOK) { if (heldItemType == Material.WRITTEN_BOOK) {
player.closeInventory(); player.closeInventory();
eBook = BooksWithoutBorders.bwb.bookEncryption(player, sign.getLine(2).substring(2), sign.getLine(3).substring(2), ""); eBook = BooksWithoutBorders.bwb.bookEncryption(player, lines[2].substring(2), lines[3].substring(2), "");
if (eBook != null) { if (eBook != null) {
player.getInventory().setItem(hand, eBook); player.getInventory().setItem(hand, eBook);
} }