diff --git a/src/main/java/net/knarcraft/bookswithoutborders/BooksWithoutBorders.java b/src/main/java/net/knarcraft/bookswithoutborders/BooksWithoutBorders.java index 150d24f..a0498b9 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/BooksWithoutBorders.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/BooksWithoutBorders.java @@ -22,6 +22,7 @@ import net.knarcraft.bookswithoutborders.command.CommandUnSign; import net.knarcraft.bookswithoutborders.command.GiveTabCompleter; import net.knarcraft.bookswithoutborders.listener.PlayerEventListener; import net.knarcraft.bookswithoutborders.listener.SignEventListener; +import net.knarcraft.bookswithoutborders.state.BookDirectory; import net.knarcraft.bookswithoutborders.utility.BookToFromTextHelper; import net.knarcraft.bookswithoutborders.utility.EconomyHelper; import net.knarcraft.bookswithoutborders.utility.FileHelper; @@ -67,15 +68,58 @@ public class BooksWithoutBorders extends JavaPlugin { private static boolean adminDecrypt; private static ItemFactory itemFactory; - public static Map> loadList; + private static Map> playerBooksList; + private static List publicBooksList; private static BooksWithoutBorders booksWithoutBorders; - public static ConsoleCommandSender consoleSender; + private static ConsoleCommandSender consoleSender; + + /** + * Gets the console sender for printing to the console + * @return

The console's console sender

+ */ + public static ConsoleCommandSender getConsoleSender() { + return consoleSender; + } + + /** + * Gets available books + * @param sender

The sender wanting to see available books

+ * @param getPublic

Whether to get available public books

+ * @return

A list of available books

+ */ + public static List getAvailableBooks(CommandSender sender, boolean getPublic) { + if (getPublic) { + return new ArrayList<>(publicBooksList); + } else { + String senderName = sender.getName(); + if (!playerBooksList.containsKey(senderName)) { + List newFiles = FileHelper.listFiles(sender, false); + playerBooksList.put(senderName, newFiles); + } + return playerBooksList.get(senderName); + } + } + + /** + * Updates available books + * @param sender

The sender to update books for

+ * @param updatePublic

Whether to update public books

+ */ + public static void updateBooks(CommandSender sender, boolean updatePublic) { + List newFiles = FileHelper.listFiles(sender, updatePublic); + if (updatePublic) { + publicBooksList = newFiles; + } else { + playerBooksList.put(sender.getName(), newFiles); + } + } @Override public void onEnable() { booksWithoutBorders = this; consoleSender = this.getServer().getConsoleSender(); - loadList = new HashMap<>(); + playerBooksList = new HashMap<>(); + publicBooksList = FileHelper.listFiles(consoleSender, true); firstBooks = new ArrayList<>(); BooksWithoutBordersSettings.initialize(this); @@ -394,38 +438,61 @@ public class BooksWithoutBorders extends JavaPlugin { return true; } - public ItemStack loadBook(CommandSender sender, String fileName, String isSigned, String dir) { - return loadBook(sender, fileName, isSigned, dir, 1); + /** + * Loads the given book + * @param sender

The command sender trying to load the book

+ * @param fileName

The index or file name of the book to load

+ * @param isSigned

Whether to load the book as signed, and not unsigned

+ * @param directory

The directory to save the book in

+ * @return

The loaded book

+ */ + public ItemStack loadBook(CommandSender sender, String fileName, String isSigned, String directory) { + return loadBook(sender, fileName, isSigned, directory, 1); } - public ItemStack loadBook(CommandSender sender, String fileName, String isSigned, String dir, int numCopies) { - //checks if player is using list number to load - for (int x = 0; x < fileName.length(); x++) { - if (!Character.isDigit(fileName.charAt(x))) { - break; - } - if (x == fileName.length() - 1 && Character.isDigit(fileName.charAt(x)) && loadList.containsKey(sender.getName())) { - if (Integer.parseInt(fileName) <= loadList.get(sender.getName()).size()) { - fileName = loadList.get(sender.getName()).get(Integer.parseInt(fileName) - 1); - } - } - } + /** + * Loads the given book + * @param sender

The command sender trying to load the book

+ * @param fileName

The index or file name of the book to load

+ * @param isSigned

Whether to load the book as signed, and not unsigned

+ * @param directory

The directory to save the book in

+ * @param numCopies

The number of copies to load

+ * @return

The loaded book

+ */ + public ItemStack loadBook(CommandSender sender, String fileName, String isSigned, String directory, int numCopies) { + BookDirectory bookDirectory = BookDirectory.getFromString(directory); - File file; - if (dir.equalsIgnoreCase("public")) { + //Find the filename if a book index is given + try { + int bookIndex = Integer.parseInt(fileName); + List availableFiles = getAvailableBooks(sender, bookDirectory == BookDirectory.PUBLIC); + if (bookIndex <= availableFiles.size()) { + fileName = availableFiles.get(Integer.parseInt(fileName) - 1); + } + } catch (NumberFormatException ignored) {} + + //Get the full path of the book to load + File file = null; + if (bookDirectory == BookDirectory.PUBLIC) { file = FileHelper.getBookFile(getBookFolder() + fileName); - } else if (dir.equalsIgnoreCase("player")) { + } else if (bookDirectory == BookDirectory.PLAYER) { file = FileHelper.getBookFile(getBookFolder() + cleanString(sender.getName()) + getSlash() + fileName); - } else if (!dir.trim().isEmpty()) { - file = FileHelper.getBookFile(getBookFolder() + "Encrypted" + getSlash() + dir + getSlash() + fileName); - } else { - file = null; + } else if (bookDirectory == BookDirectory.ENCRYPTED) { + file = FileHelper.getBookFile(getBookFolder() + "Encrypted" + getSlash() + directory + getSlash() + fileName); } if (file == null || !file.isFile()) { sendErrorMessage(sender, "Incorrect file name!"); return null; } + //Make sure the player can pay for the book + if (booksHavePrice() && !sender.hasPermission("bookswithoutborders.bypassBookPrice") && + (bookDirectory == BookDirectory.PUBLIC || bookDirectory == BookDirectory.PLAYER) && + cannotPayForBookPrinting((Player) sender, numCopies)) { + return null; + } + + //Generate a new empty book ItemStack book; BookMeta bookMetadata = (BookMeta) itemFactory.getItemMeta(Material.WRITTEN_BOOK); if (isSigned.equalsIgnoreCase("true")) { @@ -434,14 +501,15 @@ public class BooksWithoutBorders extends JavaPlugin { book = new ItemStack(Material.WRITABLE_BOOK); } - BookToFromTextHelper.bookFromYml(file, bookMetadata); + //Load the book from the given file + BookToFromTextHelper.bookFromFile(file, bookMetadata); if (bookMetadata == null) { sendErrorMessage(sender, "File was blank!!"); return null; } - if (!dir.equalsIgnoreCase("public") && !dir.equalsIgnoreCase("player") && - !dir.equalsIgnoreCase("") && bookMetadata.hasLore()) { + //Remove "encrypted" from the book lore + if (bookDirectory == BookDirectory.ENCRYPTED && bookMetadata.hasLore()) { List oldLore = bookMetadata.getLore(); if (oldLore != null) { List newLore = new ArrayList<>(oldLore); @@ -450,16 +518,10 @@ public class BooksWithoutBorders extends JavaPlugin { } } + //Set the metadata and amount to the new book book.setItemMeta(bookMetadata); book.setAmount(numCopies); - if (booksHavePrice() && !sender.hasPermission("bookswithoutborders.bypassBookPrice") && - (dir.equalsIgnoreCase("public") || dir.equalsIgnoreCase("player") || - dir.equalsIgnoreCase("")) && - cannotPayForBookPrinting((Player) sender, numCopies)) { - return null; - } - return book; } diff --git a/src/main/java/net/knarcraft/bookswithoutborders/command/CommandDelete.java b/src/main/java/net/knarcraft/bookswithoutborders/command/CommandDelete.java index 58488cb..af160f3 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/command/CommandDelete.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/command/CommandDelete.java @@ -9,6 +9,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.io.File; +import java.util.List; import static net.knarcraft.bookswithoutborders.BooksWithoutBordersSettings.getBookFolder; import static net.knarcraft.bookswithoutborders.BooksWithoutBordersSettings.getSlash; @@ -39,17 +40,20 @@ public class CommandDelete implements CommandExecutor { boolean deleteBook(CommandSender sender, String[] args, boolean deletePublic) { //List deletable files if (args.length == 0) { - BooksWithoutBorders.loadList.put(sender.getName(), FileHelper.listFiles(sender, deletePublic, false)); + FileHelper.printBooks(sender, deletePublic); return true; } //Delete the file if (args.length == 1) { - if (!BooksWithoutBorders.loadList.containsKey(sender.getName())) { - BooksWithoutBorders.sendErrorMessage(sender, "You must first use /bwb delete to create a list of delete-able files!"); + List availableBooks = BooksWithoutBorders.getAvailableBooks(sender, deletePublic); + if (availableBooks == null) { + BooksWithoutBorders.sendErrorMessage(sender, "You must first use /deletebook to create a list of delete-able files!"); return false; } else { - if (!BooksWithoutBorders.loadList.get(sender.getName()).isEmpty()) { + if (!availableBooks.isEmpty()) { performBookDeletion(sender, args[0], deletePublic); + //Update the book list + BooksWithoutBorders.updateBooks(sender, deletePublic); return true; } else { BooksWithoutBorders.sendErrorMessage(sender, "No files available to delete!"); @@ -72,9 +76,9 @@ public class CommandDelete implements CommandExecutor { //If the file name is an index of the load list, load the book try { int loadListIndex = Integer.parseInt(fileName); - String senderName = sender.getName(); - if (BooksWithoutBorders.loadList.containsKey(senderName) && loadListIndex <= BooksWithoutBorders.loadList.get(senderName).size()) { - fileName = BooksWithoutBorders.loadList.get(senderName).get(loadListIndex - 1); + List availableBooks = BooksWithoutBorders.getAvailableBooks(sender, isPublic); + if (loadListIndex <= availableBooks.size()) { + fileName = availableBooks.get(loadListIndex - 1); } } catch (NumberFormatException ignored) { } diff --git a/src/main/java/net/knarcraft/bookswithoutborders/command/CommandGive.java b/src/main/java/net/knarcraft/bookswithoutborders/command/CommandGive.java index 69c0743..402ee64 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/command/CommandGive.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/command/CommandGive.java @@ -26,6 +26,14 @@ public class CommandGive implements CommandExecutor { return giveBook(sender, args, false, "player"); } + /** + * Gives a book to another player + * @param sender

The sender trying to give a book

+ * @param args

The arguments given

+ * @param givePublic

Whether to give a public book

+ * @param folder

The folder containing the book to load

+ * @return

True if the book was given successfully

+ */ boolean giveBook(CommandSender sender, String[] args, boolean givePublic, String folder) { if (args.length == 1 || args.length > 4) { BooksWithoutBorders.sendErrorMessage(sender, "Incorrect number of arguments for this command!"); @@ -33,7 +41,7 @@ public class CommandGive implements CommandExecutor { } if (args.length == 0) { - BooksWithoutBorders.loadList.put(sender.getName(), FileHelper.listFiles(sender, givePublic, false)); + FileHelper.printBooks(sender, givePublic); return true; } @@ -56,7 +64,7 @@ public class CommandGive implements CommandExecutor { //Load books available to the player try { Integer.parseInt(bookIdentifier); - BooksWithoutBorders.loadList.put(sender.getName(), FileHelper.listFiles(sender, givePublic, true)); + BooksWithoutBorders.updateBooks(sender, givePublic); } catch (NumberFormatException ignored) { } diff --git a/src/main/java/net/knarcraft/bookswithoutborders/command/CommandLoad.java b/src/main/java/net/knarcraft/bookswithoutborders/command/CommandLoad.java index 123a7b8..117b659 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/command/CommandLoad.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/command/CommandLoad.java @@ -45,7 +45,7 @@ public class CommandLoad implements CommandExecutor { //Show books available to the player if (argumentCount == 0) { - BooksWithoutBorders.loadList.put(sender.getName(), FileHelper.listFiles(player, loadPublic, false)); + FileHelper.printBooks(sender, loadPublic); return true; } @@ -67,13 +67,13 @@ public class CommandLoad implements CommandExecutor { //Load books available to the player try { Integer.parseInt(bookIdentifier); - BooksWithoutBorders.loadList.put(player.getName(), FileHelper.listFiles(player, loadPublic, true)); + BooksWithoutBorders.updateBooks(sender, loadPublic); } catch (NumberFormatException ignored) { } String bookToLoad = InputCleaningHelper.cleanString(bookIdentifier); try { - //Give the new book if it cannot be loaded + //Give the new book if it can be loaded ItemStack newBook = booksWithoutBorders.loadBook(player, bookToLoad, isSigned, directory, Integer.parseInt(copies)); if (newBook != null) { player.getInventory().addItem(newBook); diff --git a/src/main/java/net/knarcraft/bookswithoutborders/command/CommandSave.java b/src/main/java/net/knarcraft/bookswithoutborders/command/CommandSave.java index da6353d..ec162f0 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/command/CommandSave.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/command/CommandSave.java @@ -136,6 +136,8 @@ public class CommandSave implements CommandExecutor { BookToFromTextHelper.bookToTXT(savePath, fileName, book); } + //Update the relevant book list + BooksWithoutBorders.updateBooks(player, saveToPublicFolder); BooksWithoutBorders.sendSuccessMessage(player, "Book Saved as \"" + fileName + "\""); } catch (IOException e) { e.printStackTrace(); diff --git a/src/main/java/net/knarcraft/bookswithoutborders/command/GiveTabCompleter.java b/src/main/java/net/knarcraft/bookswithoutborders/command/GiveTabCompleter.java index 31209d5..afb8e0b 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/command/GiveTabCompleter.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/command/GiveTabCompleter.java @@ -49,7 +49,7 @@ public class GiveTabCompleter implements TabCompleter { if (argumentCount == 1) { //Return list of books - return BooksWithoutBorders.loadList.put(sender.getName(), FileHelper.listFiles(sender, false, true)); + return BooksWithoutBorders.getAvailableBooks(sender, false); } else if (argumentCount == 2) { //Return online players return playerNames; diff --git a/src/main/java/net/knarcraft/bookswithoutborders/listener/PlayerEventListener.java b/src/main/java/net/knarcraft/bookswithoutborders/listener/PlayerEventListener.java index 4f2fc25..5da2d57 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/listener/PlayerEventListener.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/listener/PlayerEventListener.java @@ -1,7 +1,6 @@ package net.knarcraft.bookswithoutborders.listener; import net.knarcraft.bookswithoutborders.BooksWithoutBorders; -import net.knarcraft.bookswithoutborders.utility.FileHelper; import net.knarcraft.bookswithoutborders.utility.InputCleaningHelper; import net.knarcraft.bookswithoutborders.utility.InventoryHelper; import org.bukkit.Material; @@ -16,11 +15,9 @@ import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import java.io.File; -import java.util.List; import static net.knarcraft.bookswithoutborders.BooksWithoutBordersSettings.getBookFolder; import static net.knarcraft.bookswithoutborders.BooksWithoutBordersSettings.getSlash; -import static net.knarcraft.bookswithoutborders.utility.FileHelper.isBookListIndex; public class PlayerEventListener implements Listener { @@ -90,12 +87,6 @@ public class PlayerEventListener implements Listener { private boolean giveBookToNewPlayer(String bookName, Player player, boolean sendMessage) { if (!bookName.trim().isEmpty()) { - //Handles loadList numbers - if (isBookListIndex(bookName)) { - List availableFiles = FileHelper.listFiles(player, true, true); - BooksWithoutBorders.loadList.put(player.getName(), availableFiles); - } - //Give the book to the player if it exists ItemStack newBook = booksWithoutBorders.loadBook(player, bookName, "true", "public"); if (newBook != null) { diff --git a/src/main/java/net/knarcraft/bookswithoutborders/listener/SignEventListener.java b/src/main/java/net/knarcraft/bookswithoutborders/listener/SignEventListener.java index 8153c9e..943badc 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/listener/SignEventListener.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/listener/SignEventListener.java @@ -21,7 +21,6 @@ import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.BookMeta; import java.io.File; -import java.util.List; import static net.knarcraft.bookswithoutborders.BooksWithoutBordersSettings.getBookFolder; import static net.knarcraft.bookswithoutborders.BooksWithoutBordersSettings.getSlash; @@ -191,8 +190,7 @@ public class SignEventListener implements Listener { return; } else { if (isBookListIndex(lines[2])) { - List availableFiles = FileHelper.listFiles(player, true, true); - BooksWithoutBorders.loadList.put(player.getName(), availableFiles); + BooksWithoutBorders.updateBooks(player, true); markGiveSignValidity(event, true); return; } @@ -295,17 +293,16 @@ public class SignEventListener implements Listener { String fileName = ChatColor.stripColor(sign.getLine(2)); boolean isLoadListNumber = false; - for (int x = 0; x < fileName.length(); x++) { - if (!Character.isDigit(fileName.charAt(x))) - break; - if (x == fileName.length() - 1) { - BooksWithoutBorders.loadList.put(player.getName(), FileHelper.listFiles(player, true, true)); - isLoadListNumber = true; - } - } + try { + Integer.parseInt(fileName); + isLoadListNumber = true; + } catch (NumberFormatException ignored){} - if (!isLoadListNumber && sign.getLine(3).length() >= 2) - fileName = ChatColor.stripColor(sign.getLine(2)) + ChatColor.stripColor(sign.getLine(3)); + //Add the third line to the second line for the full filename + String thirdLine = sign.getLine(3); + if (!isLoadListNumber && thirdLine.length() >= 2) { + fileName += ChatColor.stripColor(thirdLine); + } ItemStack newBook = BooksWithoutBorders.getInstance().loadBook(player, fileName, "true", "public"); diff --git a/src/main/java/net/knarcraft/bookswithoutborders/state/BookDirectory.java b/src/main/java/net/knarcraft/bookswithoutborders/state/BookDirectory.java new file mode 100644 index 0000000..b5eb10e --- /dev/null +++ b/src/main/java/net/knarcraft/bookswithoutborders/state/BookDirectory.java @@ -0,0 +1,27 @@ +package net.knarcraft.bookswithoutborders.state; + +/** + * This enum represents the different directories books can be saved in + */ +public enum BookDirectory { + PUBLIC, + PLAYER, + ENCRYPTED; + + /** + * Gets the relevant book directory given a directory name + * @param directory

The directory to transform

+ * @return

A book directory, or null if the given directory is empty

+ */ + public static BookDirectory getFromString(String directory) { + if (directory.equalsIgnoreCase("public")) { + return BookDirectory.PUBLIC; + } else if (directory.equalsIgnoreCase("player")) { + return BookDirectory.PLAYER; + } else if (!directory.trim().isEmpty()) { + return BookDirectory.ENCRYPTED; + } else { + return null; + } + } +} diff --git a/src/main/java/net/knarcraft/bookswithoutborders/utility/BookToFromTextHelper.java b/src/main/java/net/knarcraft/bookswithoutborders/utility/BookToFromTextHelper.java index 0bea557..a74be33 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/utility/BookToFromTextHelper.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/utility/BookToFromTextHelper.java @@ -52,30 +52,19 @@ public final class BookToFromTextHelper { } /** - * Loads a book from a .yml file - * - * @param file

The path of the file to load

- * @param bookMetadata

Metadata which will be altered with the book's contents

- * @return

Metadata for the loaded book

+ * Loads a book from a file + * @param file

The file to load

+ * @param bookMetadata

The book metadata to use for saving the book

+ * @return

The book metadata of the loaded book

*/ - public static BookMeta bookFromYml(File file, BookMeta bookMetadata) { - //Handles old style loading - if (file.getName().substring(file.getName().lastIndexOf(".")).equals(".txt")) - bookMetadata = bookFromTXT(file.getName(), file, bookMetadata); - else { - try { - FileConfiguration bookYml = YamlConfiguration.loadConfiguration(file); - - bookMetadata.setTitle(bookYml.getString("Title", "Untitled")); - bookMetadata.setAuthor(bookYml.getString("Author", "Unknown")); - bookMetadata.setPages(bookYml.getStringList("Pages")); - bookMetadata.setLore(bookYml.getStringList("Lore")); - } catch (IllegalArgumentException e) { - return null; - } + public static BookMeta bookFromFile(File file, BookMeta bookMetadata) { + if (file.getName().endsWith(".txt")) { + return bookFromTXT(file.getName(), file, bookMetadata); + } else if (file.getName().endsWith(".yml")) { + return bookFromYml(file, bookMetadata); + } else { + throw new IllegalArgumentException("Trying to load a book file with an unrecognized extension"); } - - return bookMetadata; } /** @@ -91,6 +80,7 @@ public final class BookToFromTextHelper { PrintWriter printWriter = new PrintWriter(fileWriter); List pages = bookMetadata.getPages(); + //Save each page of the book as a text line printWriter.println("[Book]"); for (String page : pages) { printWriter.println(page); @@ -98,6 +88,27 @@ public final class BookToFromTextHelper { printWriter.close(); } + /** + * Loads a book from a .yml file + * + * @param file

The path of the file to load

+ * @param bookMetadata

Metadata which will be altered with the book's contents

+ * @return

Metadata for the loaded book

+ */ + private static BookMeta bookFromYml(File file, BookMeta bookMetadata) { + try { + FileConfiguration bookYml = YamlConfiguration.loadConfiguration(file); + + bookMetadata.setTitle(bookYml.getString("Title", "Untitled")); + bookMetadata.setAuthor(bookYml.getString("Author", "Unknown")); + bookMetadata.setPages(bookYml.getStringList("Pages")); + bookMetadata.setLore(bookYml.getStringList("Lore")); + } catch (IllegalArgumentException e) { + return null; + } + return bookMetadata; + } + /** * Loads a book from a text file * @@ -111,6 +122,7 @@ public final class BookToFromTextHelper { String title; String titleAuthorSeparator = BooksWithoutBorders.getTitleAuthorSeparator(); + //Get title and author from the file name if (fileName.contains(titleAuthorSeparator)) { author = fileName.substring(fileName.indexOf(titleAuthorSeparator) + 1, fileName.length() - 4); title = fileName.substring(0, fileName.indexOf(titleAuthorSeparator)); @@ -119,45 +131,22 @@ public final class BookToFromTextHelper { title = fileName.substring(0, fileName.length() - 4); } + //Replace underscores with spaces title = fixName(title, true); - List rawPages = new ArrayList<>(); - String nullCheck; - + //Read the .txt file + List rawPages; try { - FileReader fileReader = new FileReader(file); - BufferedReader bufferedReader = new BufferedReader(fileReader); - - rawPages.add(bufferedReader.readLine()); - - if (rawPages.get(0) == null) { - bufferedReader.close(); - return null; - } - - //If a book is being loaded its content need not be adjusted - if (rawPages.get(0).equalsIgnoreCase("[Book]")) { - rawPages.remove(0); - nullCheck = bufferedReader.readLine(); - while (nullCheck != null) { - rawPages.add(nullCheck); - nullCheck = bufferedReader.readLine(); - } - } else { - //Adjusts content to page length - while (rawPages.get(rawPages.size() - 1) != null) { - BookFormatter.formatLastPage(rawPages); - rawPages.add(bufferedReader.readLine()); - } - } - bufferedReader.close(); + rawPages = readTextFile(file); } catch (IOException e) { e.printStackTrace(); return null; } + //Remove any empty pages List pages = new ArrayList<>(InputCleaningHelper.cleanList(rawPages)); + //Update the metadata of the book with its new values bookMetadata.setAuthor(author); bookMetadata.setTitle(title); bookMetadata.setPages(pages); @@ -165,4 +154,43 @@ public final class BookToFromTextHelper { return bookMetadata; } + /** + * Reads text from a .txt file + * @param file

The file to read

+ * @return

A string list where each string is the text on one page

+ * @throws IOException

If unable to read from the file

+ */ + private static List readTextFile(File file) throws IOException { + List rawPages = new ArrayList<>(); + BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); + + //Use the first line to decide if we are loading a book, or creating a new book + String firstLine = bufferedReader.readLine(); + if (firstLine == null) { + bufferedReader.close(); + return null; + } + if (firstLine.equalsIgnoreCase("[Book]")) { + //Read every line directly as a page, as this is a saved book + String readLine; + do { + readLine = bufferedReader.readLine(); + if (readLine != null) { + rawPages.add(readLine); + } + } while (readLine != null); + } else { + //Adjust content to page length for each added line to make the text fit the book + rawPages.add(firstLine); + while (rawPages.get(rawPages.size() - 1) != null) { + BookFormatter.formatLastPage(rawPages); + rawPages.add(bufferedReader.readLine()); + } + BookFormatter.formatLastPage(rawPages); + } + bufferedReader.close(); + + return rawPages; + } + } diff --git a/src/main/java/net/knarcraft/bookswithoutborders/utility/EncryptionHelper.java b/src/main/java/net/knarcraft/bookswithoutborders/utility/EncryptionHelper.java index 696fb5e..0df4014 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/utility/EncryptionHelper.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/utility/EncryptionHelper.java @@ -6,6 +6,7 @@ import net.knarcraft.bookswithoutborders.encryption.SubstitutionCipher; import net.knarcraft.bookswithoutborders.state.EncryptionStyle; import org.bukkit.ChatColor; import org.bukkit.Material; +import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; @@ -213,7 +214,7 @@ public final class EncryptionHelper { } } else { try { - bookMetadata = BookToFromTextHelper.bookFromYml(file, bookMetadata); + bookMetadata = BookToFromTextHelper.bookFromFile(file, bookMetadata); } catch (Exception e) { BooksWithoutBorders.sendErrorMessage(player, "Decryption failed!"); return null; @@ -221,14 +222,15 @@ public final class EncryptionHelper { } if (deleteEncryptedFile) { + ConsoleCommandSender consoleSender = BooksWithoutBorders.getConsoleSender(); try { if (!file.delete()) { - BooksWithoutBorders.sendErrorMessage(BooksWithoutBorders.consoleSender, "Book encryption data failed to delete upon decryption!"); - BooksWithoutBorders.sendErrorMessage(BooksWithoutBorders.consoleSender, "File location:" + file.getPath()); + BooksWithoutBorders.sendErrorMessage(consoleSender, "Book encryption data failed to delete upon decryption!"); + BooksWithoutBorders.sendErrorMessage(consoleSender, "File location:" + file.getPath()); } } catch (Exception e) { - BooksWithoutBorders.sendErrorMessage(BooksWithoutBorders.consoleSender, "Book encryption data failed to delete upon decryption!"); - BooksWithoutBorders.sendErrorMessage(BooksWithoutBorders.consoleSender, "File location:" + file.getPath()); + BooksWithoutBorders.sendErrorMessage(consoleSender, "Book encryption data failed to delete upon decryption!"); + BooksWithoutBorders.sendErrorMessage(consoleSender, "File location:" + file.getPath()); } } @@ -253,7 +255,7 @@ public final class EncryptionHelper { if (!dirTest.exists()) { try { if (!dirTest.mkdir()) { - BooksWithoutBorders.sendErrorMessage(BooksWithoutBorders.consoleSender, "Unable to create encryption group folder!"); + BooksWithoutBorders.sendErrorMessage(BooksWithoutBorders.getConsoleSender(), "Unable to create encryption group folder!"); return null; } } catch (Exception e) { diff --git a/src/main/java/net/knarcraft/bookswithoutborders/utility/FileHelper.java b/src/main/java/net/knarcraft/bookswithoutborders/utility/FileHelper.java index 1a637b3..d3e29de 100644 --- a/src/main/java/net/knarcraft/bookswithoutborders/utility/FileHelper.java +++ b/src/main/java/net/knarcraft/bookswithoutborders/utility/FileHelper.java @@ -92,17 +92,39 @@ public final class FileHelper { * * @param sender

The command sender looking for files

* @param listPublic

Whether to list public or personal files

- * @param silent

Whether to just return the list without printing it

* @return

A list of available files

*/ - public static List listFiles(CommandSender sender, Boolean listPublic, boolean silent) { + public static List listFiles(CommandSender sender, Boolean listPublic) { File file; if (listPublic) { file = new File(getBookFolder()); } else { file = new File(getBookFolder() + cleanString(sender.getName()) + getSlash()); } - return FileHelper.listFiles(sender, file, silent); + return FileHelper.listFiles(sender, file); + } + + /** + * Prints the available books + * @param sender

The sender to display the books to

+ * @param listPublic

Whether to display public books

+ */ + public static void printBooks(CommandSender sender, boolean listPublic) { + List availableBooks = BooksWithoutBorders.getAvailableBooks(sender, listPublic); + FileHelper.printFiles(sender, availableBooks); + } + + /** + * Prints a list of files + * @param sender

The command sender to show the list to

+ * @param fileList

The files to list

+ */ + public static void printFiles(CommandSender sender, List fileList) { + BooksWithoutBorders.sendSuccessMessage(sender, "Available Books:"); + int listSize = fileList.size(); + for (int fileIndex = 0; fileIndex < listSize; fileIndex++) { + sender.sendMessage(ChatColor.GRAY + "[" + (fileIndex + 1) + "] " + fileList.get(fileIndex)); + } } /** @@ -110,10 +132,9 @@ public final class FileHelper { * * @param sender

The command sender looking for files

* @param searchDirectory

The directory to search for files

- * @param silent

Whether to just return the list without printing it

* @return

A list of available files

*/ - public static List listFiles(CommandSender sender, File searchDirectory, boolean silent) { + private static List listFiles(CommandSender sender, File searchDirectory) { List fileList = new ArrayList<>(); File[] existingFiles = searchDirectory.listFiles(); @@ -122,15 +143,9 @@ public final class FileHelper { return null; } - if (!silent) { - BooksWithoutBorders.sendSuccessMessage(sender, "Available Books:"); - } for (File foundFile : existingFiles) { if (foundFile.isFile()) { fileList.add(foundFile.getName()); - if (!silent) { - sender.sendMessage(ChatColor.GRAY + "[" + fileList.size() + "] " + foundFile.getName()); - } } }