Changes some static classes into instantiated classes

This commit is contained in:
2025-08-07 20:10:30 +02:00
parent 150dff7a03
commit aa02f5ca2b
30 changed files with 476 additions and 345 deletions

View File

@@ -59,11 +59,6 @@ import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getBookFolder;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getErrorColor;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getSlash;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getSuccessColor;
/** /**
* The main Books Without Borders class * The main Books Without Borders class
*/ */
@@ -77,6 +72,26 @@ public class BooksWithoutBorders extends JavaPlugin {
private static BooksWithoutBorders booksWithoutBorders; private static BooksWithoutBorders booksWithoutBorders;
private static BookshelfHandler bookshelfHandler; private static BookshelfHandler bookshelfHandler;
private static StringFormatter stringFormatter; private static StringFormatter stringFormatter;
private static BooksWithoutBordersConfig booksWithoutBordersConfig;
/**
* Logs a message to the console
*
* @param level <p>The log level to use</p>
* @param message <p>The message to log</p>
*/
public static void log(@NotNull Level level, @NotNull String message) {
getInstance().getLogger().log(level, message);
}
/**
* Gets the configuration for BwB
*
* @return <p>The BwB configuration</p>
*/
public static BooksWithoutBordersConfig getConfiguration() {
return booksWithoutBordersConfig;
}
/** /**
* Gets the string formatter * Gets the string formatter
@@ -178,7 +193,7 @@ public class BooksWithoutBorders extends JavaPlugin {
booksWithoutBorders = this; booksWithoutBorders = this;
playerBooksList = new HashMap<>(); playerBooksList = new HashMap<>();
playerLetterIndex = new HashMap<>(); playerLetterIndex = new HashMap<>();
BooksWithoutBordersConfig.initialize(this, translator); booksWithoutBordersConfig = new BooksWithoutBordersConfig(this, translator);
@Nullable List<String> files = BookFileHelper.listFiles(this.getServer().getConsoleSender(), true); @Nullable List<String> files = BookFileHelper.listFiles(this.getServer().getConsoleSender(), true);
if (files != null) { if (files != null) {
publicBooksList = files; publicBooksList = files;
@@ -189,7 +204,7 @@ public class BooksWithoutBorders extends JavaPlugin {
PluginManager pluginManager = this.getServer().getPluginManager(); PluginManager pluginManager = this.getServer().getPluginManager();
if (getSlash() != null && initialize()) { if (getConfiguration().getSlash() != null && initialize()) {
pluginManager.registerEvents(new PlayerEventListener(), this); pluginManager.registerEvents(new PlayerEventListener(), this);
pluginManager.registerEvents(new SignEventListener(), this); pluginManager.registerEvents(new SignEventListener(), this);
pluginManager.registerEvents(new BookEventListener(), this); pluginManager.registerEvents(new BookEventListener(), this);
@@ -276,12 +291,12 @@ public class BooksWithoutBorders extends JavaPlugin {
} }
//Load config //Load config
if (!BooksWithoutBordersConfig.loadConfig()) { if (!getConfiguration().loadConfig()) {
return false; return false;
} }
//Save config with loaded values to fix invalid config values //Save config with loaded values to fix invalid config values
BooksWithoutBordersConfig.saveConfigValues(); getConfiguration().saveConfigValues();
return testFileSaving(); return testFileSaving();
} }
@@ -311,8 +326,8 @@ public class BooksWithoutBorders extends JavaPlugin {
* @return <p>True if necessary folders exist</p> * @return <p>True if necessary folders exist</p>
*/ */
private boolean testFileSaving() { private boolean testFileSaving() {
File fileTest = new File(getBookFolder()); File fileTest = new File(getConfiguration().getBookFolder());
File encryptedFileTest = new File(getBookFolder() + "Encrypted" + getSlash()); File encryptedFileTest = new File(getConfiguration().getEncryptedBookPath());
if (!fileTest.exists()) { if (!fileTest.exists()) {
try { try {
if (!fileTest.mkdir()) { if (!fileTest.mkdir()) {
@@ -345,7 +360,7 @@ public class BooksWithoutBorders extends JavaPlugin {
* @param message <p>The message to send</p> * @param message <p>The message to send</p>
*/ */
public static void sendSuccessMessage(@NotNull CommandSender sender, @NotNull String message) { public static void sendSuccessMessage(@NotNull CommandSender sender, @NotNull String message) {
sender.sendMessage(getSuccessColor() + message); sender.sendMessage(getConfiguration().getSuccessColor() + message);
} }
/** /**
@@ -355,7 +370,7 @@ public class BooksWithoutBorders extends JavaPlugin {
* @param message <p>The message to send</p> * @param message <p>The message to send</p>
*/ */
public static void sendErrorMessage(@NotNull CommandSender sender, @NotNull String message) { public static void sendErrorMessage(@NotNull CommandSender sender, @NotNull String message) {
sender.sendMessage(getErrorColor() + message); sender.sendMessage(getConfiguration().getErrorColor() + message);
} }
} }

View File

@@ -6,7 +6,7 @@ import net.knarcraft.bookswithoutborders.config.BwBCommand;
import net.knarcraft.bookswithoutborders.config.Permission; import net.knarcraft.bookswithoutborders.config.Permission;
import net.knarcraft.bookswithoutborders.config.StaticMessage; import net.knarcraft.bookswithoutborders.config.StaticMessage;
import net.knarcraft.bookswithoutborders.config.Translatable; import net.knarcraft.bookswithoutborders.config.Translatable;
import net.knarcraft.bookswithoutborders.utility.EconomyHelper; import net.knarcraft.bookswithoutborders.manager.EconomyManager;
import net.knarcraft.knarlib.formatting.StringFormatter; import net.knarcraft.knarlib.formatting.StringFormatter;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@@ -57,20 +57,27 @@ public class CommandBooksWithoutBorders implements TabExecutor {
*/ */
@NotNull @NotNull
private String getBookPrice() { private String getBookPrice() {
if (!BooksWithoutBordersConfig.booksHavePrice()) { BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
if (!config.booksHavePrice()) {
return ""; return "";
} }
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter(); StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
Material bookPriceType = BooksWithoutBordersConfig.getBookPriceType(); Material bookPriceType = config.getBookPriceType();
double bookPriceQuantity = BooksWithoutBordersConfig.getBookPriceQuantity(); double bookPriceQuantity = config.getBookPriceQuantity();
if (bookPriceType != Material.AIR) { if (bookPriceType != Material.AIR) {
return stringFormatter.replacePlaceholders(Translatable.NEUTRAL_COMMANDS_BOOK_PRICE_ITEM, return stringFormatter.replacePlaceholders(Translatable.NEUTRAL_COMMANDS_BOOK_PRICE_ITEM,
List.of("{quantity}", "{type}"), List.of("{quantity}", "{type}"),
List.of(String.valueOf((int) bookPriceQuantity), bookPriceType.toString())); List.of(String.valueOf((int) bookPriceQuantity), bookPriceType.toString()));
} else { } else {
return stringFormatter.replacePlaceholder(Translatable.NEUTRAL_COMMANDS_BOOK_PRICE_ECO, EconomyManager economyManager = BooksWithoutBorders.getConfiguration().getEconomyManager();
"{price}", EconomyHelper.getEconomy().format(bookPriceQuantity)); if (economyManager.getEconomy() == null) {
return BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(Translatable.ERROR_VAULT_COST_BUT_UNAVAILABLE);
} else {
return stringFormatter.replacePlaceholder(Translatable.NEUTRAL_COMMANDS_BOOK_PRICE_ECO,
"{price}", economyManager.getEconomy().format(bookPriceQuantity));
}
} }
} }
@@ -114,7 +121,7 @@ public class CommandBooksWithoutBorders implements TabExecutor {
private String showCommandInfo(@NotNull String command, @NotNull CommandSender sender) { private String showCommandInfo(@NotNull String command, @NotNull CommandSender sender) {
PluginCommand pluginCommand = BooksWithoutBorders.getInstance().getCommand(command); PluginCommand pluginCommand = BooksWithoutBorders.getInstance().getCommand(command);
if (pluginCommand == null) { if (pluginCommand == null) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, StringFormatter.replacePlaceholder( BooksWithoutBorders.log(Level.SEVERE, StringFormatter.replacePlaceholder(
StaticMessage.COMMAND_NOT_REGISTERED.toString(), "{command}", command)); StaticMessage.COMMAND_NOT_REGISTERED.toString(), "{command}", command));
return ""; return "";
} }

View File

@@ -5,7 +5,6 @@ import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import net.knarcraft.bookswithoutborders.config.Permission; import net.knarcraft.bookswithoutborders.config.Permission;
import net.knarcraft.bookswithoutborders.config.Translatable; import net.knarcraft.bookswithoutborders.config.Translatable;
import net.knarcraft.bookswithoutborders.utility.BookHelper; import net.knarcraft.bookswithoutborders.utility.BookHelper;
import net.knarcraft.bookswithoutborders.utility.EconomyHelper;
import net.knarcraft.bookswithoutborders.utility.InventoryHelper; import net.knarcraft.bookswithoutborders.utility.InventoryHelper;
import net.knarcraft.bookswithoutborders.utility.TabCompletionTypeHelper; import net.knarcraft.bookswithoutborders.utility.TabCompletionTypeHelper;
import net.knarcraft.knarlib.formatting.StringFormatter; import net.knarcraft.knarlib.formatting.StringFormatter;
@@ -74,8 +73,10 @@ public class CommandCopy implements TabExecutor {
* @return <p>True if the copying was successful</p> * @return <p>True if the copying was successful</p>
*/ */
private boolean performCopy(int copies, @NotNull Player player, @NotNull ItemStack heldBook) { private boolean performCopy(int copies, @NotNull Player player, @NotNull ItemStack heldBook) {
BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
//Make sure the player owns the book if authorOnlyCopy is enabled //Make sure the player owns the book if authorOnlyCopy is enabled
if (BooksWithoutBordersConfig.getAuthorOnlyCopy() && if (config.getAuthorOnlyCopy() &&
!player.hasPermission(Permission.BYPASS_AUTHOR_ONLY_COPY.toString())) { !player.hasPermission(Permission.BYPASS_AUTHOR_ONLY_COPY.toString())) {
if (BookHelper.isNotAuthor(player, (BookMeta) Objects.requireNonNull(heldBook.getItemMeta()))) { if (BookHelper.isNotAuthor(player, (BookMeta) Objects.requireNonNull(heldBook.getItemMeta()))) {
return false; return false;
@@ -83,7 +84,7 @@ public class CommandCopy implements TabExecutor {
} }
BookMeta bookMeta = (BookMeta) heldBook.getItemMeta(); BookMeta bookMeta = (BookMeta) heldBook.getItemMeta();
if (BooksWithoutBordersConfig.changeGenerationOnCopy() && bookMeta != null) { if (config.changeGenerationOnCopy() && bookMeta != null) {
return copyNextGenerationBook(bookMeta, player, copies); return copyNextGenerationBook(bookMeta, player, copies);
} else { } else {
//Make sure the player can pay for the copying //Make sure the player can pay for the copying
@@ -105,9 +106,10 @@ public class CommandCopy implements TabExecutor {
* @return <p>True if the payment failed</p> * @return <p>True if the payment failed</p>
*/ */
private boolean paymentUnSuccessful(@NotNull Player player, int copies) { private boolean paymentUnSuccessful(@NotNull Player player, int copies) {
return BooksWithoutBordersConfig.booksHavePrice() && BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
return (config.booksHavePrice() &&
!player.hasPermission(Permission.BYPASS_BOOK_PRICE.toString()) && !player.hasPermission(Permission.BYPASS_BOOK_PRICE.toString()) &&
EconomyHelper.cannotPayForBookPrinting(player, copies); config.getEconomyManager().cannotPayForBookPrinting(player, copies));
} }
/** /**

View File

@@ -2,9 +2,12 @@ package net.knarcraft.bookswithoutborders.command;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import net.knarcraft.bookswithoutborders.config.Permission;
import net.knarcraft.bookswithoutborders.config.Translatable;
import net.knarcraft.bookswithoutborders.utility.BookHelper; import net.knarcraft.bookswithoutborders.utility.BookHelper;
import net.knarcraft.bookswithoutborders.utility.EncryptionHelper; import net.knarcraft.bookswithoutborders.utility.EncryptionHelper;
import net.knarcraft.bookswithoutborders.utility.InventoryHelper; import net.knarcraft.bookswithoutborders.utility.InventoryHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
@@ -17,39 +20,42 @@ import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getBookFolder;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getSlash;
/** /**
* Command executor for the decrypt command * Command executor for the decrypt command
*/ */
public class CommandDecrypt implements TabExecutor { public class CommandDecrypt implements TabExecutor {
@Override @Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label,
@NotNull String[] arguments) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
if (!(sender instanceof Player player)) { if (!(sender instanceof Player player)) {
BooksWithoutBorders.sendErrorMessage(sender, "This command can only be used by a player!"); BooksWithoutBorders.sendErrorMessage(sender, "This command can only be used by a player!");
return false; return false;
} }
if (InventoryHelper.notHoldingOneWrittenBookCheck(player, if (InventoryHelper.notHoldingOneWrittenBookCheck(player,
"You must be holding a written book to decrypt it!", stringFormatter.replacePlaceholder(Translatable.ERROR_NOT_HOLDING_WRITTEN_BOOK, "{action}",
"You cannot decrypt two books at once!")) { stringFormatter.getUnFormattedColoredMessage(Translatable.ACTION_DECRYPT)),
stringFormatter.replacePlaceholder(Translatable.ERROR_ONLY_ONE_BOOK, "{action}",
stringFormatter.getUnFormattedColoredMessage(Translatable.ACTION_DECRYPT)))) {
return false; return false;
} }
ItemStack heldItem = InventoryHelper.getHeldBook(player, true); ItemStack heldItem = InventoryHelper.getHeldBook(player, true);
BookMeta bookMetadata = (BookMeta) heldItem.getItemMeta(); BookMeta bookMetadata = (BookMeta) heldItem.getItemMeta();
if (bookMetadata == null) { if (bookMetadata == null) {
BooksWithoutBorders.sendErrorMessage(player, "Your book seems to be corrupt!"); stringFormatter.displayErrorMessage(sender, Translatable.ERROR_METADATA_MISSING);
return false; return false;
} }
//Warning: admin decrypt only allows decrypting files created by the same player. Not sure if intended BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
if (args.length == 0 && BooksWithoutBordersConfig.getAdminDecrypt() && player.hasPermission("bookswithoutborders.admin")) {
String path = getBookFolder() + "Encrypted" + getSlash();
File encryptedDirectory = new File(path); //Warning: admin decrypt only allows decrypting files created by the same player. Not sure if intended
if (arguments.length == 0 && config.getAdminDecrypt() && player.hasPermission(Permission.ADMIN.toString())) {
File encryptedDirectory = new File(config.getEncryptedBookPath());
String[] encryptedFiles = encryptedDirectory.list(); String[] encryptedFiles = encryptedDirectory.list();
if (encryptedFiles == null) { if (encryptedFiles == null) {
BooksWithoutBorders.sendErrorMessage(player, "Could not find any encrypted files!"); BooksWithoutBorders.sendErrorMessage(player, "Could not find any encrypted files!");
@@ -79,12 +85,12 @@ public class CommandDecrypt implements TabExecutor {
BooksWithoutBorders.sendErrorMessage(player, "No matching encrypted book found!"); BooksWithoutBorders.sendErrorMessage(player, "No matching encrypted book found!");
return false; return false;
} }
} else if (args.length == 0) { } else if (arguments.length == 0) {
BooksWithoutBorders.sendErrorMessage(player, "No decryption password given!"); BooksWithoutBorders.sendErrorMessage(player, "No decryption password given!");
return false; return false;
} }
String key = EncryptionHelper.getNumberKeyFromStringKey(args[0]); String key = EncryptionHelper.getNumberKeyFromStringKey(arguments[0]);
//Decrypt the book //Decrypt the book
ItemStack book = EncryptionHelper.loadEncryptedBook(player, key, true); ItemStack book = EncryptionHelper.loadEncryptedBook(player, key, true);

View File

@@ -121,25 +121,26 @@ public class CommandEncrypt implements TabExecutor {
int argumentsCount = args.length; int argumentsCount = args.length;
List<String> encryptionStyles = new ArrayList<>(); List<String> encryptionStyles = new ArrayList<>();
encryptionStyles.add("dna"); for (EncryptionStyle encryptionStyle : EncryptionStyle.values()) {
encryptionStyles.add("substitution"); encryptionStyles.add(encryptionStyle.toString());
}
if (argumentsCount == 1) { if (groupEncrypt) {
List<String> info = new ArrayList<>(); if (argumentsCount == 1) {
info.add("<password>"); return List.of("<group>");
return info; } else if (argumentsCount == 2) {
} else if (argumentsCount == 2) { return List.of("<password>");
if (groupEncrypt) { } else if (argumentsCount == 3) {
List<String> info = new ArrayList<>(); return TabCompletionHelper.filterMatchingStartsWith(encryptionStyles, args[2]);
info.add("<group>"); }
return info; } else {
} else { if (argumentsCount == 1) {
return List.of("<password>");
} else if (argumentsCount == 2) {
return TabCompletionHelper.filterMatchingStartsWith(encryptionStyles, args[1]); return TabCompletionHelper.filterMatchingStartsWith(encryptionStyles, args[1]);
} }
} else if (argumentsCount == 3 && groupEncrypt) {
return TabCompletionHelper.filterMatchingStartsWith(encryptionStyles, args[2]);
} }
return new ArrayList<>(); return List.of();
} }

View File

@@ -1,7 +1,6 @@
package net.knarcraft.bookswithoutborders.command; package net.knarcraft.bookswithoutborders.command;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
@@ -18,7 +17,7 @@ public class CommandReload implements TabExecutor {
@Override @Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label,
@NotNull String[] arguments) { @NotNull String[] arguments) {
if (BooksWithoutBordersConfig.loadConfig()) { if (BooksWithoutBorders.getConfiguration().loadConfig()) {
BooksWithoutBorders.sendSuccessMessage(sender, "BooksWithoutBorders configuration reloaded!"); BooksWithoutBorders.sendSuccessMessage(sender, "BooksWithoutBorders configuration reloaded!");
} else { } else {
BooksWithoutBorders.sendErrorMessage(sender, "Reload Failed!"); BooksWithoutBorders.sendErrorMessage(sender, "Reload Failed!");

View File

@@ -23,10 +23,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getCommandColor;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getErrorColor;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getTitleAuthorSeparator;
/** /**
* Command executor for the save command * Command executor for the save command
*/ */
@@ -78,8 +74,10 @@ public class CommandSave implements TabExecutor {
return; return;
} }
BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
//Only allow saving of own books if enabled //Only allow saving of own books if enabled
if (BooksWithoutBordersConfig.getAuthorOnlySave() && !saveToPublicFolder && if (config.getAuthorOnlySave() && !saveToPublicFolder &&
(!player.hasPermission("bookswithoutborders.bypassAuthorOnlySave") && (!player.hasPermission("bookswithoutborders.bypassAuthorOnlySave") &&
BookHelper.isNotAuthor(player, book))) { BookHelper.isNotAuthor(player, book))) {
return; return;
@@ -123,31 +121,31 @@ public class CommandSave implements TabExecutor {
if (foundDuplicates > 0) { if (foundDuplicates > 0) {
//TODO: Decide if this makes sense or needs to be changed //TODO: Decide if this makes sense or needs to be changed
//Skip duplicate book //Skip duplicate book
if (!fileName.contains("Untitled" + getTitleAuthorSeparator()) && !overwrite) { if (!fileName.contains("Untitled" + config.getTitleAuthorSeparator()) && !overwrite) {
BooksWithoutBorders.sendErrorMessage(player, "Book is already saved!"); BooksWithoutBorders.sendErrorMessage(player, "Book is already saved!");
BooksWithoutBorders.sendErrorMessage(player, "Use " + getCommandColor() + (saveToPublicFolder ? BooksWithoutBorders.sendErrorMessage(player, "Use " + config.getCommandColor() + (saveToPublicFolder ?
"/savepublicbook" : "/savebook") + "true " + getErrorColor() + "to overwrite!"); "/savepublicbook" : "/savebook") + "true " + config.getErrorColor() + "to overwrite!");
return; return;
} }
//Skip if duplicate limit is reached //Skip if duplicate limit is reached
if (foundDuplicates > BooksWithoutBordersConfig.getBookDuplicateLimit()) { if (foundDuplicates > config.getBookDuplicateLimit()) {
BooksWithoutBorders.sendErrorMessage(player, "Maximum amount of " + fileName + BooksWithoutBorders.sendErrorMessage(player, "Maximum amount of " + fileName +
" duplicates reached!"); " duplicates reached!");
BooksWithoutBorders.sendErrorMessage(player, "Use " + getCommandColor() + (saveToPublicFolder ? BooksWithoutBorders.sendErrorMessage(player, "Use " + config.getCommandColor() + (saveToPublicFolder ?
"/savepublicbook" : "/savebook") + "true " + "/savepublicbook" : "/savebook") + "true " +
getErrorColor() + "to overwrite!"); config.getErrorColor() + "to overwrite!");
return; return;
} }
//Alter duplicated filename //Alter duplicated filename
if (fileName.contains("Untitled" + getTitleAuthorSeparator()) && !overwrite) { if (fileName.contains("Untitled" + config.getTitleAuthorSeparator()) && !overwrite) {
fileName = "(" + foundDuplicates + ")" + fileName; fileName = "(" + foundDuplicates + ")" + fileName;
} }
} }
try { try {
if (BooksWithoutBordersConfig.getUseYml()) { if (config.getUseYml()) {
BookToFromTextHelper.bookToYml(savePath, fileName, book); BookToFromTextHelper.bookToYml(savePath, fileName, book);
} else { } else {
BookToFromTextHelper.bookToTXT(savePath, fileName, book); BookToFromTextHelper.bookToTXT(savePath, fileName, book);
@@ -157,7 +155,7 @@ public class CommandSave implements TabExecutor {
BooksWithoutBorders.updateBooks(player, saveToPublicFolder); BooksWithoutBorders.updateBooks(player, saveToPublicFolder);
BooksWithoutBorders.sendSuccessMessage(player, "Book Saved as \"" + fileName + ChatColor.RESET + "\""); BooksWithoutBorders.sendSuccessMessage(player, "Book Saved as \"" + fileName + ChatColor.RESET + "\"");
} catch (IOException exception) { } catch (IOException exception) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to save book"); BooksWithoutBorders.log(Level.SEVERE, "Unable to save book");
} }
} }

View File

@@ -2,7 +2,8 @@ package net.knarcraft.bookswithoutborders.command;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import net.knarcraft.bookswithoutborders.utility.EconomyHelper; import net.knarcraft.bookswithoutborders.config.StaticMessage;
import net.knarcraft.bookswithoutborders.manager.EconomyManager;
import net.knarcraft.bookswithoutborders.utility.InventoryHelper; import net.knarcraft.bookswithoutborders.utility.InventoryHelper;
import net.knarcraft.bookswithoutborders.utility.TabCompletionTypeHelper; import net.knarcraft.bookswithoutborders.utility.TabCompletionTypeHelper;
import net.knarcraft.knarlib.util.TabCompletionHelper; import net.knarcraft.knarlib.util.TabCompletionHelper;
@@ -70,10 +71,11 @@ public class CommandSetBookPrice implements TabExecutor {
* @param sender <p>The sender of the command</p> * @param sender <p>The sender of the command</p>
*/ */
private void clearItemPrice(@NotNull CommandSender sender) { private void clearItemPrice(@NotNull CommandSender sender) {
BooksWithoutBordersConfig.setBookPriceType(null); BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
BooksWithoutBordersConfig.setBookPriceQuantity(0); config.setBookPriceType(null);
config.setBookPriceQuantity(0);
booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Item_type", "Item type name"); booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Item_type", "Item type name");
booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Required_quantity", BooksWithoutBordersConfig.getBookPriceQuantity()); booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Required_quantity", config.getBookPriceQuantity());
booksWithoutBorders.saveConfig(); booksWithoutBorders.saveConfig();
BooksWithoutBorders.sendSuccessMessage(sender, "Price to create books removed!"); BooksWithoutBorders.sendSuccessMessage(sender, "Price to create books removed!");
@@ -98,10 +100,11 @@ public class CommandSetBookPrice implements TabExecutor {
return false; return false;
} }
BooksWithoutBordersConfig.setBookPriceType(heldItem.getType()); BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
BooksWithoutBordersConfig.setBookPriceQuantity(price); config.setBookPriceType(heldItem.getType());
String newPriceType = BooksWithoutBordersConfig.getBookPriceType().toString(); config.setBookPriceQuantity(price);
double newPriceQuantity = BooksWithoutBordersConfig.getBookPriceQuantity(); String newPriceType = config.getBookPriceType().toString();
double newPriceQuantity = config.getBookPriceQuantity();
booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Item_type", newPriceType); booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Item_type", newPriceType);
booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Required_quantity", newPriceQuantity); booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Required_quantity", newPriceQuantity);
booksWithoutBorders.saveConfig(); booksWithoutBorders.saveConfig();
@@ -119,19 +122,21 @@ public class CommandSetBookPrice implements TabExecutor {
* @return <p>True if the price was changed successfully</p> * @return <p>True if the price was changed successfully</p>
*/ */
private boolean setEconomyPrice(@NotNull CommandSender sender, double price) { private boolean setEconomyPrice(@NotNull CommandSender sender, double price) {
if (EconomyHelper.setupEconomy()) { EconomyManager economyManager = BooksWithoutBorders.getConfiguration().getEconomyManager();
BooksWithoutBordersConfig.setBookPriceQuantity(price); if (economyManager.getEconomy() != null) {
BooksWithoutBordersConfig.setBookPriceType(Material.AIR); BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
double newPriceQuantity = BooksWithoutBordersConfig.getBookPriceQuantity(); config.setBookPriceQuantity(price);
config.setBookPriceType(Material.AIR);
double newPriceQuantity = config.getBookPriceQuantity();
booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Item_type", "Economy"); booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Item_type", "Economy");
booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Required_quantity", newPriceQuantity); booksWithoutBorders.getConfig().set("Options.Price_to_create_book.Required_quantity", newPriceQuantity);
booksWithoutBorders.saveConfig(); booksWithoutBorders.saveConfig();
BooksWithoutBorders.sendSuccessMessage(sender, "Book creation price set to " + BooksWithoutBorders.sendSuccessMessage(sender, "Book creation price set to " +
EconomyHelper.getEconomy().format(newPriceQuantity) + "!"); economyManager.getEconomy().format(newPriceQuantity) + "!");
return true; return true;
} else { } else {
BooksWithoutBorders.sendErrorMessage(sender, "BooksWithoutBorders failed to hook into Vault! Book price not set!"); BooksWithoutBorders.sendErrorMessage(sender, StaticMessage.EXCEPTION_VAULT_NOT_AVAILABLE.toString());
return false; return false;
} }
} }

View File

@@ -1,7 +1,6 @@
package net.knarcraft.bookswithoutborders.command; package net.knarcraft.bookswithoutborders.command;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import net.knarcraft.bookswithoutborders.container.Bookshelf; import net.knarcraft.bookswithoutborders.container.Bookshelf;
import net.knarcraft.bookswithoutborders.handler.BookshelfHandler; import net.knarcraft.bookswithoutborders.handler.BookshelfHandler;
import net.knarcraft.knarlib.util.TabCompletionHelper; import net.knarcraft.knarlib.util.TabCompletionHelper;
@@ -77,7 +76,7 @@ public class CommandSetBookshelfData implements TabExecutor {
BooksWithoutBorders.sendErrorMessage(commandSender, "You must name the bookshelf before " + BooksWithoutBorders.sendErrorMessage(commandSender, "You must name the bookshelf before " +
"assigning lore!"); "assigning lore!");
} else { } else {
List<String> loreParts = Arrays.asList(builder.toString().split(BooksWithoutBordersConfig.getLoreSeparator())); List<String> loreParts = Arrays.asList(builder.toString().split(BooksWithoutBorders.getConfiguration().getLoreSeparator()));
bookshelf.setLore(loreParts); bookshelf.setLore(loreParts);
shelfHandler.save(); shelfHandler.save();
BooksWithoutBorders.sendSuccessMessage(commandSender, "Lore successfully saved"); BooksWithoutBorders.sendSuccessMessage(commandSender, "Lore successfully saved");

View File

@@ -1,7 +1,6 @@
package net.knarcraft.bookswithoutborders.command; package net.knarcraft.bookswithoutborders.command;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import net.knarcraft.bookswithoutborders.utility.InventoryHelper; import net.knarcraft.bookswithoutborders.utility.InventoryHelper;
import net.knarcraft.knarlib.property.ColorConversion; import net.knarcraft.knarlib.property.ColorConversion;
import net.knarcraft.knarlib.util.ColorHelper; import net.knarcraft.knarlib.util.ColorHelper;
@@ -47,7 +46,7 @@ public class CommandSetLore implements TabExecutor {
//Format lore //Format lore
rawLore = ColorHelper.translateColorCodes(rawLore, ColorConversion.RGB); rawLore = ColorHelper.translateColorCodes(rawLore, ColorConversion.RGB);
List<String> newLore = Arrays.asList(rawLore.split(BooksWithoutBordersConfig.getLoreSeparator())); List<String> newLore = Arrays.asList(rawLore.split(BooksWithoutBorders.getConfiguration().getLoreSeparator()));
//Update lore //Update lore
ItemMeta meta = heldItem.getItemMeta(); ItemMeta meta = heldItem.getItemMeta();

View File

@@ -1,7 +1,6 @@
package net.knarcraft.bookswithoutborders.command; package net.knarcraft.bookswithoutborders.command;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import net.knarcraft.bookswithoutborders.state.ItemSlot; import net.knarcraft.bookswithoutborders.state.ItemSlot;
import net.knarcraft.bookswithoutborders.utility.BookHelper; import net.knarcraft.bookswithoutborders.utility.BookHelper;
import net.knarcraft.bookswithoutborders.utility.InventoryHelper; import net.knarcraft.bookswithoutborders.utility.InventoryHelper;
@@ -60,7 +59,8 @@ public class CommandUnSign implements TabExecutor {
ItemStack heldBook = InventoryHelper.getHeldBook(player, mainHand); ItemStack heldBook = InventoryHelper.getHeldBook(player, mainHand);
//Only allow the owner to un-sign the book //Only allow the owner to un-sign the book
if (BooksWithoutBordersConfig.getAuthorOnlyUnsign() && !player.hasPermission("bookswithoutborders.bypassAuthorOnlyUnsign")) { if (BooksWithoutBorders.getConfiguration().getAuthorOnlyUnsign() &&
!player.hasPermission("bookswithoutborders.bypassAuthorOnlyUnsign")) {
if (BookHelper.isNotAuthor(player, Objects.requireNonNull(oldMetadata))) { if (BookHelper.isNotAuthor(player, Objects.requireNonNull(oldMetadata))) {
return; return;
} }
@@ -68,7 +68,7 @@ public class CommandUnSign implements TabExecutor {
WritableBookMeta newMetadata = (BookMeta) BooksWithoutBorders.getItemFactory().getItemMeta(Material.WRITABLE_BOOK); WritableBookMeta newMetadata = (BookMeta) BooksWithoutBorders.getItemFactory().getItemMeta(Material.WRITABLE_BOOK);
if (newMetadata == null) { if (newMetadata == null) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to create writable book metadata"); BooksWithoutBorders.log(Level.SEVERE, "Unable to create writable book metadata");
return; return;
} }

View File

@@ -1,7 +1,7 @@
package net.knarcraft.bookswithoutborders.config; package net.knarcraft.bookswithoutborders.config;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.utility.EconomyHelper; import net.knarcraft.bookswithoutborders.manager.EconomyManager;
import net.knarcraft.knarlib.formatting.Translator; import net.knarcraft.knarlib.formatting.Translator;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
@@ -21,53 +21,64 @@ import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.clea
*/ */
public class BooksWithoutBordersConfig { public class BooksWithoutBordersConfig {
private static final ChatColor errorColor = ChatColor.RED; private final ChatColor errorColor = ChatColor.RED;
private static final ChatColor successColor = ChatColor.GREEN; private final ChatColor successColor = ChatColor.GREEN;
private static final ChatColor commandColor = ChatColor.YELLOW; private final ChatColor commandColor = ChatColor.YELLOW;
private static final String SLASH = FileSystems.getDefault().getSeparator(); private final String SLASH = FileSystems.getDefault().getSeparator();
private static boolean isInitialized; private boolean isInitialized;
public static String bookFolder; public String bookFolder;
private static int bookDuplicateLimit; private int bookDuplicateLimit;
private static String titleAuthorSeparator; private String titleAuthorSeparator;
private static String loreSeparator; private String loreSeparator;
private static List<String> firstBooks = new ArrayList<>(); private List<String> firstBooks = new ArrayList<>();
private static String welcomeMessage; private String welcomeMessage;
private static Material bookPriceType = null; private Material bookPriceType = null;
private static double bookPriceQuantity; private double bookPriceQuantity;
private static boolean authorOnlyCopy; private boolean authorOnlyCopy;
private static boolean authorOnlyUnsign; private boolean authorOnlyUnsign;
private static boolean authorOnlySave; private boolean authorOnlySave;
private static boolean useYml; private boolean useYml;
private static boolean adminDecrypt; private boolean adminDecrypt;
private static boolean formatBooks; private boolean formatBooks;
private static boolean changeGenerationOnCopy; private boolean changeGenerationOnCopy;
private static boolean enableBookshelfPeeking; private boolean enableBookshelfPeeking;
private static Translator translator; private final Translator translator;
private EconomyManager economyManager;
/** /**
* Initializes the books without borders settings class * Initializes the books without borders settings class
* *
* @param booksWithoutBorders <p>The books without borders object used for getting required data</p> * @param booksWithoutBorders <p>The books without borders object used for getting required data</p>
*/ */
public static void initialize(@NotNull BooksWithoutBorders booksWithoutBorders, @NotNull Translator translator) { public BooksWithoutBordersConfig(@NotNull BooksWithoutBorders booksWithoutBorders, @NotNull Translator translator) {
if (isInitialized) { if (isInitialized) {
throw new IllegalArgumentException("Settings class initialized twice. This should not happen!"); throw new IllegalArgumentException("Settings class initialized twice. This should not happen!");
} }
BooksWithoutBordersConfig.translator = translator; this.translator = translator;
isInitialized = true; isInitialized = true;
bookFolder = booksWithoutBorders.getDataFolder().getAbsolutePath() + getSlash() + "Books" + getSlash(); bookFolder = booksWithoutBorders.getDataFolder().getAbsolutePath() + getSlash() + "Books" + getSlash();
loadConfig(); loadConfig();
} }
/**
* Gets the economy manager
*
* @return <p>The economy manager</p>
*/
@NotNull
public EconomyManager getEconomyManager() {
return this.economyManager;
}
/** /**
* Gets the folder used for storing books * Gets the folder used for storing books
* *
* @return <p>The folder used for storing books</p> * @return <p>The folder used for storing books</p>
*/ */
public static String getBookFolder() { public String getBookFolder() {
return bookFolder; return this.bookFolder;
} }
/** /**
@@ -75,8 +86,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The color to use for error messages</p> * @return <p>The color to use for error messages</p>
*/ */
public static ChatColor getErrorColor() { public ChatColor getErrorColor() {
return errorColor; return this.errorColor;
} }
/** /**
@@ -84,8 +95,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The color to use for success messages</p> * @return <p>The color to use for success messages</p>
*/ */
public static ChatColor getSuccessColor() { public ChatColor getSuccessColor() {
return successColor; return this.successColor;
} }
/** /**
@@ -93,8 +104,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The color used to color commands</p> * @return <p>The color used to color commands</p>
*/ */
public static ChatColor getCommandColor() { public ChatColor getCommandColor() {
return commandColor; return this.commandColor;
} }
/** /**
@@ -102,8 +113,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The slash to use for file separators</p> * @return <p>The slash to use for file separators</p>
*/ */
public static String getSlash() { public String getSlash() {
return SLASH; return this.SLASH;
} }
/** /**
@@ -111,8 +122,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>Whether only the book author can copy it</p> * @return <p>Whether only the book author can copy it</p>
*/ */
public static boolean getAuthorOnlyCopy() { public boolean getAuthorOnlyCopy() {
return authorOnlyCopy; return this.authorOnlyCopy;
} }
/** /**
@@ -120,8 +131,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>Whether only the book author can unsign it</p> * @return <p>Whether only the book author can unsign it</p>
*/ */
public static boolean getAuthorOnlyUnsign() { public boolean getAuthorOnlyUnsign() {
return authorOnlyUnsign; return this.authorOnlyUnsign;
} }
/** /**
@@ -129,8 +140,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>Whether a player can only save their own books</p> * @return <p>Whether a player can only save their own books</p>
*/ */
public static boolean getAuthorOnlySave() { public boolean getAuthorOnlySave() {
return authorOnlySave; return this.authorOnlySave;
} }
/** /**
@@ -138,8 +149,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>True if players can peek at the contained books</p> * @return <p>True if players can peek at the contained books</p>
*/ */
public static boolean getEnableBookshelfPeeking() { public boolean getEnableBookshelfPeeking() {
return enableBookshelfPeeking; return this.enableBookshelfPeeking;
} }
/** /**
@@ -147,8 +158,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>Whether to use YML for saving books</p> * @return <p>Whether to use YML for saving books</p>
*/ */
public static boolean getUseYml() { public boolean getUseYml() {
return useYml; return this.useYml;
} }
/** /**
@@ -156,8 +167,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>Whether admins can bypass the encryption password</p> * @return <p>Whether admins can bypass the encryption password</p>
*/ */
public static boolean getAdminDecrypt() { public boolean getAdminDecrypt() {
return adminDecrypt; return this.adminDecrypt;
} }
/** /**
@@ -165,8 +176,8 @@ public class BooksWithoutBordersConfig {
* *
* @param newQuantity <p>The new quantity necessary for payment</p> * @param newQuantity <p>The new quantity necessary for payment</p>
*/ */
public static void setBookPriceQuantity(double newQuantity) { public void setBookPriceQuantity(double newQuantity) {
bookPriceQuantity = newQuantity; this.bookPriceQuantity = newQuantity;
} }
/** /**
@@ -174,8 +185,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The quantity necessary for payment</p> * @return <p>The quantity necessary for payment</p>
*/ */
public static double getBookPriceQuantity() { public double getBookPriceQuantity() {
return bookPriceQuantity; return this.bookPriceQuantity;
} }
/** /**
@@ -186,8 +197,8 @@ public class BooksWithoutBordersConfig {
* *
* @param newType <p>The new item type to use for book pricing</p> * @param newType <p>The new item type to use for book pricing</p>
*/ */
public static void setBookPriceType(Material newType) { public void setBookPriceType(Material newType) {
bookPriceType = newType; this.bookPriceType = newType;
} }
/** /**
@@ -198,8 +209,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The item type used for book pricing</p> * @return <p>The item type used for book pricing</p>
*/ */
public static Material getBookPriceType() { public Material getBookPriceType() {
return bookPriceType; return this.bookPriceType;
} }
/** /**
@@ -207,8 +218,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The welcome message to show new players</p> * @return <p>The welcome message to show new players</p>
*/ */
public static String getWelcomeMessage() { public String getWelcomeMessage() {
return welcomeMessage; return this.welcomeMessage;
} }
/** /**
@@ -216,8 +227,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The book duplicate limit</p> * @return <p>The book duplicate limit</p>
*/ */
public static int getBookDuplicateLimit() { public int getBookDuplicateLimit() {
return bookDuplicateLimit; return this.bookDuplicateLimit;
} }
/** /**
@@ -225,8 +236,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>True if books should change their generation</p> * @return <p>True if books should change their generation</p>
*/ */
public static boolean changeGenerationOnCopy() { public boolean changeGenerationOnCopy() {
return changeGenerationOnCopy; return this.changeGenerationOnCopy;
} }
/** /**
@@ -234,8 +245,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The separator between title and author</p> * @return <p>The separator between title and author</p>
*/ */
public static String getTitleAuthorSeparator() { public String getTitleAuthorSeparator() {
return titleAuthorSeparator; return this.titleAuthorSeparator;
} }
/** /**
@@ -243,8 +254,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The separator used to denote lore newline</p> * @return <p>The separator used to denote lore newline</p>
*/ */
public static String getLoreSeparator() { public String getLoreSeparator() {
return loreSeparator; return this.loreSeparator;
} }
/** /**
@@ -252,8 +263,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>Whether all books should be formatted</p> * @return <p>Whether all books should be formatted</p>
*/ */
public static boolean formatBooks() { public boolean formatBooks() {
return formatBooks; return this.formatBooks;
} }
/** /**
@@ -261,8 +272,8 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>The books to give new players</p> * @return <p>The books to give new players</p>
*/ */
public static List<String> getFirstBooks() { public List<String> getFirstBooks() {
return new ArrayList<>(firstBooks); return new ArrayList<>(this.firstBooks);
} }
/** /**
@@ -270,29 +281,39 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>True if players need to pay for printing books</p> * @return <p>True if players need to pay for printing books</p>
*/ */
public static boolean booksHavePrice() { public boolean booksHavePrice() {
return (bookPriceType != null && bookPriceQuantity > 0); return (this.bookPriceType != null && this.bookPriceQuantity > 0);
}
/**
* Gets the path used to store encrypted books
*
* @return <p>The encrypted book path</p>
*/
@NotNull
public String getEncryptedBookPath() {
return getBookFolder() + "Encrypted" + getSlash();
} }
/** /**
* Saves the config * Saves the config
*/ */
public static void saveConfigValues() { public void saveConfigValues() {
Logger logger = BooksWithoutBorders.getInstance().getLogger(); Logger logger = BooksWithoutBorders.getInstance().getLogger();
Configuration config = BooksWithoutBorders.getInstance().getConfig(); Configuration config = BooksWithoutBorders.getInstance().getConfig();
config.set(ConfigOption.USE_YAML.getConfigNode(), useYml); config.set(ConfigOption.USE_YAML.getConfigNode(), this.useYml);
config.set(ConfigOption.MAX_DUPLICATES.getConfigNode(), bookDuplicateLimit); config.set(ConfigOption.MAX_DUPLICATES.getConfigNode(), this.bookDuplicateLimit);
config.set(ConfigOption.TITLE_AUTHOR_SEPARATOR.getConfigNode(), titleAuthorSeparator); config.set(ConfigOption.TITLE_AUTHOR_SEPARATOR.getConfigNode(), this.titleAuthorSeparator);
config.set(ConfigOption.LORE_LINE_SEPARATOR.getConfigNode(), loreSeparator); config.set(ConfigOption.LORE_LINE_SEPARATOR.getConfigNode(), this.loreSeparator);
config.set(ConfigOption.BOOKS_FOR_NEW_PLAYERS.getConfigNode(), firstBooks); config.set(ConfigOption.BOOKS_FOR_NEW_PLAYERS.getConfigNode(), this.firstBooks);
config.set(ConfigOption.MESSAGE_FOR_NEW_PLAYERS.getConfigNode(), welcomeMessage); config.set(ConfigOption.MESSAGE_FOR_NEW_PLAYERS.getConfigNode(), this.welcomeMessage);
config.set(ConfigOption.FORMAT_AFTER_SIGNING.getConfigNode(), formatBooks); config.set(ConfigOption.FORMAT_AFTER_SIGNING.getConfigNode(), this.formatBooks);
config.set(ConfigOption.ENABLE_BOOKSHELF_PEEKING.getConfigNode(), enableBookshelfPeeking); config.set(ConfigOption.ENABLE_BOOKSHELF_PEEKING.getConfigNode(), this.enableBookshelfPeeking);
String itemTypeNode = ConfigOption.PRICE_ITEM_TYPE.getConfigNode(); String itemTypeNode = ConfigOption.PRICE_ITEM_TYPE.getConfigNode();
if (bookPriceType != null) { if (this.bookPriceType != null) {
if (bookPriceType != Material.AIR) { if (this.bookPriceType != Material.AIR) {
config.set(itemTypeNode, bookPriceType.toString()); config.set(itemTypeNode, this.bookPriceType.toString());
} else { } else {
config.set(itemTypeNode, "Economy"); config.set(itemTypeNode, "Economy");
} }
@@ -300,12 +321,12 @@ public class BooksWithoutBordersConfig {
config.set(itemTypeNode, "Item type name"); config.set(itemTypeNode, "Item type name");
} }
config.set(ConfigOption.PRICE_QUANTITY.getConfigNode(), bookPriceQuantity); config.set(ConfigOption.PRICE_QUANTITY.getConfigNode(), this.bookPriceQuantity);
config.set(ConfigOption.ADMIN_AUTO_DECRYPT.getConfigNode(), adminDecrypt); config.set(ConfigOption.ADMIN_AUTO_DECRYPT.getConfigNode(), this.adminDecrypt);
config.set(ConfigOption.AUTHOR_ONLY_COPY.getConfigNode(), authorOnlyCopy); config.set(ConfigOption.AUTHOR_ONLY_COPY.getConfigNode(), this.authorOnlyCopy);
config.set(ConfigOption.AUTHOR_ONLY_UNSIGN.getConfigNode(), authorOnlyUnsign); config.set(ConfigOption.AUTHOR_ONLY_UNSIGN.getConfigNode(), this.authorOnlyUnsign);
config.set(ConfigOption.AUTHOR_ONLY_SAVE.getConfigNode(), authorOnlySave); config.set(ConfigOption.AUTHOR_ONLY_SAVE.getConfigNode(), this.authorOnlySave);
config.set(ConfigOption.CHANGE_GENERATION_ON_COPY.getConfigNode(), changeGenerationOnCopy); config.set(ConfigOption.CHANGE_GENERATION_ON_COPY.getConfigNode(), this.changeGenerationOnCopy);
//Handles old book and quill settings //Handles old book and quill settings
if (config.contains("Options.Require_book_and_quill_to_create_book")) { if (config.contains("Options.Require_book_and_quill_to_create_book")) {
@@ -313,10 +334,10 @@ public class BooksWithoutBordersConfig {
"\"Require_book_and_quill_to_create_book\"\nUpdating to \"Price_to_create_book\" settings"); "\"Require_book_and_quill_to_create_book\"\nUpdating to \"Price_to_create_book\" settings");
if (config.getBoolean("Options.Require_book_and_quill_to_create_book")) { if (config.getBoolean("Options.Require_book_and_quill_to_create_book")) {
bookPriceType = Material.WRITABLE_BOOK; this.bookPriceType = Material.WRITABLE_BOOK;
bookPriceQuantity = 1; this.bookPriceQuantity = 1;
config.set("Options.Price_to_create_book.Item_type", bookPriceType.toString()); config.set("Options.Price_to_create_book.Item_type", this.bookPriceType.toString());
config.set("Options.Price_to_create_book.Required_quantity", bookPriceQuantity); config.set("Options.Price_to_create_book.Required_quantity", this.bookPriceQuantity);
} }
config.set("Options.Require_book_and_quill_to_create_book", null); config.set("Options.Require_book_and_quill_to_create_book", null);
} }
@@ -328,53 +349,54 @@ public class BooksWithoutBordersConfig {
* *
* @return <p>True if the config was loaded successfully</p> * @return <p>True if the config was loaded successfully</p>
*/ */
public static boolean loadConfig() { public boolean loadConfig() {
Logger logger = BooksWithoutBorders.getInstance().getLogger(); Logger logger = BooksWithoutBorders.getInstance().getLogger();
BooksWithoutBorders.getInstance().reloadConfig(); BooksWithoutBorders.getInstance().reloadConfig();
Configuration config = BooksWithoutBorders.getInstance().getConfig(); Configuration config = BooksWithoutBorders.getInstance().getConfig();
try { try {
useYml = getBoolean(config, ConfigOption.USE_YAML); this.useYml = getBoolean(config, ConfigOption.USE_YAML);
bookDuplicateLimit = config.getInt(ConfigOption.MAX_DUPLICATES.getConfigNode(), this.bookDuplicateLimit = config.getInt(ConfigOption.MAX_DUPLICATES.getConfigNode(),
(Integer) ConfigOption.MAX_DUPLICATES.getDefaultValue()); (Integer) ConfigOption.MAX_DUPLICATES.getDefaultValue());
titleAuthorSeparator = getString(config, ConfigOption.TITLE_AUTHOR_SEPARATOR); this.titleAuthorSeparator = getString(config, ConfigOption.TITLE_AUTHOR_SEPARATOR);
loreSeparator = getString(config, ConfigOption.LORE_LINE_SEPARATOR); this.loreSeparator = getString(config, ConfigOption.LORE_LINE_SEPARATOR);
adminDecrypt = getBoolean(config, ConfigOption.ADMIN_AUTO_DECRYPT); this.adminDecrypt = getBoolean(config, ConfigOption.ADMIN_AUTO_DECRYPT);
authorOnlyCopy = getBoolean(config, ConfigOption.AUTHOR_ONLY_COPY); this.authorOnlyCopy = getBoolean(config, ConfigOption.AUTHOR_ONLY_COPY);
authorOnlyUnsign = getBoolean(config, ConfigOption.AUTHOR_ONLY_UNSIGN); this.authorOnlyUnsign = getBoolean(config, ConfigOption.AUTHOR_ONLY_UNSIGN);
authorOnlySave = getBoolean(config, ConfigOption.AUTHOR_ONLY_SAVE); this.authorOnlySave = getBoolean(config, ConfigOption.AUTHOR_ONLY_SAVE);
firstBooks = config.getStringList(ConfigOption.BOOKS_FOR_NEW_PLAYERS.getConfigNode()); this.firstBooks = config.getStringList(ConfigOption.BOOKS_FOR_NEW_PLAYERS.getConfigNode());
welcomeMessage = getString(config, ConfigOption.MESSAGE_FOR_NEW_PLAYERS); this.welcomeMessage = getString(config, ConfigOption.MESSAGE_FOR_NEW_PLAYERS);
formatBooks = getBoolean(config, ConfigOption.FORMAT_AFTER_SIGNING); this.formatBooks = getBoolean(config, ConfigOption.FORMAT_AFTER_SIGNING);
changeGenerationOnCopy = getBoolean(config, ConfigOption.CHANGE_GENERATION_ON_COPY); this.changeGenerationOnCopy = getBoolean(config, ConfigOption.CHANGE_GENERATION_ON_COPY);
enableBookshelfPeeking = getBoolean(config, ConfigOption.ENABLE_BOOKSHELF_PEEKING); this.enableBookshelfPeeking = getBoolean(config, ConfigOption.ENABLE_BOOKSHELF_PEEKING);
String language = config.getString("language", "en"); String language = config.getString("language", "en");
translator.loadLanguages(BooksWithoutBorders.getInstance().getDataFolder(), "en", language); this.translator.loadLanguages(BooksWithoutBorders.getInstance().getDataFolder(), "en", language);
//Convert string into material //Convert string into material
this.economyManager = new EconomyManager();
String paymentMaterial = getString(config, ConfigOption.PRICE_ITEM_TYPE); String paymentMaterial = getString(config, ConfigOption.PRICE_ITEM_TYPE);
if (paymentMaterial.equalsIgnoreCase("Economy")) { if (paymentMaterial.equalsIgnoreCase("Economy")) {
if (EconomyHelper.setupEconomy()) { if (this.economyManager.getEconomy() == null) {
bookPriceType = Material.AIR; logger.log(Level.SEVERE, StaticMessage.EXCEPTION_VAULT_NOT_AVAILABLE.toString());
this.bookPriceType = null;
} else { } else {
logger.log(Level.SEVERE, "BooksWithoutBorders failed to hook into Vault! Book price not set!"); this.bookPriceType = Material.AIR;
bookPriceType = null;
} }
} else if (!paymentMaterial.trim().isEmpty()) { } else if (!paymentMaterial.trim().isEmpty()) {
Material material = Material.matchMaterial(paymentMaterial); Material material = Material.matchMaterial(paymentMaterial);
if (material != null) { if (material != null) {
bookPriceType = material; this.bookPriceType = material;
} }
} }
bookPriceQuantity = config.getDouble(ConfigOption.PRICE_QUANTITY.getConfigNode(), this.bookPriceQuantity = config.getDouble(ConfigOption.PRICE_QUANTITY.getConfigNode(),
(Double) ConfigOption.PRICE_QUANTITY.getDefaultValue()); (Double) ConfigOption.PRICE_QUANTITY.getDefaultValue());
//Make sure titleAuthorSeparator is a valid value //Make sure titleAuthorSeparator is a valid value
titleAuthorSeparator = cleanString(titleAuthorSeparator); this.titleAuthorSeparator = cleanString(this.titleAuthorSeparator);
if (titleAuthorSeparator.length() != 1) { if (this.titleAuthorSeparator.length() != 1) {
logger.log(Level.SEVERE, "Title-Author_Separator is set to an invalid value!\n" + logger.log(Level.SEVERE, "Title-Author_Separator is set to an invalid value!\n" +
"Reverting to default value of \",\""); "Reverting to default value of \",\"");
titleAuthorSeparator = ","; this.titleAuthorSeparator = ",";
config.set("Options.Title-Author_Separator", titleAuthorSeparator); config.set("Options.Title-Author_Separator", this.titleAuthorSeparator);
} }
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.SEVERE, "Warning! Config.yml failed to load!\n" + logger.log(Level.SEVERE, "Warning! Config.yml failed to load!\n" +

View File

@@ -9,7 +9,9 @@ public enum StaticMessage {
BOOK_SAVING_FAILED("Saving failed! Aborting..."), BOOK_SAVING_FAILED("Saving failed! Aborting..."),
BOOK_FOLDER_CREATE_FAILED("Unable to create necessary folders"), BOOK_FOLDER_CREATE_FAILED("Unable to create necessary folders"),
COMMAND_NOT_REGISTERED("Command {command} has not been registered!"); COMMAND_NOT_REGISTERED("Command {command} has not been registered!"),
EXCEPTION_VAULT_NOT_AVAILABLE("BooksWithoutBorders failed to hook into Vault! Book price not set!"),
;
private final @NotNull String messageString; private final @NotNull String messageString;

View File

@@ -73,6 +73,11 @@ public enum Translatable implements TranslatableMessage {
*/ */
ERROR_INVENTORY_FULL, ERROR_INVENTORY_FULL,
/**
* The error displayed when trying to do a Vault transaction while Vault is unavailable
*/
ERROR_VAULT_COST_BUT_UNAVAILABLE,
/** /**
* The header displayed before printing all commands * The header displayed before printing all commands
*/ */
@@ -103,6 +108,11 @@ public enum Translatable implements TranslatableMessage {
*/ */
NEUTRAL_COMMANDS_COMMAND_PERMISSION, NEUTRAL_COMMANDS_COMMAND_PERMISSION,
/**
* The translation of unknown author for a book
*/
NEUTRAL_UNKNOWN_AUTHOR,
/** /**
* The translation of the copy action * The translation of the copy action
*/ */
@@ -112,6 +122,11 @@ public enum Translatable implements TranslatableMessage {
* The translation of the clear action * The translation of the clear action
*/ */
ACTION_CLEAR, ACTION_CLEAR,
/**
* The translation of the decrypt action
*/
ACTION_DECRYPT,
; ;
@Override @Override

View File

@@ -73,7 +73,7 @@ public class AES {
try { try {
aes.init(mode, secretKeySpec, ivParameterSpec); aes.init(mode, secretKeySpec, ivParameterSpec);
} catch (InvalidKeyException | InvalidAlgorithmParameterException exception) { } catch (InvalidKeyException | InvalidAlgorithmParameterException exception) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES input given!"); BooksWithoutBorders.log(Level.SEVERE, "Invalid AES input given!");
return null; return null;
} }
//Perform encryption/decryption and output result //Perform encryption/decryption and output result
@@ -81,7 +81,7 @@ public class AES {
byte[] output = aes.doFinal(getInputBytes(input, encrypt)); byte[] output = aes.doFinal(getInputBytes(input, encrypt));
return createResult(output, encrypt); return createResult(output, encrypt);
} catch (IllegalBlockSizeException | BadPaddingException exception) { } catch (IllegalBlockSizeException | BadPaddingException exception) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES block size or padding"); BooksWithoutBorders.log(Level.SEVERE, "Invalid AES block size or padding");
return null; return null;
} }
} }
@@ -140,7 +140,7 @@ public class AES {
try { try {
aes = Cipher.getInstance("AES/CBC/PKCS5Padding"); aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException | NoSuchPaddingException exception) { } catch (NoSuchAlgorithmException | NoSuchPaddingException exception) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES algorithm or padding"); BooksWithoutBorders.log(Level.SEVERE, "Invalid AES algorithm or padding");
return null; return null;
} }
return aes; return aes;
@@ -159,14 +159,14 @@ public class AES {
try { try {
keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
} catch (NoSuchAlgorithmException exception) { } catch (NoSuchAlgorithmException exception) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES algorithm"); BooksWithoutBorders.log(Level.SEVERE, "Invalid AES algorithm");
return null; return null;
} }
SecretKey tmp; SecretKey tmp;
try { try {
tmp = keyFactory.generateSecret(spec); tmp = keyFactory.generateSecret(spec);
} catch (InvalidKeySpecException exception) { } catch (InvalidKeySpecException exception) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES key specification"); BooksWithoutBorders.log(Level.SEVERE, "Invalid AES key specification");
return null; return null;
} }
return new SecretKeySpec(tmp.getEncoded(), "AES"); return new SecretKeySpec(tmp.getEncoded(), "AES");

View File

@@ -1,7 +1,7 @@
package net.knarcraft.bookswithoutborders.gui; package net.knarcraft.bookswithoutborders.gui;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.utility.BookFileHelper;
import net.knarcraft.bookswithoutborders.utility.BookFormatter; import net.knarcraft.bookswithoutborders.utility.BookFormatter;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent;
@@ -28,8 +28,8 @@ public class AuthorBookIndex extends BookIndex {
public static void printBooks(@NotNull CommandSender sender, boolean listPublic, @NotNull String command, int page, public static void printBooks(@NotNull CommandSender sender, boolean listPublic, @NotNull String command, int page,
@NotNull String authorName) { @NotNull String authorName) {
List<String> availableBooks = BooksWithoutBorders.getAvailableBooks(sender, listPublic); List<String> availableBooks = BooksWithoutBorders.getAvailableBooks(sender, listPublic);
availableBooks.removeIf((bookPath) -> !BookFormatter.stripColor(bookPath.substring(0, bookPath.length() - 4).split( availableBooks.removeIf((bookPath) ->
BooksWithoutBordersConfig.getTitleAuthorSeparator())[1]).equalsIgnoreCase(authorName)); !BookFormatter.stripColor(BookFileHelper.getBookAuthorFromPath(bookPath)).equalsIgnoreCase(authorName));
int totalPages = (int) Math.ceil((double) availableBooks.size() / booksPerPage); int totalPages = (int) Math.ceil((double) availableBooks.size() / booksPerPage);
if (page > totalPages) { if (page > totalPages) {

View File

@@ -1,6 +1,6 @@
package net.knarcraft.bookswithoutborders.gui; package net.knarcraft.bookswithoutborders.gui;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.utility.BookFileHelper;
import net.knarcraft.bookswithoutborders.utility.InputCleaningHelper; import net.knarcraft.bookswithoutborders.utility.InputCleaningHelper;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent;
@@ -140,14 +140,10 @@ public abstract class BookIndex {
*/ */
@NotNull @NotNull
protected static String getNiceName(@NotNull String bookPath) { protected static String getNiceName(@NotNull String bookPath) {
String separator = BooksWithoutBordersConfig.getTitleAuthorSeparator(); String title = BookFileHelper.getBookTitleFromPath(bookPath);
bookPath = ChatColor.translateAlternateColorCodes('&', bookPath.substring(0, bookPath.length() - 4)); String author = BookFileHelper.getBookAuthorFromPath(bookPath);
if (bookPath.contains(separator)) { return ChatColor.translateAlternateColorCodes('&',
String[] parts = bookPath.split(separator); title.replace("_", " ") + ChatColor.RESET + " by " + author + ChatColor.RESET);
return parts[0].replace("_", " ") + ChatColor.RESET + " by " + parts[1] + ChatColor.RESET;
} else {
return bookPath + ChatColor.RESET + " by Unknown" + ChatColor.RESET;
}
} }
} }

View File

@@ -72,7 +72,7 @@ public class BookshelfHandler {
YamlConfiguration configuration = YamlConfiguration.loadConfiguration(bookshelfFile); YamlConfiguration configuration = YamlConfiguration.loadConfiguration(bookshelfFile);
ConfigurationSection bookshelfSection = configuration.getConfigurationSection("bookshelves"); ConfigurationSection bookshelfSection = configuration.getConfigurationSection("bookshelves");
if (bookshelfSection == null) { if (bookshelfSection == null) {
BooksWithoutBorders.getInstance().getLogger().log(Level.INFO, BooksWithoutBorders.log(Level.INFO,
"BooksWithoutBorders found no bookshelves to load"); "BooksWithoutBorders found no bookshelves to load");
return; return;
} }
@@ -118,7 +118,7 @@ public class BookshelfHandler {
} }
configuration.save(bookshelfFile); configuration.save(bookshelfFile);
} catch (IOException exception) { } catch (IOException exception) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to save bookshelves!"); BooksWithoutBorders.log(Level.SEVERE, "Unable to save bookshelves!");
} }
} }

View File

@@ -1,6 +1,6 @@
package net.knarcraft.bookswithoutborders.listener; package net.knarcraft.bookswithoutborders.listener;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.utility.BookFormatter; import net.knarcraft.bookswithoutborders.utility.BookFormatter;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
@@ -16,7 +16,7 @@ public class BookEventListener implements Listener {
@EventHandler @EventHandler
public void onBookSign(@NotNull PlayerEditBookEvent event) { public void onBookSign(@NotNull PlayerEditBookEvent event) {
if (event.isCancelled() || !event.isSigning() || !BooksWithoutBordersConfig.formatBooks()) { if (event.isCancelled() || !event.isSigning() || !BooksWithoutBorders.getConfiguration().formatBooks()) {
return; return;
} }
event.setNewBookMeta(BookFormatter.formatPages(event.getNewBookMeta())); event.setNewBookMeta(BookFormatter.formatPages(event.getNewBookMeta()));

View File

@@ -1,7 +1,7 @@
package net.knarcraft.bookswithoutborders.listener; package net.knarcraft.bookswithoutborders.listener;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.config.Translatable;
import net.knarcraft.bookswithoutborders.container.Bookshelf; import net.knarcraft.bookswithoutborders.container.Bookshelf;
import net.knarcraft.bookswithoutborders.handler.BookshelfHandler; import net.knarcraft.bookswithoutborders.handler.BookshelfHandler;
import net.knarcraft.bookswithoutborders.utility.IntegerToRomanConverter; import net.knarcraft.bookswithoutborders.utility.IntegerToRomanConverter;
@@ -63,7 +63,7 @@ public class BookshelfListener implements Listener {
} }
// Check if bookshelf peeking is enabled, and the player can peek // Check if bookshelf peeking is enabled, and the player can peek
if (!BooksWithoutBordersConfig.getEnableBookshelfPeeking() || if (!BooksWithoutBorders.getConfiguration().getEnableBookshelfPeeking() ||
!event.getPlayer().hasPermission("bookswithoutborders.peekbookshelf")) { !event.getPlayer().hasPermission("bookswithoutborders.peekbookshelf")) {
return; return;
} }
@@ -155,7 +155,7 @@ public class BookshelfListener implements Listener {
title = bookMeta.getTitle(); title = bookMeta.getTitle();
} }
if (!bookMeta.hasAuthor() || bookMeta.getAuthor() == null) { if (!bookMeta.hasAuthor() || bookMeta.getAuthor() == null) {
author = "Unknown"; author = BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(Translatable.NEUTRAL_UNKNOWN_AUTHOR);
} else { } else {
author = bookMeta.getAuthor(); author = bookMeta.getAuthor();
} }

View File

@@ -58,13 +58,14 @@ public class PlayerEventListener implements Listener {
@EventHandler @EventHandler
public void onPlayerJoin(@NotNull PlayerJoinEvent event) { public void onPlayerJoin(@NotNull PlayerJoinEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
//If a book directory exists with this player's name, move it to this player's UUID //If a book directory exists with this player's name, move it to this player's UUID
String bookFolder = BooksWithoutBordersConfig.getBookFolder(); String bookFolder = config.getBookFolder();
File file = new File(bookFolder + InputCleaningHelper.cleanString(player.getName())); File file = new File(bookFolder + InputCleaningHelper.cleanString(player.getName()));
if (file.exists()) { if (file.exists()) {
if (!file.renameTo(new File(bookFolder + player.getUniqueId()))) { if (!file.renameTo(new File(bookFolder + player.getUniqueId()))) {
BooksWithoutBorders.getInstance().getLogger().log(Level.WARNING, "Unable to migrate player book " + BooksWithoutBorders.log(Level.WARNING, "Unable to migrate player book " +
"directory for player " + player.getName()); "directory for player " + player.getName());
} }
} }
@@ -74,7 +75,7 @@ public class PlayerEventListener implements Listener {
boolean sendMessage = true; boolean sendMessage = true;
//Gives new players necessary books //Gives new players necessary books
for (String bookName : BooksWithoutBordersConfig.getFirstBooks()) { for (String bookName : config.getFirstBooks()) {
sendMessage = giveBookToNewPlayer(bookName, player, sendMessage); sendMessage = giveBookToNewPlayer(bookName, player, sendMessage);
} }
} }
@@ -114,7 +115,7 @@ public class PlayerEventListener implements Listener {
} }
//Send the player a welcome message if it exists //Send the player a welcome message if it exists
String welcomeMessage = BooksWithoutBordersConfig.getWelcomeMessage(); String welcomeMessage = BooksWithoutBorders.getConfiguration().getWelcomeMessage();
if (!welcomeMessage.trim().isEmpty() && newBook != null && sendMessage) { if (!welcomeMessage.trim().isEmpty() && newBook != null && sendMessage) {
sendMessage = false; sendMessage = false;
booksWithoutBorders.getServer().getScheduler().scheduleSyncDelayedTask(booksWithoutBorders, booksWithoutBorders.getServer().getScheduler().scheduleSyncDelayedTask(booksWithoutBorders,
@@ -164,7 +165,7 @@ public class PlayerEventListener implements Listener {
//Unknown author is ignored //Unknown author is ignored
fileName = oldBook.getTitle(); fileName = oldBook.getTitle();
} else { } else {
fileName = oldBook.getTitle() + BooksWithoutBordersConfig.getTitleAuthorSeparator() + oldBook.getAuthor(); fileName = oldBook.getTitle() + BooksWithoutBorders.getConfiguration().getTitleAuthorSeparator() + oldBook.getAuthor();
} }
String playerFolderPath = BookHelper.getBookDirectoryPathString(BookDirectory.PLAYER, player); String playerFolderPath = BookHelper.getBookDirectoryPathString(BookDirectory.PLAYER, player);

View File

@@ -30,8 +30,6 @@ import org.jetbrains.annotations.Nullable;
import java.io.File; import java.io.File;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getBookFolder;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getSlash;
import static net.knarcraft.bookswithoutborders.utility.BookFileHelper.isBookListIndex; import static net.knarcraft.bookswithoutborders.utility.BookFileHelper.isBookListIndex;
/** /**
@@ -39,8 +37,6 @@ import static net.knarcraft.bookswithoutborders.utility.BookFileHelper.isBookLis
*/ */
public class SignEventListener implements Listener { public class SignEventListener implements Listener {
private final String slash = getSlash();
@EventHandler @EventHandler
public void onSignChange(@NotNull SignChangeEvent event) { public void onSignChange(@NotNull SignChangeEvent event) {
if (event.isCancelled()) { if (event.isCancelled()) {
@@ -207,7 +203,7 @@ public class SignEventListener implements Listener {
} }
//Tests if a full file name has been supplied and points to an actual file //Tests if a full file name has been supplied and points to an actual file
String signFile = getBookFolder() + lines[2] + lines[3]; String signFile = BooksWithoutBorders.getConfiguration().getBookFolder() + lines[2] + lines[3];
if (BookFileHelper.bookFileExists(signFile)) { if (BookFileHelper.bookFileExists(signFile)) {
markGiveSignValidity(event, true); markGiveSignValidity(event, true);
return; return;
@@ -248,6 +244,8 @@ public class SignEventListener implements Listener {
*/ */
private void decryptBook(@NotNull BookMeta oldBook, @NotNull Player player, @NotNull ItemStack heldItem, private void decryptBook(@NotNull BookMeta oldBook, @NotNull Player player, @NotNull ItemStack heldItem,
@NotNull EquipmentSlot hand) { @NotNull EquipmentSlot hand) {
BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
ItemStack newBook; ItemStack newBook;
//Check if the book is encrypted by Books Without Borders //Check if the book is encrypted by Books Without Borders
@@ -259,17 +257,17 @@ public class SignEventListener implements Listener {
//Permission check //Permission check
if (!player.hasPermission("bookswithoutborders.decrypt." + groupName) && if (!player.hasPermission("bookswithoutborders.decrypt." + groupName) &&
!(BooksWithoutBordersConfig.getAdminDecrypt() && player.hasPermission("bookswithoutborders.admin"))) { !(config.getAdminDecrypt() && player.hasPermission("bookswithoutborders.admin"))) {
return; return;
} }
String fileName = oldBook.getTitle() + BooksWithoutBordersConfig.getTitleAuthorSeparator() + oldBook.getAuthor(); String fileName = oldBook.getTitle() + config.getTitleAuthorSeparator() + oldBook.getAuthor();
String encryptionFile = InputCleaningHelper.cleanString(groupName) + slash + fileName + ".yml"; String encryptionFile = InputCleaningHelper.cleanString(groupName) + config.getSlash() + fileName + ".yml";
File file = new File(getBookFolder() + "Encrypted" + slash + encryptionFile); File file = new File(BooksWithoutBorders.getConfiguration().getEncryptedBookPath() + encryptionFile);
if (!file.isFile()) { if (!file.isFile()) {
file = new File(getBookFolder() + fileName + ".txt"); file = new File(config.getBookFolder() + fileName + ".txt");
if (!file.isFile()) { if (!file.isFile()) {
return; return;
} }

View File

@@ -1,7 +1,9 @@
package net.knarcraft.bookswithoutborders.utility; package net.knarcraft.bookswithoutborders.manager;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import net.knarcraft.bookswithoutborders.config.StaticMessage;
import net.knarcraft.bookswithoutborders.config.Translatable;
import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.Economy;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
@@ -13,19 +15,35 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicesManager; import org.bukkit.plugin.ServicesManager;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
/** /**
* Helper class for economy related functions * A manager for managing Vault economy integration
*/ */
public final class EconomyHelper { public class EconomyManager {
private static Economy economy; private @Nullable Economy economy = null;
private EconomyHelper() { /**
* Instantiates the economy manager
*/
public EconomyManager() throws IllegalStateException {
Server server = BooksWithoutBorders.getInstance().getServer();
Plugin plugin = server.getPluginManager().getPlugin("Vault");
ServicesManager servicesManager = server.getServicesManager();
if (plugin == null) {
throw new IllegalStateException(StaticMessage.EXCEPTION_VAULT_NOT_AVAILABLE.toString());
}
RegisteredServiceProvider<Economy> economyProvider = servicesManager.getRegistration(Economy.class);
if (economyProvider != null) {
this.economy = economyProvider.getProvider();
}
} }
/** /**
@@ -33,35 +51,11 @@ public final class EconomyHelper {
* *
* @return <p>An economy instance, or null if it's not initialized</p> * @return <p>An economy instance, or null if it's not initialized</p>
*/ */
@NotNull @Nullable
public static Economy getEconomy() { public Economy getEconomy() {
return economy; return economy;
} }
/**
* Tries to set up economy
*
* @return <p>True if economy is set up and enabled</p>
*/
public static boolean setupEconomy() {
if (economy != null) {
return true;
}
Server server = BooksWithoutBorders.getInstance().getServer();
Plugin plugin = server.getPluginManager().getPlugin("Vault");
ServicesManager servicesManager = server.getServicesManager();
if (plugin != null) {
RegisteredServiceProvider<Economy> economyProvider = servicesManager.getRegistration(Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
}
return (economy != null);
}
/** /**
* Makes the player pay for printing a given number of books * Makes the player pay for printing a given number of books
* *
@@ -69,15 +63,16 @@ public final class EconomyHelper {
* @param numCopies <p>The number of copies the player is trying to print</p> * @param numCopies <p>The number of copies the player is trying to print</p>
* @return <p>True if the player cannot pay for the printing of the books</p> * @return <p>True if the player cannot pay for the printing of the books</p>
*/ */
public static boolean cannotPayForBookPrinting(@NotNull Player player, int numCopies) { public boolean cannotPayForBookPrinting(@NotNull Player player, int numCopies) {
BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
//BookPriceQuantity: How many items are required to pay for each book //BookPriceQuantity: How many items are required to pay for each book
//BookPriceType: Which item is used to pay for the books. AIR = use economy //BookPriceType: Which item is used to pay for the books. AIR = use economy
Material bookCurrency = BooksWithoutBordersConfig.getBookPriceType(); Material bookCurrency = config.getBookPriceType();
double cost = BooksWithoutBordersConfig.getBookPriceQuantity() * numCopies; double cost = config.getBookPriceQuantity() * numCopies;
int itemCost = (int) cost; int itemCost = (int) cost;
if (bookCurrency == Material.AIR) { if (bookCurrency == Material.AIR) {
return !EconomyHelper.payForBookPrintingEconomy(player, cost, numCopies); return !payForBookPrintingEconomy(player, cost, numCopies);
} else { } else {
if (bookCurrency == Material.WRITABLE_BOOK) { if (bookCurrency == Material.WRITABLE_BOOK) {
//Writable books are treated as a special case to prevent WIP books from being used //Writable books are treated as a special case to prevent WIP books from being used
@@ -102,7 +97,7 @@ public final class EconomyHelper {
* @param itemCost <p>The number of writable books to pay</p> * @param itemCost <p>The number of writable books to pay</p>
* @return <p>True if the payment was successful</p> * @return <p>True if the payment was successful</p>
*/ */
private static boolean takeWritableBookPayment(@NotNull Player player, int itemCost) { private boolean takeWritableBookPayment(@NotNull Player player, int itemCost) {
List<ItemStack> books = getPlayersEmptyBooks(player); List<ItemStack> books = getPlayersEmptyBooks(player);
if (countItems(books) < itemCost) { if (countItems(books) < itemCost) {
BooksWithoutBorders.sendErrorMessage(player, itemCost + " empty " + Material.WRITABLE_BOOK + BooksWithoutBorders.sendErrorMessage(player, itemCost + " empty " + Material.WRITABLE_BOOK +
@@ -133,7 +128,7 @@ public final class EconomyHelper {
* @param items <p>The items to count</p> * @param items <p>The items to count</p>
* @return <p>The total number of items</p> * @return <p>The total number of items</p>
*/ */
private static int countItems(@NotNull List<ItemStack> items) { private int countItems(@NotNull List<ItemStack> items) {
int totalItems = 0; int totalItems = 0;
for (ItemStack itemStack : items) { for (ItemStack itemStack : items) {
totalItems += itemStack.getAmount(); totalItems += itemStack.getAmount();
@@ -148,7 +143,7 @@ public final class EconomyHelper {
* @return <p>The empty books in the player's inventory</p> * @return <p>The empty books in the player's inventory</p>
*/ */
@NotNull @NotNull
private static List<ItemStack> getPlayersEmptyBooks(@NotNull Player player) { private List<ItemStack> getPlayersEmptyBooks(@NotNull Player player) {
List<ItemStack> validBooks = new ArrayList<>(); List<ItemStack> validBooks = new ArrayList<>();
for (ItemStack itemStack : player.getInventory().getContents()) { for (ItemStack itemStack : player.getInventory().getContents()) {
if (itemStack == null || itemStack.getType() != Material.WRITABLE_BOOK) { if (itemStack == null || itemStack.getType() != Material.WRITABLE_BOOK) {
@@ -171,7 +166,12 @@ public final class EconomyHelper {
* @param numCopies <p>The number of books the player is printing</p> * @param numCopies <p>The number of books the player is printing</p>
* @return <p>True if the player had the money and it has been withdrawn</p> * @return <p>True if the player had the money and it has been withdrawn</p>
*/ */
private static boolean payForBookPrintingEconomy(@NotNull Player player, double cost, int numCopies) { private boolean payForBookPrintingEconomy(@NotNull Player player, double cost, int numCopies) {
if (economy == null) {
BooksWithoutBorders.getStringFormatter().displayErrorMessage(player, Translatable.ERROR_VAULT_COST_BUT_UNAVAILABLE);
return false;
}
if ((economy.getBalance(player) - cost) >= 0) { if ((economy.getBalance(player) - cost) >= 0) {
economy.withdrawPlayer(player, cost); economy.withdrawPlayer(player, cost);
BooksWithoutBorders.sendSuccessMessage(player, economy.format(cost) + " withdrawn to create " + BooksWithoutBorders.sendSuccessMessage(player, economy.format(cost) + " withdrawn to create " +
@@ -191,12 +191,12 @@ public final class EconomyHelper {
* @param player <p>The player which needs to pay</p> * @param player <p>The player which needs to pay</p>
* @param itemCost <p>The number of items to pay</p> * @param itemCost <p>The number of items to pay</p>
*/ */
private static void payForBookPrintingItem(@NotNull Player player, int itemCost) { private void payForBookPrintingItem(@NotNull Player player, int itemCost) {
PlayerInventory playerInventory = player.getInventory(); PlayerInventory playerInventory = player.getInventory();
int clearedAmount = 0; int clearedAmount = 0;
while (clearedAmount < itemCost) { while (clearedAmount < itemCost) {
int firstItemIndex = playerInventory.first(BooksWithoutBordersConfig.getBookPriceType()); int firstItemIndex = playerInventory.first(BooksWithoutBorders.getConfiguration().getBookPriceType());
ItemStack firstItem = playerInventory.getItem(firstItemIndex); ItemStack firstItem = playerInventory.getItem(firstItemIndex);
if (Objects.requireNonNull(firstItem).getAmount() <= itemCost - clearedAmount) { if (Objects.requireNonNull(firstItem).getAmount() <= itemCost - clearedAmount) {

View File

@@ -12,6 +12,11 @@ public enum EncryptionStyle {
private final String name; private final String name;
/**
* Instantiates a new encryption style
*
* @param name <p>The human-readable encryption style name</p>
*/
EncryptionStyle(@NotNull String name) { EncryptionStyle(@NotNull String name) {
this.name = name; this.name = name;
} }
@@ -32,4 +37,10 @@ public enum EncryptionStyle {
return SUBSTITUTION; return SUBSTITUTION;
} }
@Override
@NotNull
public String toString() {
return this.name;
}
} }

View File

@@ -1,7 +1,7 @@
package net.knarcraft.bookswithoutborders.utility; package net.knarcraft.bookswithoutborders.utility;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.config.Translatable;
import net.knarcraft.bookswithoutborders.state.BookDirectory; import net.knarcraft.bookswithoutborders.state.BookDirectory;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -16,8 +16,6 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getBookFolder;
/** /**
* Helper class for dealing with files * Helper class for dealing with files
*/ */
@@ -33,7 +31,7 @@ public final class BookFileHelper {
* @return <p>True if the number is a book index</p> * @return <p>True if the number is a book index</p>
*/ */
public static boolean isBookListIndex(@NotNull String possibleIndex) { public static boolean isBookListIndex(@NotNull String possibleIndex) {
File bookDirectory = new File(getBookFolder().replaceAll("[\\\\/]$", "")); File bookDirectory = new File(BooksWithoutBorders.getConfiguration().getBookFolder().replaceAll("[\\\\/]$", ""));
try { try {
//Tests if a load list number has been supplied //Tests if a load list number has been supplied
@@ -150,14 +148,12 @@ public final class BookFileHelper {
continue; continue;
} }
String fileName = foundFile.getName(); String fileName = foundFile.getName();
String separator = BooksWithoutBordersConfig.getTitleAuthorSeparator(); String separator = BooksWithoutBorders.getConfiguration().getTitleAuthorSeparator();
if (fileName.contains(separator)) { if (fileName.contains(separator)) {
//Convert the UUID into a username if necessary //Convert the UUID into a username if necessary
String[] data = fileName.split(separator); String userName = getBookAuthorFromPath(fileName);
String extension = data[1].substring(data[1].length() - 4); String title = getBookTitleFromPath(fileName);
String userName = data[1].substring(0, data[1].length() - 4); fileList.add(title + separator + BookHelper.authorFromUUID(userName));
data[1] = BookHelper.authorFromUUID(userName) + extension;
fileList.add(String.join(separator, data));
} else { } else {
fileList.add(fileName); fileList.add(fileName);
} }
@@ -187,4 +183,68 @@ public final class BookFileHelper {
return foundDuplicates; return foundDuplicates;
} }
/**
* Gets a book's title given the book's path
*
* @param path <p>The path of the book</p>
* @return <p>The book title</p>
*/
@NotNull
public static String getBookTitleFromPath(@NotNull String path) {
String separator = BooksWithoutBorders.getConfiguration().getTitleAuthorSeparator();
String stripped = stripExtensionFromPath(path);
if (stripped.contains(separator)) {
return stripped.split(separator)[0];
} else {
return stripped;
}
}
/**
* Gets a book's author given the book's path
*
* @param path <p>The path of the book</p>
* @return <p>The author name</p>
*/
@NotNull
public static String getBookAuthorFromPath(@NotNull String path) {
String separator = BooksWithoutBorders.getConfiguration().getTitleAuthorSeparator();
String stripped = stripExtensionFromPath(path);
if (stripped.contains(separator)) {
return stripped.split(separator)[1];
} else {
return BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(Translatable.NEUTRAL_UNKNOWN_AUTHOR);
}
}
/**
* Strips the extension from the given path
*
* @param path <p>The path to strip the extension from</p>
* @return <p>The input with the extension stripped</p>
*/
@NotNull
public static String stripExtensionFromPath(@NotNull String path) {
if (path.contains(".")) {
return path.substring(0, path.lastIndexOf("."));
} else {
return path;
}
}
/**
* Gets the extension from the given path
*
* @param path <p>The path to get the extension from</p>
* @return <p>The extension of the input</p>
*/
@NotNull
public static String getExtensionFromPath(@NotNull String path) {
if (path.contains(".")) {
return path.substring((path.length() - path.lastIndexOf(".")) + 1);
} else {
return "";
}
}
} }

View File

@@ -2,6 +2,7 @@ package net.knarcraft.bookswithoutborders.utility;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import net.knarcraft.bookswithoutborders.config.Translatable;
import net.knarcraft.bookswithoutborders.state.BookDirectory; import net.knarcraft.bookswithoutborders.state.BookDirectory;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -14,7 +15,6 @@ import org.jetbrains.annotations.Nullable;
import java.io.File; import java.io.File;
import java.util.UUID; import java.util.UUID;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getSlash;
import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.fixName; import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.fixName;
/** /**
@@ -35,7 +35,7 @@ public final class BookHelper {
@NotNull @NotNull
public static String authorFromUUID(@NotNull String author) { public static String authorFromUUID(@NotNull String author) {
try { try {
UUID authorID = UUID.fromString(author); UUID authorID = UUID.fromString(BookFormatter.stripColor(author));
Player player = Bukkit.getPlayer(authorID); Player player = Bukkit.getPlayer(authorID);
if (player != null) { if (player != null) {
author = player.getName(); author = player.getName();
@@ -70,12 +70,13 @@ public final class BookHelper {
*/ */
@Nullable @Nullable
public static String getBookDirectoryPathString(@NotNull BookDirectory bookDirectory, @NotNull CommandSender sender) { public static String getBookDirectoryPathString(@NotNull BookDirectory bookDirectory, @NotNull CommandSender sender) {
BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
String folder = null; String folder = null;
String bookFolder = BooksWithoutBordersConfig.getBookFolder(); String bookFolder = config.getBookFolder();
if (bookDirectory == BookDirectory.PUBLIC) { if (bookDirectory == BookDirectory.PUBLIC) {
folder = bookFolder; folder = bookFolder;
} else if (bookDirectory == BookDirectory.PLAYER && sender instanceof Player player) { } else if (bookDirectory == BookDirectory.PLAYER && sender instanceof Player player) {
folder = bookFolder + player.getUniqueId() + getSlash(); folder = bookFolder + player.getUniqueId() + config.getSlash();
} }
return folder; return folder;
} }
@@ -87,7 +88,7 @@ public final class BookHelper {
*/ */
public static void increaseGeneration(@NotNull ItemStack bookItem) { public static void increaseGeneration(@NotNull ItemStack bookItem) {
BookMeta bookMeta = (BookMeta) bookItem.getItemMeta(); BookMeta bookMeta = (BookMeta) bookItem.getItemMeta();
if (BooksWithoutBordersConfig.changeGenerationOnCopy() && bookMeta != null) { if (BooksWithoutBorders.getConfiguration().changeGenerationOnCopy() && bookMeta != null) {
bookMeta.setGeneration(BookHelper.getNextGeneration(bookMeta.getGeneration())); bookMeta.setGeneration(BookHelper.getNextGeneration(bookMeta.getGeneration()));
bookItem.setItemMeta(bookMeta); bookItem.setItemMeta(bookMeta);
} }
@@ -124,7 +125,7 @@ public final class BookHelper {
*/ */
@NotNull @NotNull
public static String getBookFile(@NotNull BookMeta book, @NotNull Player player, boolean isPublic) throws IllegalArgumentException { public static String getBookFile(@NotNull BookMeta book, @NotNull Player player, boolean isPublic) throws IllegalArgumentException {
String titleAuthorSeparator = BooksWithoutBordersConfig.getTitleAuthorSeparator(); String titleAuthorSeparator = BooksWithoutBorders.getConfiguration().getTitleAuthorSeparator();
String bookName; String bookName;
if (book.hasTitle()) { if (book.hasTitle()) {
bookName = book.getTitle(); bookName = book.getTitle();
@@ -144,7 +145,7 @@ public final class BookHelper {
} else { } else {
authorName = book.getAuthor(); authorName = book.getAuthor();
if (authorName == null) { if (authorName == null) {
authorName = "Unknown"; authorName = BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(Translatable.NEUTRAL_UNKNOWN_AUTHOR);
} }
} }

View File

@@ -68,18 +68,21 @@ public final class BookLoader {
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
} }
BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
//Get the full path of the book to load //Get the full path of the book to load
File file = getFullPath(sender, fileName, bookDirectory, directory); File file = getFullPath(sender, fileName, bookDirectory, directory);
if (file == null) { if (file == null) {
//Try converting the username to UUID //Try converting the username to UUID
String titleAuthorSeparator = BooksWithoutBordersConfig.getTitleAuthorSeparator(); String separator = config.getTitleAuthorSeparator();
String[] data = fileName.split(titleAuthorSeparator); String userName = BookFileHelper.getBookAuthorFromPath(fileName);
String extension = data[1].substring(data[1].length() - 4); String title = BookFileHelper.getBookTitleFromPath(fileName);
String userName = data[1].substring(0, data[1].length() - 4); String extension = BookFileHelper.getExtensionFromPath(fileName);
Player player = Bukkit.getPlayer(userName); Player player = Bukkit.getPlayer(userName);
if (player != null) { if (player != null) {
data[1] = player.getUniqueId() + extension; userName = userName.replace(BookFormatter.stripColor(userName), player.getUniqueId().toString());
file = getFullPath(sender, String.join(titleAuthorSeparator, data), bookDirectory, directory); file = getFullPath(sender, title + separator + userName + extension, bookDirectory, directory);
if (file == null) { if (file == null) {
BooksWithoutBorders.sendErrorMessage(sender, "Incorrect file name!"); BooksWithoutBorders.sendErrorMessage(sender, "Incorrect file name!");
return null; return null;
@@ -90,10 +93,10 @@ public final class BookLoader {
} }
//Make sure the player can pay for the book //Make sure the player can pay for the book
if (BooksWithoutBordersConfig.booksHavePrice() && if (config.booksHavePrice() &&
!sender.hasPermission("bookswithoutborders.bypassBookPrice") && !sender.hasPermission("bookswithoutborders.bypassBookPrice") &&
(bookDirectory == BookDirectory.PUBLIC || bookDirectory == BookDirectory.PLAYER) && (bookDirectory == BookDirectory.PUBLIC || bookDirectory == BookDirectory.PLAYER) &&
EconomyHelper.cannotPayForBookPrinting((Player) sender, numCopies)) { config.getEconomyManager().cannotPayForBookPrinting((Player) sender, numCopies)) {
return null; return null;
} }
@@ -149,11 +152,11 @@ public final class BookLoader {
@Nullable @Nullable
private static File getFullPath(@NotNull CommandSender sender, @NotNull String fileName, private static File getFullPath(@NotNull CommandSender sender, @NotNull String fileName,
@NotNull BookDirectory bookDirectory, @NotNull String directory) { @NotNull BookDirectory bookDirectory, @NotNull String directory) {
BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
File file; File file;
String slash = BooksWithoutBordersConfig.getSlash(); String slash = config.getSlash();
String bookFolder = BooksWithoutBordersConfig.getBookFolder();
if (bookDirectory == BookDirectory.ENCRYPTED) { if (bookDirectory == BookDirectory.ENCRYPTED) {
file = BookFileHelper.getBookFile(bookFolder + "Encrypted" + slash + directory + slash + fileName); file = BookFileHelper.getBookFile(config.getEncryptedBookPath() + directory + slash + fileName);
} else { } else {
file = BookFileHelper.getBookFile(BookHelper.getBookDirectoryPathString(bookDirectory, sender) + fileName); file = BookFileHelper.getBookFile(BookHelper.getBookDirectoryPathString(bookDirectory, sender) + fileName);
} }

View File

@@ -1,7 +1,7 @@
package net.knarcraft.bookswithoutborders.utility; package net.knarcraft.bookswithoutborders.utility;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders; import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.config.Translatable;
import net.knarcraft.knarlib.util.FileHelper; import net.knarcraft.knarlib.util.FileHelper;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@@ -122,7 +122,8 @@ public final class BookToFromTextHelper {
bookMetadata.setGeneration(BookMeta.Generation.valueOf(bookYml.getString("Generation", "ORIGINAL"))); bookMetadata.setGeneration(BookMeta.Generation.valueOf(bookYml.getString("Generation", "ORIGINAL")));
bookMetadata.setTitle(bookYml.getString("Title", "Untitled")); bookMetadata.setTitle(bookYml.getString("Title", "Untitled"));
bookMetadata.setAuthor(authorFromUUID(bookYml.getString("Author", "Unknown"))); bookMetadata.setAuthor(authorFromUUID(bookYml.getString("Author",
BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(Translatable.NEUTRAL_UNKNOWN_AUTHOR))));
bookMetadata.setPages(bookYml.getStringList("Pages")); bookMetadata.setPages(bookYml.getStringList("Pages"));
bookMetadata.setLore(bookYml.getStringList("Lore")); bookMetadata.setLore(bookYml.getStringList("Lore"));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@@ -141,21 +142,9 @@ public final class BookToFromTextHelper {
*/ */
@Nullable @Nullable
private static BookMeta bookFromTXT(@NotNull String fileName, @NotNull File file, @NotNull BookMeta bookMetadata) { private static BookMeta bookFromTXT(@NotNull String fileName, @NotNull File file, @NotNull BookMeta bookMetadata) {
String author;
String title;
String titleAuthorSeparator = BooksWithoutBordersConfig.getTitleAuthorSeparator();
//Remove .txt extension
fileName = fileName.substring(0, fileName.length() - 4);
//Get title and author from the file name //Get title and author from the file name
if (fileName.contains(titleAuthorSeparator)) { String title = BookFileHelper.getBookTitleFromPath(fileName);
String[] titleAuthor = fileName.split(titleAuthorSeparator); String author = BookFileHelper.getBookAuthorFromPath(fileName);
title = titleAuthor[0];
author = titleAuthor[1];
} else {
author = "Unknown";
title = fileName;
}
//Replace underscores with spaces //Replace underscores with spaces
title = fixName(title, true); title = fixName(title, true);
@@ -165,11 +154,11 @@ public final class BookToFromTextHelper {
try { try {
rawPages = readTextFile(file); rawPages = readTextFile(file);
if (rawPages == null) { if (rawPages == null) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Text file's first line was null"); BooksWithoutBorders.log(Level.SEVERE, "Text file's first line was null");
return null; return null;
} }
} catch (IOException exception) { } catch (IOException exception) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to read text file"); BooksWithoutBorders.log(Level.SEVERE, "Unable to read text file");
return null; return null;
} }

View File

@@ -20,8 +20,6 @@ import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getBookFolder;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getSlash;
import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.cleanString; import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.cleanString;
import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.fixName; import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.fixName;
@@ -211,7 +209,7 @@ public final class EncryptionHelper {
public static ItemStack loadEncryptedBook(@NotNull Player player, @NotNull String key, boolean deleteEncryptedFile) { public static ItemStack loadEncryptedBook(@NotNull Player player, @NotNull String key, boolean deleteEncryptedFile) {
ItemStack heldBook = InventoryHelper.getHeldBook(player, true); ItemStack heldBook = InventoryHelper.getHeldBook(player, true);
BookMeta bookMetadata = (BookMeta) heldBook.getItemMeta(); BookMeta bookMetadata = (BookMeta) heldBook.getItemMeta();
String path = getBookFolder() + "Encrypted" + getSlash(); String path = BooksWithoutBorders.getConfiguration().getEncryptedBookPath();
if (bookMetadata == null) { if (bookMetadata == null) {
return null; return null;
@@ -266,17 +264,18 @@ public final class EncryptionHelper {
@Nullable @Nullable
private static BookMeta saveEncryptedBookForGroup(@NotNull Player player, @NotNull BookMeta bookMetadata, private static BookMeta saveEncryptedBookForGroup(@NotNull Player player, @NotNull BookMeta bookMetadata,
@NotNull String groupName) { @NotNull String groupName) {
String path = getBookFolder() + "Encrypted" + getSlash() + cleanString(groupName) + getSlash(); BooksWithoutBordersConfig config = BooksWithoutBorders.getConfiguration();
String path = config.getEncryptedBookPath() + cleanString(groupName) + config.getSlash();
File dirTest = new File(path); File dirTest = new File(path);
//Creates group dir //Creates group dir
if (!dirTest.exists()) { if (!dirTest.exists()) {
try { try {
if (!dirTest.mkdir()) { if (!dirTest.mkdir()) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to create encryption group folder!"); BooksWithoutBorders.log(Level.SEVERE, "Unable to create encryption group folder!");
return null; return null;
} }
} catch (Exception exception) { } catch (Exception exception) {
BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to save group encrypted book"); BooksWithoutBorders.log(Level.SEVERE, "Unable to save group encrypted book");
return null; return null;
} }
} }
@@ -294,7 +293,7 @@ public final class EncryptionHelper {
bookMetadata.setLore(newLore); bookMetadata.setLore(newLore);
//Save file //Save file
File file = (BooksWithoutBordersConfig.getUseYml()) ? new File(path + fileName + ".yml") : File file = (BooksWithoutBorders.getConfiguration().getUseYml()) ? new File(path + fileName + ".yml") :
new File(path + fileName + ".txt"); new File(path + fileName + ".txt");
if (!file.isFile()) { if (!file.isFile()) {
try { try {
@@ -318,13 +317,13 @@ public final class EncryptionHelper {
*/ */
@NotNull @NotNull
private static Boolean saveEncryptedBook(@NotNull Player player, @NotNull BookMeta bookMetaData, @NotNull String key) { private static Boolean saveEncryptedBook(@NotNull Player player, @NotNull BookMeta bookMetaData, @NotNull String key) {
String path = getBookFolder() + "Encrypted" + getSlash(); String path = BooksWithoutBorders.getConfiguration().getEncryptedBookPath();
String fileName = "[" + key + "]" + BookHelper.getBookFile(bookMetaData, player, true); String fileName = "[" + key + "]" + BookHelper.getBookFile(bookMetaData, player, true);
fileName = fixName(cleanString(fileName), false); fileName = fixName(cleanString(fileName), false);
//cancels saving if file is already encrypted //cancels saving if file is already encrypted
File file = (BooksWithoutBordersConfig.getUseYml()) ? new File(path + fileName + ".yml") : File file = (BooksWithoutBorders.getConfiguration().getUseYml()) ? new File(path + fileName + ".yml") :
new File(path + fileName + ".txt"); new File(path + fileName + ".txt");
if (file.isFile()) { if (file.isFile()) {
return true; return true;

View File

@@ -14,6 +14,7 @@ en:
ERROR_BOOK_COPIED_TOO_FAR: "You cannot copy this book any further. You must have the original or a direct copy." ERROR_BOOK_COPIED_TOO_FAR: "You cannot copy this book any further. You must have the original or a direct copy."
ERROR_INVENTORY_FULL: "You need an available slot in your inventory." ERROR_INVENTORY_FULL: "You need an available slot in your inventory."
ERROR_METADATA_MISSING: "Unable to get metadata for the held book!" ERROR_METADATA_MISSING: "Unable to get metadata for the held book!"
ERROR_VAULT_COST_BUT_UNAVAILABLE: "The cost was set to economy, but Vault is unavailable!"
NEUTRAL_COMMANDS_HEADER: | NEUTRAL_COMMANDS_HEADER: |
&e[] denote optional parameters &e[] denote optional parameters
<> denote required parameters <> denote required parameters
@@ -26,5 +27,7 @@ en:
NEUTRAL_COMMANDS_COMMAND: "\n \n&e{usage}: &a{description}" NEUTRAL_COMMANDS_COMMAND: "\n \n&e{usage}: &a{description}"
NEUTRAL_COMMANDS_COMMAND_NO_PERMISSION_REQUIRED: "None" NEUTRAL_COMMANDS_COMMAND_NO_PERMISSION_REQUIRED: "None"
NEUTRAL_COMMANDS_COMMAND_PERMISSION: " &7{{permission}}" NEUTRAL_COMMANDS_COMMAND_PERMISSION: " &7{{permission}}"
NEUTRAL_UNKNOWN_AUTHOR: "Unknown"
ACTION_COPY: "copy" ACTION_COPY: "copy"
ACTION_CLEAR: "clear" ACTION_CLEAR: "clear"
ACTION_DECRYPT: "decrypt"