Changes formatting method for remaining code
All checks were successful
EpicKnarvik97/Books-Without-Borders/pipeline/head This commit looks good

This commit is contained in:
2025-08-26 11:07:10 +02:00
parent dcf6310d16
commit b9edc52896
23 changed files with 184 additions and 295 deletions

View File

@@ -40,6 +40,7 @@ import net.knarcraft.bookswithoutborders.container.MigrationRequest;
import net.knarcraft.bookswithoutborders.handler.BookshelfHandler;
import net.knarcraft.bookswithoutborders.listener.BookEventListener;
import net.knarcraft.bookswithoutborders.listener.BookshelfListener;
import net.knarcraft.bookswithoutborders.listener.GroupDecryptListener;
import net.knarcraft.bookswithoutborders.listener.PlayerEventListener;
import net.knarcraft.bookswithoutborders.listener.SignEventListener;
import net.knarcraft.bookswithoutborders.utility.BookFileHelper;
@@ -85,7 +86,6 @@ public class BooksWithoutBorders extends JavaPlugin {
private Map<Character, Integer> publicLetterIndex;
private Map<UUID, Map<Character, Integer>> playerLetterIndex;
private BookshelfHandler bookshelfHandler;
private StringFormatter stringFormatter;
private BwBConfig booksWithoutBordersConfig;
private final Queue<MigrationRequest> migrationQueue = new LinkedList<>();
@@ -108,15 +108,6 @@ public class BooksWithoutBorders extends JavaPlugin {
return getInstance().booksWithoutBordersConfig;
}
/**
* Gets the string formatter
*
* @return <p>The string formatter</p>
*/
public static StringFormatter getStringFormatter() {
return getInstance().stringFormatter;
}
/**
* Gets the migration queue
*
@@ -221,7 +212,7 @@ public class BooksWithoutBorders extends JavaPlugin {
translator.registerMessageCategory(SaveMessage.SUCCESS_SAVED);
translator.registerMessageCategory(SignText.SIGN_HEADER);
stringFormatter = new StringFormatter(this.getDescription().getName(), translator);
StringFormatter stringFormatter = new StringFormatter(this.getDescription().getName(), translator);
stringFormatter.setColorConversion(ColorConversion.RGB);
stringFormatter.setSuccessColor(ChatColor.of("#A9FF84"));
stringFormatter.setErrorColor(ChatColor.of("#FF84A9"));
@@ -246,6 +237,7 @@ public class BooksWithoutBorders extends JavaPlugin {
pluginManager.registerEvents(new SignEventListener(), this);
pluginManager.registerEvents(new BookEventListener(), this);
pluginManager.registerEvents(new BookshelfListener(), this);
pluginManager.registerEvents(new GroupDecryptListener(), this);
} else {
this.getPluginLoader().disablePlugin(this);
}
@@ -309,7 +301,8 @@ public class BooksWithoutBorders extends JavaPlugin {
if (pluginCommand != null) {
pluginCommand.setExecutor(executor);
} else {
getLogger().log(Level.SEVERE, "Failed to register command " + commandName);
getLogger().log(Level.SEVERE, new FormatBuilder(StaticMessage.EXCEPTION_COMMAND_REGISTRATION_FAILED.toString()).
replace("{command}", commandName).build());
}
}
@@ -323,10 +316,7 @@ public class BooksWithoutBorders extends JavaPlugin {
try {
itemFactory = this.getServer().getItemFactory();
} catch (java.lang.NoSuchMethodError noSuchMethodError) {
getLogger().log(Level.SEVERE, """
Warning! [BooksWithoutBorders] failed to initialize!
Please confirm the correct version of [BooksWithoutBorders] is
being run for this version of spigot!""");
getLogger().log(Level.SEVERE, StaticMessage.EXCEPTION_ITEM_FACTORY_INIT_FAILED.toString());
return false;
}

View File

@@ -57,14 +57,14 @@ public class CommandSetBookPrice implements TabExecutor {
return false;
}
return switch (arguments[0].toLowerCase()) {
case "item" -> setItemPrice(sender, price);
case "economy" -> setEconomyPrice(sender, price);
default -> {
new FormatBuilder(CostMessage.ERROR_COST_INVALID_TYPE).error(sender);
yield false;
}
};
if (arguments[0].equalsIgnoreCase("item")) {
return setItemPrice(sender, price);
} else if (arguments[0].equalsIgnoreCase(StaticMessage.COST_ECONOMY.toString())) {
return setEconomyPrice(sender, price);
} else {
new FormatBuilder(CostMessage.ERROR_COST_INVALID_TYPE).error(sender);
return false;
}
}
/**
@@ -76,11 +76,11 @@ public class CommandSetBookPrice implements TabExecutor {
BwBConfig config = BooksWithoutBorders.getConfiguration();
config.setBookPriceType(null);
config.setBookPriceQuantity(0);
booksWithoutBorders.getConfig().set(ConfigOption.PRICE_ITEM_TYPE.getConfigNode(), "Item type name");
booksWithoutBorders.getConfig().set(ConfigOption.PRICE_ITEM_TYPE.getConfigNode(), StaticMessage.COST_NONE.toString());
booksWithoutBorders.getConfig().set(ConfigOption.PRICE_QUANTITY.getConfigNode(), config.getBookPriceQuantity());
booksWithoutBorders.saveConfig();
BooksWithoutBorders.getStringFormatter().displaySuccessMessage(sender, CostMessage.SUCCESS_COST_REMOVED);
new FormatBuilder(CostMessage.SUCCESS_COST_REMOVED).success(sender);
}
/**
@@ -130,7 +130,7 @@ public class CommandSetBookPrice implements TabExecutor {
config.setBookPriceQuantity(price);
config.setBookPriceType(Material.AIR);
double newPriceQuantity = config.getBookPriceQuantity();
booksWithoutBorders.getConfig().set(ConfigOption.PRICE_ITEM_TYPE.getConfigNode(), "Economy");
booksWithoutBorders.getConfig().set(ConfigOption.PRICE_ITEM_TYPE.getConfigNode(), StaticMessage.COST_ECONOMY.toString());
booksWithoutBorders.getConfig().set(ConfigOption.PRICE_QUANTITY.getConfigNode(), newPriceQuantity);
booksWithoutBorders.saveConfig();
@@ -165,7 +165,7 @@ public class CommandSetBookPrice implements TabExecutor {
private void initializeTabCompleteLists() {
paymentTypes = new ArrayList<>();
paymentTypes.add("item");
paymentTypes.add("economy");
paymentTypes.add(StaticMessage.COST_ECONOMY.toString().toLowerCase());
}
}

View File

@@ -6,7 +6,7 @@ import net.knarcraft.bookswithoutborders.config.translation.Translatable;
import net.knarcraft.bookswithoutborders.state.ItemSlot;
import net.knarcraft.bookswithoutborders.utility.BookHelper;
import net.knarcraft.bookswithoutborders.utility.InventoryHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
@@ -27,17 +27,14 @@ public class CommandUnSign implements TabExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label,
@NotNull String[] arguments) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
if (!(sender instanceof Player player)) {
stringFormatter.displayErrorMessage(sender, Translatable.ERROR_PLAYER_ONLY);
new FormatBuilder(Translatable.ERROR_PLAYER_ONLY).error(sender);
return false;
}
if (InventoryHelper.notHoldingOneWrittenBookCheck(player,
stringFormatter.replacePlaceholder(Translatable.ERROR_NOT_HOLDING_WRITTEN_BOOK, "{action}",
stringFormatter.getUnFormattedColoredMessage(Translatable.ACTION_UNSIGN)),
stringFormatter.replacePlaceholder(Translatable.ERROR_ONLY_ONE_BOOK, "{action}",
stringFormatter.getUnFormattedColoredMessage(Translatable.ACTION_UNSIGN)))) {
new FormatBuilder(Translatable.ERROR_NOT_HOLDING_WRITTEN_BOOK).replace("{action}", Translatable.ACTION_UNSIGN).build(),
new FormatBuilder(Translatable.ERROR_ONLY_ONE_BOOK).replace("{action}", Translatable.ACTION_UNSIGN).build())) {
return false;
}
@@ -57,7 +54,7 @@ public class CommandUnSign implements TabExecutor {
//Get the old book
BookMeta oldMetadata = InventoryHelper.getHeldBookMetadata(player, mainHand);
if (oldMetadata == null) {
BooksWithoutBorders.getStringFormatter().displayErrorMessage(player, Translatable.ERROR_METADATA_MISSING);
new FormatBuilder(Translatable.ERROR_METADATA_MISSING).error(player);
return;
}
ItemStack heldBook = InventoryHelper.getHeldBook(player, mainHand);
@@ -78,6 +75,7 @@ public class CommandUnSign implements TabExecutor {
reverseColorCodes(book);
InventoryHelper.replaceHeldItem(player, book, mainHand);
new FormatBuilder(Translatable.SUCCESS_UNSIGNED).success(player);
}
@Override

View File

@@ -3,7 +3,6 @@ package net.knarcraft.bookswithoutborders.config;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.manager.EconomyManager;
import net.knarcraft.knarlib.formatting.Translator;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.Configuration;
import org.jetbrains.annotations.NotNull;
@@ -12,7 +11,6 @@ import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.cleanString;
@@ -21,10 +19,7 @@ import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.clea
*/
public class BwBConfig {
private final ChatColor errorColor = ChatColor.RED;
private final ChatColor successColor = ChatColor.GREEN;
private final String SLASH = FileSystems.getDefault().getSeparator();
private boolean isInitialized;
private final String bookFolder;
private int bookDuplicateLimit;
@@ -53,11 +48,7 @@ public class BwBConfig {
* @param booksWithoutBorders <p>The books without borders object used for getting required data</p>
*/
public BwBConfig(@NotNull BooksWithoutBorders booksWithoutBorders, @NotNull Translator translator) {
if (isInitialized) {
throw new IllegalArgumentException("Settings class initialized twice. This should not happen!");
}
this.translator = translator;
isInitialized = true;
bookFolder = booksWithoutBorders.getDataFolder().getAbsolutePath() + getSlash() + "Books" + getSlash();
loadConfig();
}
@@ -81,24 +72,6 @@ public class BwBConfig {
return this.bookFolder;
}
/**
* Gets the color to use for error messages
*
* @return <p>The color to use for error messages</p>
*/
public ChatColor getErrorColor() {
return this.errorColor;
}
/**
* Gets the color to use for success messages
*
* @return <p>The color to use for success messages</p>
*/
public ChatColor getSuccessColor() {
return this.successColor;
}
/**
* Gets the correct slash to use for the used OS
*
@@ -314,10 +287,10 @@ public class BwBConfig {
if (this.bookPriceType != Material.AIR) {
config.set(itemTypeNode, this.bookPriceType.toString());
} else {
config.set(itemTypeNode, "Economy");
config.set(itemTypeNode, StaticMessage.COST_ECONOMY.toString());
}
} else {
config.set(itemTypeNode, "Item type name");
config.set(itemTypeNode, StaticMessage.COST_NONE.toString());
}
config.set(ConfigOption.PRICE_QUANTITY.getConfigNode(), this.bookPriceQuantity);
@@ -336,7 +309,6 @@ public class BwBConfig {
* @return <p>True if the config was loaded successfully</p>
*/
public boolean loadConfig() {
Logger logger = BooksWithoutBorders.getInstance().getLogger();
BooksWithoutBorders.getInstance().reloadConfig();
Configuration config = BooksWithoutBorders.getInstance().getConfig();
try {
@@ -361,9 +333,9 @@ public class BwBConfig {
//Convert string into material
this.economyManager = new EconomyManager();
String paymentMaterial = getString(config, ConfigOption.PRICE_ITEM_TYPE);
if (paymentMaterial.equalsIgnoreCase("Economy")) {
if (paymentMaterial.equalsIgnoreCase(StaticMessage.COST_ECONOMY.toString())) {
if (this.economyManager.getEconomy() == null) {
logger.log(Level.SEVERE, StaticMessage.EXCEPTION_VAULT_NOT_AVAILABLE.toString());
BooksWithoutBorders.log(Level.SEVERE, StaticMessage.EXCEPTION_VAULT_NOT_AVAILABLE.toString());
this.bookPriceType = null;
} else {
this.bookPriceType = Material.AIR;
@@ -380,15 +352,13 @@ public class BwBConfig {
//Make sure titleAuthorSeparator is a valid value
this.titleAuthorSeparator = cleanString(this.titleAuthorSeparator);
if (this.titleAuthorSeparator.length() != 1) {
logger.log(Level.SEVERE, "Title author separator is set to an invalid value!\n" +
"Reverting to default value of \",\"");
BooksWithoutBorders.log(Level.SEVERE, StaticMessage.EXCEPTION_TITLE_AUTHOR_SEPARATOR_INVALID.toString());
this.titleAuthorSeparator = ",";
config.set(ConfigOption.TITLE_AUTHOR_SEPARATOR.getConfigNode(), this.titleAuthorSeparator);
}
} catch (Exception exception) {
logger.log(Level.SEVERE, exception.getMessage());
logger.log(Level.SEVERE, "Warning! Config.yml failed to load!\n" +
"Try Looking for settings that are missing values!");
BooksWithoutBorders.log(Level.SEVERE, exception.getMessage());
BooksWithoutBorders.log(Level.SEVERE, StaticMessage.EXCEPTION_CONFIGURATION_INVALID.toString());
return false;
}

View File

@@ -31,6 +31,28 @@ public enum StaticMessage {
EXCEPTION_BOOK_UNKNOWN_EXTENSION("Trying to load a book file with an unrecognized extension"),
EXCEPTION_UNEXPECTED_ENCRYPTED_BOOK("Attempted to load a normal book, but found an encrypted book instead"),
EXCEPTION_NOT_HOLDING_ONE_BOOK("The player is not holding exactly one book."),
EXCEPTION_TITLE_AUTHOR_SEPARATOR_INVALID("Title author separator is set to an invalid value!\nReverting to default value of \",\""),
EXCEPTION_CONFIGURATION_INVALID("Warning! Config.yml failed to load!\nTry Looking for settings that are missing values!"),
EXCEPTION_BOOK_METADATA_CREATION_FAILED("Unable to create writable book metadata"),
EXCEPTION_AES_NO_CONFIGURATION("Attempted to save AES encrypted book without supplying a configuration!"),
EXCEPTION_ENCRYPTED_LOAD_FAILED("Book encryption failed!"),
EXCEPTION_ENCRYPTED_GROUP_FOLDER_CREATION_FAILED("Unable to create encryption group folder!"),
EXCEPTION_GROUP_ENCRYPT_SAVE_FAILED("Unable to save group encrypted book"),
EXCEPTION_COMMAND_REGISTRATION_FAILED("Failed to register command {command}"),
EXCEPTION_ITEM_FACTORY_INIT_FAILED("""
Warning! [BooksWithoutBorders] failed to initialize!
Please confirm the correct version of [BooksWithoutBorders] is
being run for this version of spigot!"""),
/**
* The cost type used to specify economy
*/
COST_ECONOMY("Economy"),
/**
* The cost type to specify no cost
*/
COST_NONE("Item type name"),
;
private final @NotNull String messageString;

View File

@@ -98,6 +98,11 @@ public enum Translatable implements TranslatableMessage {
*/
SUCCESS_ENCRYPTED,
/**
* The success message displayed when a book is successfully unsigned
*/
SUCCESS_UNSIGNED,
/**
* The neutral message displayed when attempting legacy decryption after the updated decryption has failed
*/

View File

@@ -4,6 +4,7 @@ import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.translation.Formatting;
import net.knarcraft.bookswithoutborders.utility.BookFileHelper;
import net.knarcraft.bookswithoutborders.utility.BookFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.knarcraft.knarlib.formatting.TranslatableMessage;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent;
@@ -35,7 +36,7 @@ public class AuthorBookIndex extends BookIndex {
int totalPages = (int) Math.ceil((double) availableBooks.size() / booksPerPage);
if (page > totalPages) {
BooksWithoutBorders.getStringFormatter().displayErrorMessage(sender, Formatting.NEUTRAL_AUTHOR_BOOKS_INVALID_PAGE);
new FormatBuilder(Formatting.NEUTRAL_AUTHOR_BOOKS_INVALID_PAGE).error(sender);
} else {
showAuthorBooks(sender, command, page, totalPages, availableBooks, authorName, listPublic);
}
@@ -59,7 +60,7 @@ public class AuthorBookIndex extends BookIndex {
String navigationCommand = command + " author" + authorName;
TranslatableMessage message = listPublic ? Formatting.NEUTRAL_AUTHOR_PUBLIC_BOOKS_HEADER : Formatting.NEUTRAL_AUTHOR_PLAYER_BOOKS_HEADER;
componentBuilder.append(color(message, "{author}", authorName));
componentBuilder.append(new FormatBuilder(message).replace("{author}", authorName).color().build());
displayBookList(componentBuilder, command, page, availableBooks);
@@ -85,13 +86,13 @@ public class AuthorBookIndex extends BookIndex {
for (int bookIndex = startIndex; bookIndex < Math.min(startIndex + booksPerPage, availableBooks.size()); bookIndex++) {
String title = BookFileHelper.getBookTitleFromPath(availableBooks.get(bookIndex));
String author = BookFileHelper.getBookAuthorFromPath(availableBooks.get(bookIndex));
String niceName = color(title) + color(Formatting.NEUTRAL_BOOK_LIST_AUTHOR_SEPARATOR) + color(author);
String niceName = new FormatBuilder(title + Formatting.NEUTRAL_BOOK_LIST_AUTHOR_SEPARATOR + author).color().build();
componentBuilder.append(niceName).color(ChatColor.WHITE).event(
new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + command + " " +
availableBooks.get(bookIndex))).event(
new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(BooksWithoutBorders.getStringFormatter().
getUnFormattedColoredMessage(Formatting.NEUTRAL_AUTHOR_BOOKS_PATH))));
new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(
new FormatBuilder(Formatting.NEUTRAL_AUTHOR_BOOKS_PATH).color().build())));
componentBuilder.append("\n");
}
}

View File

@@ -1,12 +1,8 @@
package net.knarcraft.bookswithoutborders.gui;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.translation.Formatting;
import net.knarcraft.bookswithoutborders.utility.InputCleaningHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.TranslatableMessage;
import net.knarcraft.knarlib.property.ColorConversion;
import net.knarcraft.knarlib.util.ColorHelper;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
@@ -14,9 +10,7 @@ import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.hover.content.Text;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
public abstract class BookIndex {
@@ -89,8 +83,8 @@ public abstract class BookIndex {
*/
protected static void displayTotalPages(@NotNull ComponentBuilder componentBuilder, @NotNull String command,
int page, int totalPages) {
String pageDisplay = color(Formatting.NEUTRAL_BOOK_LIST_TOTAL_PAGES, List.of("{current}", "{total}"),
List.of(String.valueOf(page), String.valueOf(totalPages)));
String pageDisplay = new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_TOTAL_PAGES).replace("{current}",
String.valueOf(page)).replace("{total}", String.valueOf(totalPages)).color().build();
componentBuilder.append(pageDisplay,
ComponentBuilder.FormatRetention.NONE).color(interactColor).event(new HoverEvent(
HoverEvent.Action.SHOW_TEXT, new Text("/" + command + " page" + page))).event(
@@ -112,7 +106,7 @@ public abstract class BookIndex {
if (firstInstances.containsKey(character)) {
int pageIndex = (firstInstances.get(character) / booksPerPage) + 1;
HoverEvent hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(
color(Formatting.NEUTRAL_BOOK_LIST_INDEX_HOVER, "{character}", "" + character)));
new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_INDEX_HOVER).replace("{character}", "" + character).color().build()));
ClickEvent clickEvent = new ClickEvent(ClickEvent.Action.RUN_COMMAND,
"/" + command + " page" + pageIndex);
@@ -133,11 +127,11 @@ public abstract class BookIndex {
*/
protected static void displayPreviousButton(@NotNull ComponentBuilder componentBuilder,
@NotNull String command, int page) {
String previousPage = color(Formatting.NEUTRAL_BOOK_LIST_PREVIOUS_PAGE);
String previousPage = new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_PREVIOUS_PAGE).color().build();
if (page > 1) {
String fullCommand = "/" + command + " page" + (page - 1);
HoverEvent prevPagePreview = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(
color(Formatting.NEUTRAL_BOOK_LIST_TO_PAGE, "{page}", String.valueOf(page - 1))));
new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_TO_PAGE).replace("{page}", String.valueOf(page - 1)).color().build()));
ClickEvent prevPageClick = new ClickEvent(ClickEvent.Action.RUN_COMMAND, fullCommand);
componentBuilder.append(previousPage, ComponentBuilder.FormatRetention.NONE).color(interactColor).
event(prevPagePreview).event(prevPageClick);
@@ -156,11 +150,11 @@ public abstract class BookIndex {
*/
protected static void displayNextButton(@NotNull ComponentBuilder componentBuilder,
@NotNull String command, int page, int totalPages) {
String nextPage = color(Formatting.NEUTRAL_BOOK_LIST_NEXT_PAGE);
String nextPage = new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_NEXT_PAGE).color().build();
if (page < totalPages) {
String fullCommand = "/" + command + " page" + (page + 1);
HoverEvent nextPagePreview = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(
color(Formatting.NEUTRAL_BOOK_LIST_TO_PAGE, "{page}", String.valueOf(page + 1))));
new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_TO_PAGE).replace("{page}", String.valueOf(page + 1)).color().build()));
ClickEvent nextPageClick = new ClickEvent(ClickEvent.Action.RUN_COMMAND, fullCommand);
componentBuilder.append(nextPage, ComponentBuilder.FormatRetention.NONE).color(interactColor)
.event(nextPagePreview).event(nextPageClick);
@@ -169,60 +163,4 @@ public abstract class BookIndex {
}
}
/**
* Colors a translatable message
*
* @param translatableMessage <p>The message to color</p>
* @return <p>The colored message</p>
*/
@NotNull
protected static String color(@NotNull TranslatableMessage translatableMessage) {
return color(translatableMessage, (List<String>) null, null);
}
/**
* Colors a translatable message
*
* @param translatableMessage <p>The message to color</p>
* @param placeholder <p>Placeholder to replace</p>
* @param replacement <p>Replacement value</p>
* @return <p>The colored message</p>
*/
@NotNull
protected static String color(@NotNull TranslatableMessage translatableMessage, @NotNull String placeholder,
@NotNull String replacement) {
return color(translatableMessage, List.of(placeholder), List.of(replacement));
}
/**
* Colors a translatable message
*
* @param translatableMessage <p>The message to color</p>
* @param placeholders <p>Placeholders to replace</p>
* @param replacements <p>Replacement values</p>
* @return <p>The colored message</p>
*/
@NotNull
protected static String color(@NotNull TranslatableMessage translatableMessage, @Nullable List<String> placeholders,
@Nullable List<String> replacements) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
if (placeholders == null || replacements == null) {
return stringFormatter.getUnFormattedColoredMessage(translatableMessage);
} else {
return ColorHelper.translateColorCodes(stringFormatter.replacePlaceholders(translatableMessage,
placeholders, replacements), ColorConversion.RGB);
}
}
/**
* Colors a message
*
* @param input <p>The message to color</p>
* @return <p>The colored message</p>
*/
@NotNull
protected static String color(@NotNull String input) {
return ColorHelper.translateColorCodes(input, ColorConversion.RGB);
}
}

View File

@@ -4,6 +4,7 @@ import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.translation.Formatting;
import net.knarcraft.bookswithoutborders.utility.BookFileHelper;
import net.knarcraft.bookswithoutborders.utility.BookFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.knarcraft.knarlib.formatting.TranslatableMessage;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent;
@@ -45,7 +46,7 @@ public class PagedBookIndex extends BookIndex {
int totalPages = (int) Math.ceil((double) availableBooks.size() / booksPerPage);
if (page > totalPages) {
BooksWithoutBorders.getStringFormatter().displayErrorMessage(sender, Formatting.NEUTRAL_AUTHOR_BOOKS_INVALID_PAGE);
new FormatBuilder(Formatting.NEUTRAL_AUTHOR_BOOKS_INVALID_PAGE).error(sender);
} else {
showBookMenu(sender, command, page, totalPages, availableBooks, firstInstances, listPublic);
}
@@ -68,7 +69,7 @@ public class PagedBookIndex extends BookIndex {
ComponentBuilder componentBuilder = new ComponentBuilder();
TranslatableMessage message = listPublic ? Formatting.NEUTRAL_BOOK_LIST_PUBLIC_BOOKS_HEADER : Formatting.NEUTRAL_BOOK_LIST_PLAYER_BOOKS_HEADER;
componentBuilder.append(color(message));
componentBuilder.append(new FormatBuilder(message).color().build());
displayBookList(componentBuilder, command, page, availableBooks);
displayPreviousButton(componentBuilder, command, page);
@@ -93,22 +94,23 @@ public class PagedBookIndex extends BookIndex {
@NotNull List<String> availableBooks) {
int startIndex = (page - 1) * booksPerPage;
for (int bookIndex = startIndex; bookIndex < Math.min(startIndex + booksPerPage, availableBooks.size()); bookIndex++) {
String title = color(BookFileHelper.getBookTitleFromPath(availableBooks.get(bookIndex)));
String author = color(BookFileHelper.getBookAuthorFromPath(availableBooks.get(bookIndex)));
String title = new FormatBuilder(BookFileHelper.getBookTitleFromPath(availableBooks.get(bookIndex))).color().build();
String author = new FormatBuilder(BookFileHelper.getBookAuthorFromPath(availableBooks.get(bookIndex))).color().build();
ClickEvent indexClick = new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + command + " " + (bookIndex + 1));
HoverEvent indexHover = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(color(Formatting.NEUTRAL_BOOK_LIST_BOOK_INDEX_HOVER)));
HoverEvent indexHover = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_BOOK_INDEX_HOVER).color().build()));
ClickEvent pathClick = new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + command + " " + availableBooks.get(bookIndex));
HoverEvent pathHover = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(color(Formatting.NEUTRAL_BOOK_LIST_PATH_HOVER)));
HoverEvent pathHover = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_PATH_HOVER).color().build()));
ClickEvent authorClick = new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/" + command + " author" + BookFormatter.stripColor(author) + " page1");
HoverEvent authorHover = new HoverEvent(HoverEvent.Action.SHOW_TEXT,
new Text(color(Formatting.NEUTRAL_BOOK_LIST_AUTHOR_HOVER, "{author}", BookFormatter.stripColor(author))));
new Text(new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_AUTHOR_HOVER).replace("{author}", BookFormatter.stripColor(author)).color().build()));
componentBuilder.append(color(Formatting.NEUTRAL_BOOK_LIST_BOOK_INDEX_NUMBER, "{index}",
String.valueOf(bookIndex + 1))).color(interactColor).event(indexClick).event(indexHover);
componentBuilder.append(new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_BOOK_INDEX_NUMBER).replace("{index}",
String.valueOf(bookIndex + 1)).color().build()).color(interactColor).event(indexClick).event(indexHover);
componentBuilder.append(" ", ComponentBuilder.FormatRetention.NONE);
componentBuilder.append(title).color(ChatColor.WHITE).event(pathClick).event(pathHover);
componentBuilder.append(color(Formatting.NEUTRAL_BOOK_LIST_AUTHOR_SEPARATOR), ComponentBuilder.FormatRetention.NONE).color(ChatColor.WHITE);
componentBuilder.append(new FormatBuilder(Formatting.NEUTRAL_BOOK_LIST_AUTHOR_SEPARATOR).color().build(),
ComponentBuilder.FormatRetention.NONE).color(ChatColor.WHITE);
componentBuilder.append(author).color(ChatColor.WHITE).event(authorClick).event(authorHover);
componentBuilder.append("\n");
}

View File

@@ -7,7 +7,7 @@ import net.knarcraft.bookswithoutborders.container.Bookshelf;
import net.knarcraft.bookswithoutborders.handler.BookshelfHandler;
import net.knarcraft.bookswithoutborders.utility.BookHelper;
import net.knarcraft.bookswithoutborders.utility.IntegerToRomanConverter;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
@@ -74,8 +74,7 @@ public class BookshelfListener implements Listener {
event.setUseItemInHand(Event.Result.DENY);
ChiseledBookshelfInventory bookshelfInventory = chiseledBookshelf.getInventory();
BooksWithoutBorders.getStringFormatter().displaySuccessMessage(player,
getBookshelfDescription(bookshelfInventory, event.getClickedBlock().getLocation()));
new FormatBuilder(getBookshelfDescription(bookshelfInventory, event.getClickedBlock().getLocation())).success(player);
}
/**
@@ -87,7 +86,6 @@ public class BookshelfListener implements Listener {
*/
@NotNull
private String getBookshelfDescription(@NotNull ChiseledBookshelfInventory bookshelfInventory, @NotNull Location location) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
StringBuilder builder = new StringBuilder();
Bookshelf bookshelf = BooksWithoutBorders.getBookshelfHandler().getFromLocation(location);
@@ -96,13 +94,13 @@ public class BookshelfListener implements Listener {
if (bookshelf != null) {
title = bookshelf.getTitle();
for (String loreLine : bookshelf.getLore()) {
lore.append(stringFormatter.replacePlaceholder(Formatting.NEUTRAL_BOOKSHELF_HEADER_LORE, "{lore}", loreLine));
lore.append(new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_HEADER_LORE).replace("{lore}", loreLine).build());
}
} else {
title = stringFormatter.getUnFormattedColoredMessage(Formatting.NEUTRAL_BOOKSHELF_HEADER_TITLE_EMPTY);
title = new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_HEADER_TITLE_EMPTY).build();
}
builder.append(stringFormatter.replacePlaceholders(Formatting.NEUTRAL_BOOKSHELF_HEADER_TITLE,
List.of("{name}", "{lore}"), List.of(title, lore.toString())));
builder.append(new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_HEADER_TITLE).replace("{name}", title).
replace("{lore}", lore.toString()).build());
for (int i = 0; i < bookshelfInventory.getSize(); i++) {
appendBookshelfItem(i, builder, bookshelfInventory);
@@ -119,21 +117,19 @@ public class BookshelfListener implements Listener {
*/
private void appendBookshelfItem(int counter, @NotNull StringBuilder builder,
@NotNull ChiseledBookshelfInventory bookshelfInventory) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
// Show the row header before the first item, and before the fourth item
int index = (counter % 3) + 1;
if (counter == 0) {
builder.append(stringFormatter.getUnFormattedColoredMessage(Formatting.NEUTRAL_BOOKSHELF_HEADER_TOP));
builder.append(new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_HEADER_TOP).build());
} else if (counter == 3) {
builder.append(stringFormatter.getUnFormattedColoredMessage(Formatting.NEUTRAL_BOOKSHELF_HEADER_BOTTOM));
builder.append(new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_HEADER_BOTTOM).build());
}
builder.append(stringFormatter.replacePlaceholder(Formatting.NEUTRAL_BOOKSHELF_ENTRY_INDEX, "{index}", String.valueOf(index)));
builder.append(new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_ENTRY_INDEX).replace("{index}", String.valueOf(index)).build());
ItemStack itemStack = bookshelfInventory.getItem(counter);
if (itemStack == null) {
builder.append(stringFormatter.getUnFormattedColoredMessage(Formatting.NEUTRAL_BOOKSHELF_EMPTY));
builder.append(new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_EMPTY).build());
return;
}
ItemMeta meta = itemStack.getItemMeta();
@@ -143,8 +139,7 @@ public class BookshelfListener implements Listener {
} else if (meta instanceof EnchantmentStorageMeta enchantmentStorageMeta) {
builder.append(getEnchantedBookDescription(enchantmentStorageMeta));
} else if (meta != null) {
builder.append(stringFormatter.getUnFormattedColoredMessage(
Formatting.NEUTRAL_BOOKSHELF_PLAIN_BOOK_PREFIX)).append(getPlainBookDescription(meta));
builder.append(new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_PLAIN_BOOK_PREFIX).build()).append(getPlainBookDescription(meta));
}
}
@@ -158,8 +153,7 @@ public class BookshelfListener implements Listener {
private String getPlainBookDescription(@NotNull ItemMeta itemMeta) {
String name = itemMeta.getDisplayName();
if (name.isEmpty()) {
name = BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(
Formatting.NEUTRAL_BOOKSHELF_UNNAMED_PLAIN_BOOK_FORMAT);
name = new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_UNNAMED_PLAIN_BOOK_FORMAT).build();
}
return name;
}
@@ -174,8 +168,8 @@ public class BookshelfListener implements Listener {
private String getBookDescription(@NotNull BookMeta bookMeta) {
String title = BookHelper.getBookTitle(bookMeta);
String author = BookHelper.getBookAuthor(bookMeta, null);
return BooksWithoutBorders.getStringFormatter().replacePlaceholders(Formatting.NEUTRAL_BOOKSHELF_WRITTEN_FORMAT,
List.of("{title}", "{author}"), List.of(title, author));
return new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_WRITTEN_FORMAT).replace("{title}", title).
replace("{author}", author).build();
}
/**
@@ -187,8 +181,7 @@ public class BookshelfListener implements Listener {
@NotNull
private String getEnchantedBookDescription(@NotNull EnchantmentStorageMeta enchantmentStorageMeta) {
StringBuilder builder = new StringBuilder();
builder.append(BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(
Formatting.NEUTRAL_BOOKSHELF_ENCHANTED_PREFIX));
builder.append(new FormatBuilder(Formatting.NEUTRAL_BOOKSHELF_ENCHANTED_PREFIX).build());
Map<Enchantment, Integer> enchantmentMap = enchantmentStorageMeta.getStoredEnchants();
List<String> enchantments = new ArrayList<>(enchantmentMap.size());
for (Map.Entry<Enchantment, Integer> enchantmentEntry : enchantmentMap.entrySet()) {

View File

@@ -8,7 +8,7 @@ import net.knarcraft.bookswithoutborders.state.BookDirectory;
import net.knarcraft.bookswithoutborders.utility.BookFileHelper;
import net.knarcraft.bookswithoutborders.utility.BookLoader;
import net.knarcraft.bookswithoutborders.utility.InputCleaningHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@@ -48,7 +48,6 @@ public class GroupDecryptListener implements Listener {
if (oldBook == null) {
return;
}
decryptBook(oldBook, player, heldItem, hand);
}
}
@@ -63,7 +62,6 @@ public class GroupDecryptListener implements Listener {
*/
private void decryptBook(@NotNull BookMeta oldBook, @NotNull Player player, @NotNull ItemStack heldItem,
@NotNull EquipmentSlot hand) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
BwBConfig config = BooksWithoutBorders.getConfiguration();
ItemStack newBook;
@@ -78,7 +76,7 @@ public class GroupDecryptListener implements Listener {
//Permission check
if (!player.hasPermission(Permission.DECRYPT + "." + groupName) &&
!(config.getAdminDecrypt() && player.hasPermission(Permission.ADMIN.toString()))) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_GROUP_DECRYPT_NO_PERMISSION);
new FormatBuilder(Translatable.ERROR_GROUP_DECRYPT_NO_PERMISSION).error(player);
return;
}
@@ -92,7 +90,7 @@ public class GroupDecryptListener implements Listener {
if (file == null) {
file = BookFileHelper.findBookFile(config.getBookFolder(), oldBook);
if (file == null) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_GROUP_DECRYPT_NOT_FOUND);
new FormatBuilder(Translatable.ERROR_GROUP_DECRYPT_NOT_FOUND).error(player);
return;
}
}
@@ -102,13 +100,13 @@ public class GroupDecryptListener implements Listener {
heldItem.getAmount());
if (newBook == null) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_GROUP_DECRYPT_LOAD_FAILED);
new FormatBuilder(Translatable.ERROR_GROUP_DECRYPT_LOAD_FAILED).error(player);
return;
}
player.getInventory().setItem(hand, newBook);
player.closeInventory();
stringFormatter.displaySuccessMessage(player, Translatable.SUCCESS_AUTO_DECRYPTED);
new FormatBuilder(Translatable.SUCCESS_AUTO_DECRYPTED).success(player);
}
}

View File

@@ -5,7 +5,7 @@ import net.knarcraft.bookswithoutborders.config.BwBConfig;
import net.knarcraft.bookswithoutborders.config.StaticMessage;
import net.knarcraft.bookswithoutborders.utility.BookLoader;
import net.knarcraft.bookswithoutborders.utility.InputCleaningHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@@ -31,11 +31,10 @@ public class PlayerEventListener implements Listener {
//If a book directory exists with this player's name, move it to this player's UUID
String bookFolder = config.getBookFolder();
File file = new File(bookFolder, InputCleaningHelper.cleanString(player.getName()));
if (file.exists()) {
if (!file.renameTo(new File(bookFolder, player.getUniqueId().toString()))) {
BooksWithoutBorders.log(Level.WARNING, StringFormatter.replacePlaceholder(
StaticMessage.WARNING_USER_BOOK_MIGRATION_IMPOSSIBLE.toString(), "{player}", player.getName()));
}
if (file.exists() && !file.renameTo(new File(bookFolder, player.getUniqueId().toString()))) {
BooksWithoutBorders.log(Level.WARNING, new FormatBuilder(
StaticMessage.WARNING_USER_BOOK_MIGRATION_IMPOSSIBLE.toString()).
replace("{player}", player.getName()).build());
}
//Handle new players

View File

@@ -10,7 +10,7 @@ import net.knarcraft.bookswithoutborders.utility.BookFileHelper;
import net.knarcraft.bookswithoutborders.utility.BookFormatter;
import net.knarcraft.bookswithoutborders.utility.BookLoader;
import net.knarcraft.bookswithoutborders.utility.EncryptionHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Material;
import org.bukkit.Tag;
@@ -30,8 +30,6 @@ import org.bukkit.inventory.PlayerInventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import static net.knarcraft.bookswithoutborders.utility.BookFileHelper.isBookListIndex;
/**
@@ -48,8 +46,6 @@ public class SignEventListener implements Listener {
String[] lines = event.getLines();
Player player = event.getPlayer();
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
//Check if creating a Books Without Borders Sign and if the player has permission
if (SignType.fromString(lines[0]) != SignType.BOOKS_WITHOUT_BORDERS ||
!player.hasPermission(Permission.SIGNS.toString())) {
@@ -57,19 +53,19 @@ public class SignEventListener implements Listener {
}
//Mark the sign as active
event.setLine(0, stringFormatter.getUnFormattedColoredMessage(SignText.SIGN_HEADER));
event.setLine(0, new FormatBuilder(SignText.SIGN_HEADER).color().build());
//Check if the sign is of a valid type
SignType type = SignType.fromString(lines[1]);
if (type == null || lines[2].trim().isEmpty()) {
//Mark the second line as invalid
event.setLine(1, stringFormatter.replacePlaceholder(SignText.SIGN_INVALID, "{line}", lines[1]));
stringFormatter.displayErrorMessage(player, SignText.ERROR_SIGN_INVALID);
event.setLine(1, new FormatBuilder(SignText.SIGN_INVALID).replace("{line}", lines[1]).color().build());
new FormatBuilder(SignText.ERROR_SIGN_INVALID).error(player);
return;
}
//Mark the second line as valid
event.setLine(1, stringFormatter.replacePlaceholder(SignText.SIGN_VALID, "{line}", lines[1]));
event.setLine(1, new FormatBuilder(SignText.SIGN_VALID).replace("{line}", lines[1]).color().build());
lines = event.getLines();
//Mark valid encryption/decryption sign
@@ -77,14 +73,13 @@ public class SignEventListener implements Listener {
//Generate book giving sign
generateGiveSign(event, lines, player);
} else {
event.setLine(2, stringFormatter.replacePlaceholder(SignText.SIGN_PASSWORD, "{password}", lines[2]));
event.setLine(3, stringFormatter.replacePlaceholder(SignText.SIGN_VALID, "{line}", lines[3]));
event.setLine(2, new FormatBuilder(SignText.SIGN_PASSWORD).replace("{password}", lines[2]).color().build());
event.setLine(3, new FormatBuilder(SignText.SIGN_VALID).replace("{line}", lines[3]).color().build());
}
}
@EventHandler
public void onClick(@NotNull PlayerInteractEvent event) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
Player player = event.getPlayer();
PlayerInventory playerInventory = player.getInventory();
EquipmentSlot hand = event.getHand();
@@ -118,8 +113,8 @@ public class SignEventListener implements Listener {
giveBook(sign, player);
} else {
SignSide front = sign.getSide(Side.FRONT);
stringFormatter.displayErrorMessage(player, stringFormatter.replacePlaceholders(SignText.ERROR_SIGN_COMMAND_INVALID,
List.of("{action}", "{data}"), List.of(front.getLine(1), front.getLine(2))));
new FormatBuilder(SignText.ERROR_SIGN_COMMAND_INVALID).replace("{action}", front.getLine(1)).
replace("{data}", front.getLine(2)).error(player);
player.sendMessage(String.valueOf(getSignLine2Color(sign)));
}
}
@@ -259,12 +254,11 @@ public class SignEventListener implements Listener {
ItemStack newBook = BookLoader.loadBook(player, fileName, true, "public");
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
if (newBook != null) {
player.getInventory().addItem(newBook);
stringFormatter.displaySuccessMessage(player, SignText.SUCCESS_SIGN_GIVE);
new FormatBuilder(SignText.SUCCESS_SIGN_GIVE).success(player);
} else {
stringFormatter.displayErrorMessage(player, GiveMessage.ERROR_GIVE_LOAD_FAILED);
new FormatBuilder(GiveMessage.ERROR_GIVE_LOAD_FAILED).error(player);
}
}

View File

@@ -3,7 +3,7 @@ package net.knarcraft.bookswithoutborders.manager;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BwBConfig;
import net.knarcraft.bookswithoutborders.config.translation.CostMessage;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Material;
import org.bukkit.Server;
@@ -65,7 +65,6 @@ public class EconomyManager {
*/
public boolean cannotPayForBookPrinting(@NotNull Player player, int numCopies) {
BwBConfig config = BooksWithoutBorders.getConfiguration();
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
//BookPriceQuantity: How many items are required to pay for each book
//BookPriceType: Which item is used to pay for the books. AIR = use economy
Material bookCurrency = config.getBookPriceType();
@@ -84,9 +83,8 @@ public class EconomyManager {
payForBookPrintingItem(player, itemCost);
return false;
} else {
stringFormatter.displayErrorMessage(player, stringFormatter.replacePlaceholders(
CostMessage.ERROR_COST_INSUFFICIENT_AMOUNT, List.of("{cost}", "{currency}"),
List.of(String.valueOf(itemCost), bookCurrency.toString())));
new FormatBuilder(CostMessage.ERROR_COST_INSUFFICIENT_AMOUNT).replace("{cost}",
String.valueOf(itemCost)).replace("{currency}", bookCurrency.toString()).error(player);
return true;
}
}
@@ -99,11 +97,10 @@ public class EconomyManager {
* @return <p>True if the payment was successful</p>
*/
private boolean takeWritableBookPayment(@NotNull Player player, int itemCost) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
List<ItemStack> books = getPlayersEmptyBooks(player);
if (countItems(books) < itemCost) {
stringFormatter.displayErrorMessage(player, stringFormatter.replacePlaceholder(
CostMessage.ERROR_COST_INSUFFICIENT_WRITABLE_BOOK, "{cost}", String.valueOf(itemCost)));
new FormatBuilder(CostMessage.ERROR_COST_INSUFFICIENT_WRITABLE_BOOK).
replace("{cost}", String.valueOf(itemCost)).error(player);
return false;
} else {
int clearedAmount = 0;
@@ -169,20 +166,19 @@ public class EconomyManager {
* @return <p>True if the player had the money and it has been withdrawn</p>
*/
private boolean payForBookPrintingEconomy(@NotNull Player player, double cost, int numCopies) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
if (economy == null) {
stringFormatter.displayErrorMessage(player, CostMessage.ERROR_VAULT_COST_BUT_UNAVAILABLE);
new FormatBuilder(CostMessage.ERROR_VAULT_COST_BUT_UNAVAILABLE).error(player);
return false;
}
if ((economy.getBalance(player) - cost) >= 0) {
economy.withdrawPlayer(player, cost);
stringFormatter.displaySuccessMessage(player, stringFormatter.replacePlaceholders(
CostMessage.SUCCESS_COST_PAID, List.of("{cost}", "{copies}", "{balance}"),
List.of(economy.format(cost), String.valueOf(numCopies), economy.format(economy.getBalance(player)))));
new FormatBuilder(CostMessage.SUCCESS_COST_PAID).replace("{cost}", economy.format(cost)).
replace("{copies}", String.valueOf(numCopies)).
replace("{balance}", economy.format(economy.getBalance(player))).success(player);
return true;
} else {
stringFormatter.replacePlaceholder(CostMessage.ERROR_COST_INSUFFICIENT_ECONOMY, "{cost}", economy.format(cost));
new FormatBuilder(CostMessage.ERROR_COST_INSUFFICIENT_ECONOMY).replace("{cost}", economy.format(cost)).error(player);
return false;
}
}

View File

@@ -1,8 +1,8 @@
package net.knarcraft.bookswithoutborders.state;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.translation.SignText;
import net.knarcraft.bookswithoutborders.utility.BookFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -68,8 +68,7 @@ public enum SignType {
*/
@NotNull
private static String getText(@NotNull SignText signText) {
return BookFormatter.stripColor(
BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(signText));
return BookFormatter.stripColor(new FormatBuilder(signText).build());
}
}

View File

@@ -8,7 +8,7 @@ import net.knarcraft.bookswithoutborders.utility.BookFileHelper;
import net.knarcraft.bookswithoutborders.utility.BookHelper;
import net.knarcraft.bookswithoutborders.utility.BookToFromTextHelper;
import net.knarcraft.bookswithoutborders.utility.EncryptionHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
@@ -18,7 +18,6 @@ import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
@@ -68,12 +67,11 @@ public class MigrationQueueThread implements Runnable {
success = success & migrateFile(migrationRequest.file(), migrationRequest.player());
if (BooksWithoutBorders.getMigrationQueue().peek() == null) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
Player player = migrationRequest.player();
if (success) {
stringFormatter.displaySuccessMessage(player, Translatable.SUCCESS_MIGRATED);
new FormatBuilder(Translatable.SUCCESS_MIGRATED).success(player);
} else {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_MIGRATION_FAILED);
new FormatBuilder(Translatable.ERROR_MIGRATION_FAILED).error(player);
}
BooksWithoutBorders.getInstance().getServer().getScheduler().cancelTask(this.taskId);
success = null;
@@ -149,10 +147,8 @@ public class MigrationQueueThread implements Runnable {
}
return deleteBook(file.getParentFile(), newName, file);
} catch (IllegalArgumentException | IOException exception) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
stringFormatter.displayErrorMessage(player, stringFormatter.replacePlaceholders(
Translatable.ERROR_MIGRATION_BOOK_FAILED, List.of("{file}", "{exception}"),
List.of(file.getName(), exception.getMessage())));
new FormatBuilder(Translatable.ERROR_MIGRATION_BOOK_FAILED).replace("{file}", file.getName()).
replace("{exception}", exception.getMessage()).error(player);
return false;
}
}

View File

@@ -4,6 +4,7 @@ import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.translation.Formatting;
import net.knarcraft.bookswithoutborders.config.translation.Translatable;
import net.knarcraft.bookswithoutborders.state.BookDirectory;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -142,7 +143,7 @@ public final class BookFileHelper {
File[] existingFiles = searchDirectory.listFiles();
if (!searchDirectory.exists() || existingFiles == null || existingFiles.length == 0) {
BooksWithoutBorders.getStringFormatter().displayErrorMessage(sender, Translatable.ERROR_NO_BOOKS_TO_LIST);
new FormatBuilder(Translatable.ERROR_NO_BOOKS_TO_LIST).error(sender);
return null;
}
@@ -221,7 +222,7 @@ public final class BookFileHelper {
} else if (stripped.contains(",")) {
return stripped.split(",")[1];
} else {
return BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(Formatting.NEUTRAL_UNKNOWN_AUTHOR);
return new FormatBuilder(Formatting.NEUTRAL_UNKNOWN_AUTHOR).color().build();
}
}

View File

@@ -2,9 +2,11 @@ package net.knarcraft.bookswithoutborders.utility;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BwBConfig;
import net.knarcraft.bookswithoutborders.config.StaticMessage;
import net.knarcraft.bookswithoutborders.config.translation.Formatting;
import net.knarcraft.bookswithoutborders.config.translation.Translatable;
import net.knarcraft.bookswithoutborders.state.BookDirectory;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
@@ -42,7 +44,7 @@ public final class BookHelper {
public static ItemStack unsignBook(@NotNull BookMeta oldMetadata, int amount) {
WritableBookMeta newMetadata = (BookMeta) BooksWithoutBorders.getItemFactory().getItemMeta(Material.WRITABLE_BOOK);
if (newMetadata == null) {
BooksWithoutBorders.log(Level.SEVERE, "Unable to create writable book metadata");
BooksWithoutBorders.log(Level.SEVERE, StaticMessage.EXCEPTION_BOOK_METADATA_CREATION_FAILED.toString());
return null;
}
@@ -194,7 +196,7 @@ public final class BookHelper {
} else {
authorName = book.getAuthor();
if (authorName == null) {
authorName = BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(Formatting.NEUTRAL_UNKNOWN_AUTHOR);
authorName = new FormatBuilder(Formatting.NEUTRAL_UNKNOWN_AUTHOR).color().build();
}
}
return authorName;
@@ -212,7 +214,7 @@ public final class BookHelper {
bookName = book.getTitle();
}
if (bookName == null) {
bookName = BooksWithoutBorders.getStringFormatter().getUnFormattedColoredMessage(Formatting.NEUTRAL_UNKNOWN_TITLE);
bookName = new FormatBuilder(Formatting.NEUTRAL_UNKNOWN_TITLE).color().build();
}
return bookName;
}
@@ -228,7 +230,7 @@ public final class BookHelper {
if (isAuthor(player.getName(), book.getAuthor())) {
return false;
} else {
BooksWithoutBorders.getStringFormatter().displayErrorMessage(player, Translatable.ERROR_AUTHOR_ONLY);
new FormatBuilder(Translatable.ERROR_AUTHOR_ONLY).error(player);
return true;
}
}

View File

@@ -5,7 +5,7 @@ import net.knarcraft.bookswithoutborders.config.BwBConfig;
import net.knarcraft.bookswithoutborders.config.Permission;
import net.knarcraft.bookswithoutborders.config.translation.Translatable;
import net.knarcraft.bookswithoutborders.state.BookDirectory;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -57,8 +57,7 @@ public final class BookLoader {
@NotNull String directory, int numCopies) {
BookDirectory bookDirectory = BookDirectory.getFromString(directory);
if (bookDirectory == null) {
BooksWithoutBorders.getStringFormatter().displayErrorMessage(sender,
Translatable.ERROR_BOOK_DIRECTORY_UNKNOWN);
new FormatBuilder(Translatable.ERROR_BOOK_DIRECTORY_UNKNOWN).error(sender);
return null;
}
return loadBook(sender, fileName, isSigned, bookDirectory, directory, numCopies);
@@ -78,7 +77,6 @@ public final class BookLoader {
@Nullable
public static ItemStack loadBook(@NotNull CommandSender sender, @NotNull String fileName, boolean isSigned,
@NotNull BookDirectory bookDirectory, @NotNull String directory, int numCopies) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
//Find the filename if a book index is given
try {
int bookIndex = Integer.parseInt(fileName);
@@ -99,8 +97,7 @@ public final class BookLoader {
String replaced = BookFileHelper.replaceAuthorWithUUID(fileName);
file = getFullPath(sender, replaced, bookDirectory, directory);
if (file == null) {
stringFormatter.displayErrorMessage(sender,
Translatable.ERROR_INCORRECT_FILE_NAME);
new FormatBuilder(Translatable.ERROR_INCORRECT_FILE_NAME).error(sender);
return null;
}
}
@@ -118,15 +115,14 @@ public final class BookLoader {
BookMeta bookMetadata = (BookMeta) BooksWithoutBorders.getItemFactory().getItemMeta(Material.WRITTEN_BOOK);
if (bookMetadata == null) {
stringFormatter.displayErrorMessage(sender,
Translatable.ERROR_METADATA_CREATION_FAILED);
new FormatBuilder(Translatable.ERROR_METADATA_CREATION_FAILED).error(sender);
return null;
}
//Load the book from the given file
bookMetadata = BookToFromTextHelper.bookFromFile(file, bookMetadata);
if (bookMetadata == null) {
stringFormatter.displayErrorMessage(sender, Translatable.ERROR_LOAD_BOOK_EMPTY);
new FormatBuilder(Translatable.ERROR_LOAD_BOOK_EMPTY).error(sender);
return null;
}

View File

@@ -6,7 +6,7 @@ import net.knarcraft.bookswithoutborders.config.translation.Formatting;
import net.knarcraft.bookswithoutborders.container.EncryptedBook;
import net.knarcraft.bookswithoutborders.encryption.AESConfiguration;
import net.knarcraft.bookswithoutborders.encryption.EncryptionStyle;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.knarcraft.knarlib.util.FileHelper;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
@@ -81,7 +81,7 @@ public final class BookToFromTextHelper {
}
if (encryptedBook.encryptionStyle() == EncryptionStyle.AES) {
if (encryptedBook.aesConfiguration() == null) {
throw new IOException("Attempted to save AES encrypted book without supplying a configuration!");
throw new IOException(StaticMessage.EXCEPTION_AES_NO_CONFIGURATION.toString());
}
bookYml.set("Encryption.AES.IV", EncryptionHelper.bytesToHex(encryptedBook.aesConfiguration().iv()));
bookYml.set("Encryption.AES.Salt", EncryptionHelper.bytesToHex(encryptedBook.aesConfiguration().salt()));
@@ -94,7 +94,7 @@ public final class BookToFromTextHelper {
List<String> encryptedPages = EncryptionHelper.encryptDecryptBookPages(encryptedBook.bookMeta(),
encryptedBook.encryptionStyle(), encryptedBook.aesConfiguration(), encryptedBook.encryptionKey(), true);
if (encryptedPages == null || encryptedPages.isEmpty()) {
throw new IOException("Book encryption failed!");
throw new IOException(StaticMessage.EXCEPTION_ENCRYPTED_LOAD_FAILED.toString());
}
bookYml.set("Encryption.Data", encryptedPages);
}
@@ -231,8 +231,6 @@ public final class BookToFromTextHelper {
*/
@Nullable
private static BookMeta bookFromYml(@NotNull File file, @NotNull BookMeta bookMetadata, boolean isEncrypted) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
FileConfiguration bookYml = YamlConfiguration.loadConfiguration(file);
// Don't allow encrypted books to be loaded unless known to be encrypted
@@ -249,10 +247,8 @@ public final class BookToFromTextHelper {
return null;
}
bookMetadata.setTitle(bookYml.getString("Title",
stringFormatter.getUnFormattedColoredMessage(Formatting.NEUTRAL_UNKNOWN_TITLE)));
bookMetadata.setAuthor(authorFromUUID(bookYml.getString("Author",
stringFormatter.getUnFormattedColoredMessage(Formatting.NEUTRAL_UNKNOWN_AUTHOR))));
bookMetadata.setTitle(bookYml.getString("Title", new FormatBuilder(Formatting.NEUTRAL_UNKNOWN_TITLE).build()));
bookMetadata.setAuthor(authorFromUUID(bookYml.getString("Author", new FormatBuilder(Formatting.NEUTRAL_UNKNOWN_AUTHOR).build())));
bookMetadata.setPages(bookYml.getStringList("Pages"));
bookMetadata.setLore(bookYml.getStringList("Lore"));
bookMetadata.setDisplayName(bookYml.getString("DisplayName"));

View File

@@ -13,7 +13,7 @@ import net.knarcraft.bookswithoutborders.encryption.GenenCrypt;
import net.knarcraft.bookswithoutborders.encryption.Magic;
import net.knarcraft.bookswithoutborders.encryption.OneTimePad;
import net.knarcraft.bookswithoutborders.encryption.SubstitutionCipher;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
@@ -31,7 +31,6 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.cleanString;
@@ -155,15 +154,14 @@ public final class EncryptionHelper {
public static ItemStack encryptBook(Player player, boolean mainHand, @NotNull String key,
@NotNull EncryptionStyle style, @NotNull String groupName,
boolean preventAdminDecrypt) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
BookMeta book = InventoryHelper.getHeldBookMetadata(player, mainHand);
if (book == null) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_METADATA_MISSING);
new FormatBuilder(Translatable.ERROR_METADATA_MISSING).error(player);
return null;
}
if (!book.hasPages()) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_ENCRYPT_BOOK_EMPTY);
new FormatBuilder(Translatable.ERROR_ENCRYPT_BOOK_EMPTY).error(player);
return null;
}
@@ -191,7 +189,7 @@ public final class EncryptionHelper {
ItemStack encryptedBook = createEncryptedBook(book, newPages, player, newMetadata);
stringFormatter.displaySuccessMessage(player, Translatable.SUCCESS_ENCRYPTED);
new FormatBuilder(Translatable.SUCCESS_ENCRYPTED).success(player);
return encryptedBook;
}
@@ -258,7 +256,6 @@ public final class EncryptionHelper {
@Nullable
public static ItemStack loadEncryptedBook(@NotNull Player player, @NotNull String key, boolean deleteEncryptedFile,
boolean forceDecrypt) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
ItemStack heldBook = InventoryHelper.getHeldBook(player, true);
BookMeta bookMetadata = (BookMeta) heldBook.getItemMeta();
String path = BooksWithoutBorders.getConfiguration().getEncryptedBookPath();
@@ -273,7 +270,7 @@ public final class EncryptionHelper {
File file = new File(path + fileName + ".yml");
if (!file.isFile()) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_DECRYPT_NOT_FOUND);
new FormatBuilder(Translatable.ERROR_DECRYPT_NOT_FOUND).error(player);
return null;
} else {
try {
@@ -284,7 +281,7 @@ public final class EncryptionHelper {
bookMetadata = book.bookMeta();
}
} catch (Exception exception) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_DECRYPT_FAILED);
new FormatBuilder(Translatable.ERROR_DECRYPT_FAILED).error(player);
return null;
}
}
@@ -309,8 +306,7 @@ public final class EncryptionHelper {
*/
@Nullable
public static ItemStack loadEncryptedBookLegacy(@NotNull Player player, @NotNull String key, boolean deleteEncryptedFile) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
stringFormatter.displayNeutralMessage(player, Translatable.NEUTRAL_ATTEMPTING_LEGACY_DECRYPTION);
new FormatBuilder(Translatable.NEUTRAL_ATTEMPTING_LEGACY_DECRYPTION).neutral(player);
ItemStack heldBook = InventoryHelper.getHeldBook(player, true);
BookMeta bookMetadata = (BookMeta) heldBook.getItemMeta();
String path = BooksWithoutBorders.getConfiguration().getEncryptedBookPath();
@@ -331,7 +327,7 @@ public final class EncryptionHelper {
if (!file.isFile()) {
file = new File(path + fileName + ".txt");
if (!file.isFile()) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_DECRYPT_LEGACY_INVALID_KEY);
new FormatBuilder(Translatable.ERROR_DECRYPT_LEGACY_INVALID_KEY).error(player);
return null;
}
}
@@ -339,11 +335,11 @@ public final class EncryptionHelper {
try {
bookMetadata = BookToFromTextHelper.bookFromFile(file, bookMetadata);
if (bookMetadata == null) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_DECRYPT_FAILED);
new FormatBuilder(Translatable.ERROR_DECRYPT_FAILED).error(player);
return null;
}
} catch (Exception exception) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_DECRYPT_FAILED);
new FormatBuilder(Translatable.ERROR_DECRYPT_FAILED).error(player);
return null;
}
@@ -411,15 +407,15 @@ public final class EncryptionHelper {
* @param file <p>The file to delete</p>
*/
private static void deleteEncryptedFile(@NotNull File file) {
Logger logger = BooksWithoutBorders.getInstance().getLogger();
String errorMessage = StaticMessage.EXCEPTION_ENCRYPTED_FILE_DELETE_FAILED.toString();
try {
if (!file.delete()) {
logger.log(Level.SEVERE, StringFormatter.replacePlaceholder(errorMessage, "{path}", file.getPath()));
if (file.delete()) {
return;
}
} catch (Exception exception) {
logger.log(Level.SEVERE, StringFormatter.replacePlaceholder(errorMessage, "{path}", file.getPath()));
} catch (Exception ignored) {
}
BooksWithoutBorders.log(Level.SEVERE, new FormatBuilder(
StaticMessage.EXCEPTION_ENCRYPTED_FILE_DELETE_FAILED.toString()).
replace("{path}", file.getPath()).build());
}
/**
@@ -440,11 +436,11 @@ public final class EncryptionHelper {
if (!dirTest.exists()) {
try {
if (!dirTest.mkdir()) {
BooksWithoutBorders.log(Level.SEVERE, "Unable to create encryption group folder!");
BooksWithoutBorders.log(Level.SEVERE, StaticMessage.EXCEPTION_ENCRYPTED_GROUP_FOLDER_CREATION_FAILED.toString());
return null;
}
} catch (Exception exception) {
BooksWithoutBorders.log(Level.SEVERE, "Unable to save group encrypted book");
BooksWithoutBorders.log(Level.SEVERE, StaticMessage.EXCEPTION_GROUP_ENCRYPT_SAVE_FAILED.toString());
return null;
}
}
@@ -467,7 +463,7 @@ public final class EncryptionHelper {
try {
BookToFromTextHelper.bookToYml(path, fileName, bookMetadata);
} catch (IOException exception) {
BooksWithoutBorders.getStringFormatter().displayErrorMessage(player, Translatable.ERROR_GROUP_ENCRYPT_FAILED);
new FormatBuilder(Translatable.ERROR_GROUP_ENCRYPT_FAILED).error(player);
return null;
}
}
@@ -484,7 +480,6 @@ public final class EncryptionHelper {
*/
@NotNull
private static Boolean saveEncryptedBook(@NotNull Player player, @NotNull EncryptedBook encryptedBook) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
String path = BooksWithoutBorders.getConfiguration().getEncryptedBookPath();
String fileName = BookHelper.getBookFile(encryptedBook.bookMeta(), player, true);
@@ -493,14 +488,14 @@ public final class EncryptionHelper {
//cancels saving if file is already encrypted
File file = new File(path, fileName + ".yml");
if (file.isFile()) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_ENCRYPT_ALREADY_SAVED);
new FormatBuilder(Translatable.ERROR_ENCRYPT_ALREADY_SAVED).error(player);
return false;
}
try {
BookToFromTextHelper.encryptedBookToYml(path, fileName, encryptedBook);
} catch (IOException exception) {
stringFormatter.displayErrorMessage(player, Translatable.ERROR_ENCRYPT_FAILED);
new FormatBuilder(Translatable.ERROR_ENCRYPT_FAILED).error(player);
return false;
}
return true;

View File

@@ -1,11 +1,10 @@
package net.knarcraft.bookswithoutborders.utility;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.StaticMessage;
import net.knarcraft.bookswithoutborders.config.translation.Translatable;
import net.knarcraft.bookswithoutborders.state.BookHoldingState;
import net.knarcraft.bookswithoutborders.state.ItemSlot;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@@ -68,7 +67,7 @@ public final class InventoryHelper {
} else if (itemSlot == ItemSlot.OFF_HAND) {
replaceHeldItem(player, newBook, false);
} else {
BooksWithoutBorders.getStringFormatter().displayErrorMessage(player, Translatable.ERROR_BOOK_NOT_FOUND);
new FormatBuilder(Translatable.ERROR_BOOK_NOT_FOUND).error(player);
}
}
@@ -82,17 +81,16 @@ public final class InventoryHelper {
*/
public static boolean notHoldingOneWritableBookCheck(@NotNull Player player, @NotNull String noBookMessage,
@NotNull String twoBooksMessage) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
BookHoldingState holdingState = getBookHoldingState(player);
if (holdingState == BookHoldingState.NONE || holdingState == BookHoldingState.SIGNED_BOTH_HANDS ||
holdingState == BookHoldingState.SIGNED_MAIN_HAND || holdingState == BookHoldingState.SIGNED_OFF_HAND) {
stringFormatter.displayErrorMessage(player, noBookMessage);
new FormatBuilder(noBookMessage).error(player);
return true;
}
if (holdingState == BookHoldingState.UNSIGNED_BOTH_HANDS) {
stringFormatter.displayErrorMessage(player, twoBooksMessage);
new FormatBuilder(twoBooksMessage).error(player);
return true;
}
@@ -109,17 +107,16 @@ public final class InventoryHelper {
*/
public static boolean notHoldingOneWrittenBookCheck(@NotNull Player player, @NotNull String noBookMessage,
@NotNull String twoBooksMessage) {
StringFormatter stringFormatter = BooksWithoutBorders.getStringFormatter();
BookHoldingState holdingState = getBookHoldingState(player);
if (holdingState == BookHoldingState.NONE || holdingState == BookHoldingState.UNSIGNED_BOTH_HANDS ||
holdingState == BookHoldingState.UNSIGNED_MAIN_HAND || holdingState == BookHoldingState.UNSIGNED_OFF_HAND) {
stringFormatter.displayErrorMessage(player, noBookMessage);
new FormatBuilder(noBookMessage).error(player);
return true;
}
if (holdingState == BookHoldingState.SIGNED_BOTH_HANDS) {
stringFormatter.displayErrorMessage(player, twoBooksMessage);
new FormatBuilder(twoBooksMessage).error(player);
return true;
}

View File

@@ -29,6 +29,7 @@ en:
SUCCESS_TITLE_SET: "Title set to {title}!"
SUCCESS_MIGRATED: "Successfully migrated all books"
SUCCESS_ENCRYPTED: "Book encrypted!"
SUCCESS_UNSIGNED: "Book un-signed"
ACTION_COPY: "copy"
ACTION_CLEAR: "clear"
ACTION_DECRYPT: "decrypt"