MODERN_TEXT_PRECOMPILE_LANG = ConfigValue.create("ModernTextFormation.Precompile_Language",
true,
"When enabled, parses (deserializes) language messages to Spigot TextComponent(s) on plugin load.",
diff --git a/src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java b/src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java
index ea724ea..501b470 100644
--- a/src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java
+++ b/src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java
@@ -15,6 +15,7 @@ import su.nightexpress.nightcore.util.Colorizer;
import su.nightexpress.nightcore.util.text.NightMessage;
import static su.nightexpress.nightcore.util.text.tag.Tags.*;
+import static su.nightexpress.nightcore.util.Placeholders.*;
public class CheckPermCommand {
@@ -33,9 +34,13 @@ public class CheckPermCommand {
Player player = arguments.getPlayerArgument(ARG_PLAYER);
String builder =
BOLD.enclose(LIGHT_YELLOW.enclose("Permissions report for ") + LIGHT_ORANGE.enclose(player.getName() + ":")) +
+ TAG_LINE_BREAK +
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("Primary Group: ") + Colorizer.plain(VaultHook.getPermissionGroup(player))) +
+ TAG_LINE_BREAK +
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("All Groups: ") + Colorizer.plain(String.join(", ", VaultHook.getPermissionGroups(player)))) +
+ TAG_LINE_BREAK +
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("Prefix: ") + VaultHook.getPrefix(player)) +
+ TAG_LINE_BREAK +
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("Suffix: ") + VaultHook.getSuffix(player));
NightMessage.create(builder).send(context.getSender());
return true;
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java b/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java
index 570f6b3..c160ed4 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java
@@ -11,6 +11,7 @@ import su.nightexpress.nightcore.database.sql.SQLCondition;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import su.nightexpress.nightcore.database.sql.executor.*;
+import su.nightexpress.nightcore.database.sql.query.UpdateEntity;
import su.nightexpress.nightcore.database.sql.query.UpdateQuery;
import su.nightexpress.nightcore.manager.AbstractManager;
@@ -145,21 +146,27 @@ public abstract class AbstractDataHandler extends Abs
}
@NotNull
- public UpdateQuery updateQuery(@NotNull String table, @NotNull List values, @NotNull List conditions) {
- return UpdateQuery.create(table, values, conditions);
+ public UpdateEntity createUpdateEntity(@NotNull List values, @NotNull List conditions) {
+ return UpdateEntity.create(values, conditions);
}
+// @NotNull
+// public UpdateQuery updateQuery(@NotNull String table, @NotNull List values, @NotNull List conditions) {
+// return UpdateQuery.create(table, values, conditions);
+// }
+//
public void executeUpdate(@NotNull String table, @NotNull List values, @NotNull List conditions) {
- this.executeUpdate(this.updateQuery(table, values, conditions));
+ this.executeUpdate(UpdateQuery.create(table, values, conditions));
}
public void executeUpdate(@NotNull UpdateQuery query) {
SQLQueries.executeUpdate(this.connector, query);
}
- public void executeUpdates(@NotNull List queries) {
- SQLQueries.executeUpdates(this.connector, queries);
- }
+// @Deprecated
+// public void executeUpdates(@NotNull UpdateQuery queries) {
+// SQLQueries.executeUpdates(this.connector, queries);
+// }
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java
index 4de3d34..382d1d6 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java
@@ -10,6 +10,7 @@ import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import su.nightexpress.nightcore.database.sql.column.ColumnType;
import su.nightexpress.nightcore.core.CoreConfig;
+import su.nightexpress.nightcore.database.sql.query.UpdateEntity;
import su.nightexpress.nightcore.database.sql.query.UpdateQuery;
import su.nightexpress.nightcore.util.Lists;
import su.nightexpress.nightcore.util.TimeUtil;
@@ -57,7 +58,7 @@ public abstract class AbstractUserDataHandler, U ex
@Override
public void onSave() {
- this.executeUpdates(this.plugin.getUserManager().getLoaded().stream().map(this::saveQuery).toList());
+ //this.saveUsers(this.plugin.getUserManager().getLoaded());
}
@Override
@@ -81,8 +82,13 @@ public abstract class AbstractUserDataHandler
, U ex
this.createTable(this.tableUsers, columns);
}
+ public boolean isNameIdCacheEnabled() {
+ // TODO NOT WORKING FOR MYSQL DUE TO LOCAL CACHE, OTHER SERVERS THINK THAT PLAYER NOT EXISTS
+ return CoreConfig.USER_CACHE_NAME_AND_UUID.get() && this.getDatabaseType() == DatabaseType.SQLITE;
+ }
+
public void cacheNamesAndIds() {
- if (!CoreConfig.USER_CACHE_NAME_AND_UUID.get()) return;
+ if (!this.isNameIdCacheEnabled()) return;
Function function = resultSet -> {
try {
@@ -137,33 +143,29 @@ public abstract class AbstractUserDataHandler, U ex
}
public boolean isUserExists(@NotNull String name) {
- if (CoreConfig.USER_CACHE_NAME_AND_UUID.get()) {
+ if (this.isNameIdCacheEnabled()) {
return this.existNames.contains(name.toLowerCase());
}
return this.contains(this.tableUsers, Collections.singletonList(COLUMN_USER_NAME), SQLCondition.equal(COLUMN_USER_NAME.asLowerCase().toValue(name.toLowerCase())));
}
public boolean isUserExists(@NotNull UUID uuid) {
- if (CoreConfig.USER_CACHE_NAME_AND_UUID.get()) {
+ if (this.isNameIdCacheEnabled()) {
return this.existIDs.contains(uuid);
}
return this.contains(this.tableUsers, Collections.singletonList(COLUMN_USER_ID), SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)));
}
public void saveUser(@NotNull U user) {
- /*List values = new ArrayList<>();
- values.add(COLUMN_USER_NAME.toValue(user.getName()));
- values.add(COLUMN_USER_DATE_CREATED.toValue(user.getDateCreated()));
- values.add(COLUMN_USER_LAST_ONLINE.toValue(user.getLastOnline()));
- values.addAll(this.getSaveColumns(user));
+ this.executeUpdate(UpdateQuery.create(this.tableUsers, this.createUpdateEntity(user)));
+ }
- this.update(this.tableUsers, values, SQLCondition.equal(COLUMN_USER_ID.toValue(user.getId())));*/
-
- this.executeUpdate(this.saveQuery(user));
+ public void saveUsers(@NotNull Collection users) {
+ this.executeUpdate(UpdateQuery.create(this.tableUsers, users.stream().map(this::createUpdateEntity).toList()));
}
@NotNull
- public UpdateQuery saveQuery(@NotNull U user) {
+ public UpdateEntity createUpdateEntity(@NotNull U user) {
List values = new ArrayList<>();
values.add(COLUMN_USER_NAME.toValue(user.getName()));
values.add(COLUMN_USER_DATE_CREATED.toValue(user.getDateCreated()));
@@ -174,7 +176,7 @@ public abstract class AbstractUserDataHandler, U ex
SQLCondition.equal(COLUMN_USER_ID.toValue(user.getId()))
);
- return this.updateQuery(this.tableUsers, values, conditions);
+ return this.createUpdateEntity(values, conditions);
}
public void addUser(@NotNull U user) {
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java
index 6a82e33..9bae76a 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java
@@ -4,8 +4,6 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightDataPlugin;
-import su.nightexpress.nightcore.database.sql.SQLQueries;
-import su.nightexpress.nightcore.database.sql.query.UpdateQuery;
import su.nightexpress.nightcore.manager.AbstractManager;
import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.database.listener.UserListener;
@@ -33,7 +31,7 @@ public abstract class AbstractUserManager
, U extend
@Override
protected void onLoad() {
this.addListener(new UserListener<>(this.plugin));
- this.addTask(this.plugin.createAsyncTask(this::saveScheduled).setTicksInterval(1));
+ this.addTask(this.plugin.createAsyncTask(this::saveScheduled).setTicksInterval(20L));
}
@Override
@@ -60,13 +58,10 @@ public abstract class AbstractUserManager
, U extend
}
public void saveScheduled() {
- List queries = new ArrayList<>();
- this.scheduledSaves.forEach(user -> queries.add(this.getDataHandler().saveQuery(user)));
- this.scheduledSaves.clear();
- SQLQueries.executeUpdates(this.getDataHandler().getConnector(), queries);
+ if (this.scheduledSaves.isEmpty()) return;
- //this.scheduledSaves.forEach(this::save);
- //this.scheduledSaves.clear();
+ this.getDataHandler().saveUsers(this.scheduledSaves);
+ this.scheduledSaves.clear();
}
@NotNull
@@ -252,6 +247,10 @@ public abstract class AbstractUserManager, U extend
this.scheduledSaves.add(user);
}
+ public boolean isScheduledToSave(@NotNull U user) {
+ return this.scheduledSaves.contains(user);
+ }
+
@Deprecated
public void saveAsync(@NotNull U user) {
this.scheduleSave(user);
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java
index bee0072..e92f459 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java
@@ -2,6 +2,7 @@ package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.AbstractConnector;
+import su.nightexpress.nightcore.database.sql.query.UpdateEntity;
import su.nightexpress.nightcore.database.sql.query.UpdateQuery;
import java.sql.*;
@@ -85,26 +86,60 @@ public class SQLQueries {
}
public static void executeUpdate(@NotNull AbstractConnector connector, @NotNull UpdateQuery query) {
- executeUpdates(connector, List.of(query));
+ executeUpdates(connector, query);
}
- public static void executeUpdates(@NotNull AbstractConnector connector, @NotNull List queries) {
- try (Connection connection = connector.getConnection()) {
- for (UpdateQuery query : queries) {
- try (PreparedStatement statement = connection.prepareStatement(query.getSQL())) {
+ public static void executeUpdates(@NotNull AbstractConnector connector, @NotNull UpdateQuery query) {
+ if (query.isEmpty()) return;
- int count = 1;
- for (String columnValue : query.getValues()) {
- statement.setString(count++, columnValue);
- }
- for (String conditionValue : query.getWheres()) {
- statement.setString(count++, conditionValue);
- }
+ List entities = query.getEntities();
+ //if (entities.isEmpty()) return;
- statement.executeUpdate();
+ //if (queries.isEmpty()) return;
+
+// try (Connection connection = connector.getConnection()) {
+// for (UpdateQuery query : queries) {
+// try (PreparedStatement statement = connection.prepareStatement(query.getSQL())) {
+//
+// int count = 1;
+// for (String columnValue : query.getValues()) {
+// statement.setString(count++, columnValue);
+// }
+// for (String conditionValue : query.getWheres()) {
+// statement.setString(count++, conditionValue);
+// }
+//
+// statement.executeUpdate();
+// }
+// catch (SQLException exception) {
+// exception.printStackTrace();
+// }
+// }
+// }
+// catch (SQLException exception) {
+// exception.printStackTrace();
+// }
+
+ String sql = query.getSQL();//queries.get(0).getSQL();
+
+ try (Connection connection = connector.getConnection();
+ PreparedStatement statement = connection.prepareStatement(sql)) {
+
+ int entityCount = 0;
+ for (UpdateEntity entity : entities) {
+ int paramCount = 1;
+
+ for (String columnValue : entity.getValues()) {
+ statement.setString(paramCount++, columnValue);
}
- catch (SQLException exception) {
- exception.printStackTrace();
+ for (String conditionValue : entity.getWheres()) {
+ statement.setString(paramCount++, conditionValue);
+ }
+ statement.addBatch();
+ entityCount++;
+
+ if (entityCount % 500 == 0 || entityCount == entities.size()) {
+ statement.executeBatch();
}
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java b/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java
index 6ae40de..6f65951 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java
@@ -1,15 +1,23 @@
package su.nightexpress.nightcore.database.sql.query;
import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.database.sql.SQLUtils;
public class AbstractQuery {
- private final String sql;
+ protected final String table;
+ protected final String sql;
- protected AbstractQuery(@NotNull String sql) {
+ protected AbstractQuery(@NotNull String table, @NotNull String sql) {
+ this.table = SQLUtils.escape(table);
this.sql = sql;
}
+ @NotNull
+ public String getTable() {
+ return table;
+ }
+
@NotNull
public String getSQL() {
return sql;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java
new file mode 100644
index 0000000..f9565db
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java
@@ -0,0 +1,83 @@
+package su.nightexpress.nightcore.database.sql.query;
+
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.database.sql.SQLCondition;
+import su.nightexpress.nightcore.database.sql.SQLValue;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class UpdateEntity {
+
+ private final List columnNames;
+ private final List values;
+ private final List whereColumns;
+ private final List wheres;
+
+ private UpdateEntity(@NotNull List columnNames,
+ @NotNull List values,
+ @NotNull List whereColumns,
+ @NotNull List wheres) {
+ this.columnNames = columnNames;
+ this.values = values;
+ this.whereColumns = whereColumns;
+ this.wheres = wheres;
+ }
+
+ @NotNull
+ public static UpdateEntity create(@NotNull List values) {
+ return create(values, Collections.emptyList());
+ }
+
+ @NotNull
+ public static UpdateEntity create(@NotNull List values, @NotNull List conditions) {
+ List columnNames = new ArrayList<>();
+ List columnValues = new ArrayList<>();
+ List whereColumns = new ArrayList<>();
+ List whereValues = new ArrayList<>();
+
+ values.forEach(value -> {
+ columnNames.add(value.getColumn().getNameEscaped() + " = ?");
+ columnValues.add(value.getValue());
+ });
+
+ conditions.forEach(condition -> {
+ whereColumns.add(condition.getColumn().getNameEscaped() + " " + condition.getType().getOperator() + " ?");
+ whereValues.add(condition.getValue().getValue());
+ });
+
+ return new UpdateEntity(columnNames, columnValues, whereColumns, whereValues);
+ }
+
+ @NotNull
+ public String createSQL(@NotNull String table) {
+ StringBuilder builder = new StringBuilder();
+ builder.append("UPDATE ").append(table);
+ builder.append(" SET ").append(String.join(",", this.columnNames));
+ if (!this.whereColumns.isEmpty()) {
+ builder.append(" WHERE ").append(String.join(" AND ", this.whereColumns));
+ }
+ return builder.toString();
+ }
+
+ @NotNull
+ public List getColumnNames() {
+ return columnNames;
+ }
+
+ @NotNull
+ public List getValues() {
+ return values;
+ }
+
+ @NotNull
+ public List getWhereColumns() {
+ return whereColumns;
+ }
+
+ @NotNull
+ public List getWheres() {
+ return wheres;
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java
index efce046..0c51bc6 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java
@@ -6,18 +6,34 @@ import su.nightexpress.nightcore.database.sql.SQLUtils;
import su.nightexpress.nightcore.database.sql.SQLValue;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Collections;
import java.util.List;
-public class UpdateQuery extends AbstractQuery {
+public class UpdateQuery /*extends AbstractQuery*/ {
- private final List values;
- private final List wheres;
+ private final List entities;
+ private final String table;
- private UpdateQuery(@NotNull String sql, @NotNull List values, @NotNull List wheres) {
- super(sql);
- this.values = values;
- this.wheres = wheres;
+ private String sql;
+
+ public UpdateQuery(@NotNull String table/*@NotNull String table, @NotNull String sql*/) {
+ //super(table, sql);
+ this.table = SQLUtils.escape(table);
+ this.entities = new ArrayList<>();
+ }
+
+ public UpdateQuery append(@NotNull UpdateEntity entity) {
+ String entitySQL = entity.createSQL(this.table);
+ if (this.sql == null) {
+ this.sql = entitySQL;
+ }
+ else if (!entitySQL.equalsIgnoreCase(this.sql)) {
+ throw new IllegalStateException("Can not add SQLEntity with a different signature!");
+ }
+
+ this.entities.add(entity);
+ return this;
}
@NotNull
@@ -25,6 +41,44 @@ public class UpdateQuery extends AbstractQuery {
return create(table, values, Collections.emptyList());
}
+ @NotNull
+ public static UpdateQuery create(@NotNull String table, @NotNull List values, @NotNull List conditions) {
+ return create(table, UpdateEntity.create(values, conditions));
+ }
+
+ @NotNull
+ public static UpdateQuery create(@NotNull String table, @NotNull UpdateEntity entity) {
+ return new UpdateQuery(table).append(entity);
+ }
+
+ @NotNull
+ public static UpdateQuery create(@NotNull String table, @NotNull Collection entities) {
+ UpdateQuery query = new UpdateQuery(table);
+ entities.forEach(query::append);
+ return query;
+ }
+
+
+
+ public boolean isEmpty() {
+ return this.sql == null || this.table.isBlank() || this.sql.isBlank() || this.entities.isEmpty();
+ }
+
+ @NotNull
+ public String getSQL() {
+ return sql;
+ }
+
+ @NotNull
+ public List getEntities() {
+ return entities;
+ }
+
+ /*@NotNull
+ public static UpdateQuery create(@NotNull String table, @NotNull List values) {
+ return create(table, values, Collections.emptyList());
+ }
+
@NotNull
public static UpdateQuery create(@NotNull String table, @NotNull List values, @NotNull List conditions) {
List columnNames = new ArrayList<>();
@@ -62,5 +116,5 @@ public class UpdateQuery extends AbstractQuery {
@NotNull
public List getWheres() {
return wheres;
- }
+ }*/
}
diff --git a/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java
index 2c14b7a..03413e0 100644
--- a/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java
+++ b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java
@@ -16,6 +16,7 @@ import su.nightexpress.nightcore.util.Players;
import su.nightexpress.nightcore.util.StringUtil;
import su.nightexpress.nightcore.util.text.NightMessage;
import su.nightexpress.nightcore.util.text.TextRoot;
+import su.nightexpress.nightcore.util.text.tag.Tags;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
import su.nightexpress.nightcore.util.wrapper.UniSound;
@@ -148,7 +149,7 @@ public class LangMessage {
// Remove completely empty lines.
// Especially useful for message tags lines without extra text.
StringBuilder stripper = new StringBuilder();
- for (String part : text.split(Placeholders.TAG_LINE_BREAK)) {
+ for (String part : Tags.LINE_BREAK.split(text)) {
if (part.isEmpty()) continue;
if (!stripper.isEmpty()) stripper.append(Placeholders.TAG_LINE_BREAK);
@@ -237,7 +238,7 @@ public class LangMessage {
Players.sendActionBar(player, this.getMessage(player));
}
else if (this.options.getOutputType() == OutputType.TITLES) {
- String[] split = this.getMessage(sender).getString().split(Placeholders.TAG_LINE_BREAK);
+ String[] split = Tags.LINE_BREAK.split(this.getMessage(sender).getString());
String title = NightMessage.asLegacy(split[0]);
String subtitle = split.length >= 2 ? NightMessage.asLegacy(split[1]) : "";
diff --git a/src/main/java/su/nightexpress/nightcore/util/BenchmarkLoop.java b/src/main/java/su/nightexpress/nightcore/util/BenchmarkLoop.java
index b4d9d43..f987fa3 100644
--- a/src/main/java/su/nightexpress/nightcore/util/BenchmarkLoop.java
+++ b/src/main/java/su/nightexpress/nightcore/util/BenchmarkLoop.java
@@ -6,8 +6,10 @@ package su.nightexpress.nightcore.util;
//@Fork(value = 1, jvmArgs = {"-Xms2G", "-Xmx2G"})
public class BenchmarkLoop {
- /*public static void main(String[] args) throws RunnerException {
+// public static void main(String[] args) {
+// }
+ /*public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(BenchmarkLoop.class.getSimpleName())
.forks(1)
diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java b/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java
index cd2c94b..1c8b875 100644
--- a/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java
+++ b/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java
@@ -1,10 +1,15 @@
package su.nightexpress.nightcore.util;
+import com.mojang.datafixers.DSL;
+import com.mojang.datafixers.DataFixer;
+import com.mojang.serialization.Dynamic;
+import com.mojang.serialization.DynamicOps;
import org.bukkit.Bukkit;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCore;
+import su.nightexpress.nightcore.core.CoreConfig;
import java.io.*;
import java.lang.reflect.Constructor;
@@ -29,6 +34,18 @@ public class ItemNbt {
private static final Method NBT_IO_WRITE = Reflex.getMethod(NBT_IO_CLASS, "a", COMPOUND_TAG_CLASS, DataOutput.class);
private static final Method NBT_IO_READ = Reflex.getMethod(NBT_IO_CLASS, "a", DataInput.class);
+ private static final Class> DATA_FIXERS_CLASS = Reflex.getClass("net.minecraft.util.datafix", "DataConverterRegistry"); // DataFixers
+ private static final Method GET_DATA_FIXER = Reflex.getMethod(DATA_FIXERS_CLASS, "a");
+ private static final Class> NBT_OPS_CLASS = Reflex.getClass("net.minecraft.nbt", "DynamicOpsNBT"); // NbtOps
+ private static final Class> REFERENCES_CLASS = Reflex.getClass("net.minecraft.util.datafix.fixes", "DataConverterTypes"); // References
+
+ private static final int DATA_FIXER_SOURCE_VERSION = 3700; // 1.20.4
+ private static final int DATA_FXIER_TARGET_VERSION = 3953; // 1.21
+
+ private static DataFixer DATA_FIXER;
+ private static Object NBT_OPS_INSTANCE;
+ private static Object REFERENCE_ITEM_STACK;
+
// For 1.20.6+
private static Method MINECRAFT_SERVER_REGISTRY_ACCESS;
private static Method ITEM_STACK_PARSE_OPTIONAL;
@@ -40,6 +57,16 @@ public class ItemNbt {
private static Method NMS_SAVE;
static {
+ if (GET_DATA_FIXER != null) {
+ DATA_FIXER = (DataFixer) Reflex.invokeMethod(GET_DATA_FIXER, DATA_FIXERS_CLASS);
+ }
+ if (NBT_OPS_CLASS != null) {
+ NBT_OPS_INSTANCE = Reflex.getFieldValue(NBT_OPS_CLASS, "a");
+ }
+ if (REFERENCES_CLASS != null) {
+ REFERENCE_ITEM_STACK = Reflex.getFieldValue(REFERENCES_CLASS, "t");
+ }
+
if (Version.isAtLeast(Version.MC_1_20_6)) {
Class> minecraftServerClass = Reflex.getClass("net.minecraft.server", "MinecraftServer");
Class> holderLookupProviderClass = Reflex.getInnerClass("net.minecraft.core.HolderLookup", "a"); // Provider
@@ -132,6 +159,12 @@ public class ItemNbt {
Object compoundTag = NBT_IO_READ.invoke(null, new DataInputStream(inputStream));
Object itemStack;
+ if (Version.isAtLeast(Version.MC_1_20_6) && CoreConfig.DATA_FIXER_ENABLED.get()) {
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ Dynamic> dynamic = new Dynamic<>((DynamicOps) NBT_OPS_INSTANCE, compoundTag);
+ compoundTag = DATA_FIXER.update((DSL.TypeReference) REFERENCE_ITEM_STACK, dynamic, DATA_FIXER_SOURCE_VERSION, DATA_FXIER_TARGET_VERSION).getValue();
+ }
+
if (useRegistry) {
if (ITEM_STACK_PARSE_OPTIONAL == null) return null;
diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java b/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java
index 10f852c..a61cf82 100644
--- a/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java
+++ b/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java
@@ -11,7 +11,6 @@ import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.language.entry.LangItem;
import su.nightexpress.nightcore.util.placeholder.PlaceholderMap;
import su.nightexpress.nightcore.util.text.NightMessage;
-import su.nightexpress.nightcore.util.text.tag.Tags;
import java.util.ArrayList;
import java.util.List;
@@ -20,9 +19,11 @@ import java.util.function.UnaryOperator;
public class ItemReplacer {
- private final ItemStack item;
- private final ItemMeta meta;
- private final PlaceholderMap placeholderMap;
+ private final ItemStack item;
+ private final ItemMeta meta;
+
+ private final PlaceholderMap placeholderCache;
+ private final List> operatorCache;
private String displayName;
private String lore;
@@ -42,7 +43,8 @@ public class ItemReplacer {
public ItemReplacer(@Nullable ItemStack item, @Nullable ItemMeta meta) {
this.item = item;
this.meta = meta;
- this.placeholderMap = new PlaceholderMap();
+ this.placeholderCache = new PlaceholderMap();
+ this.operatorCache = new ArrayList<>();
}
@NotNull
@@ -76,8 +78,19 @@ public class ItemReplacer {
public void writeMeta() {
if (!this.hasMeta()) return;
- this.replace(this.placeholderMap.replacer());
- if (this.papi != null) this.injectPlaceholderAPI(this.papi);
+ List> operators = new ArrayList<>(this.operatorCache);
+ operators.add(this.placeholderCache.replacer());
+
+ boolean hasDisplayName = this.displayName != null;
+ boolean hasLore = this.lore != null;
+
+ operators.forEach(operator -> {
+ if (hasDisplayName) this.setDisplayName(operator.apply(this.displayName));
+ if (hasLore) this.setLore(operator.apply(this.lore));
+ });
+
+ //this.replace(this.placeholderCache.replacer());
+// this.injectPlaceholderAPI(this.papi);
this.meta.setDisplayName(this.getDisplayName() == null ? null : NightMessage.asLegacy(this.getDisplayName()));
this.meta.setLore(this.packTrimmedLore());
@@ -89,6 +102,9 @@ public class ItemReplacer {
if (this.hasItem()) {
this.item.setItemMeta(this.meta);
}
+
+ this.placeholderCache.clear();
+ this.operatorCache.clear();
}
public static void replace(@NotNull ItemStack item, @NotNull UnaryOperator replacer) {
@@ -158,80 +174,107 @@ public class ItemReplacer {
return this;
}
+ @NotNull
+ private ItemReplacer cachePlaceholder(@NotNull String placeholder, @NotNull Supplier value) {
+ this.placeholderCache.add(placeholder, value);
+ return this;
+ }
+
+ @NotNull
+ private ItemReplacer cacheOperator(@NotNull UnaryOperator operator) {
+ this.operatorCache.add(operator);
+ return this;
+ }
+
@NotNull
public ItemReplacer replace(@NotNull String placeholder, @NotNull String value) {
- return this.replace(placeholder, () -> value);
+ return this.cachePlaceholder(placeholder, () -> value);
}
@NotNull
public ItemReplacer replace(@NotNull String placeholder, @NotNull Supplier value) {
- this.placeholderMap.add(placeholder, value);
- return this;
+ return this.cachePlaceholder(placeholder, value);
+ }
+
+ @NotNull
+ public ItemReplacer replace(@NotNull String placeholder, @NotNull List replacer) {
+ return this.cacheOperator(str -> str.replace(placeholder, String.join("\n", replacer)));
}
@NotNull
public ItemReplacer replace(@NotNull PlaceholderMap... placeholderMaps) {
for (PlaceholderMap placeholder : placeholderMaps) {
- this.placeholderMap.add(placeholder);
+ this.placeholderCache.add(placeholder);
}
return this;
}
@NotNull
public ItemReplacer replace(@NotNull UnaryOperator replacer) {
- if (this.getDisplayName() != null) {
- this.setDisplayName(replacer.apply(this.getDisplayName()));
- }
-
- if (this.getLore() != null) {
- this.setLore(replacer.apply(this.getLore()));
- }
- return this;
+// this.operatorCache.add(replacer);
+//
+// if (this.getDisplayName() != null) {
+// this.setDisplayName(replacer.apply(this.getDisplayName()));
+// }
+//
+// if (this.getLore() != null) {
+// this.setLore(replacer.apply(this.getLore()));
+// }
+ return cacheOperator(replacer);
}
@NotNull
public ItemReplacer replacePlaceholderAPI(@NotNull Player player) {
+// if (Plugins.hasPlaceholderAPI()) {
+// this.papi = player;
+// }
if (Plugins.hasPlaceholderAPI()) {
- this.papi = player;
+ this.cacheOperator(str -> PlaceholderAPI.setPlaceholders(player, str));
}
return this;
}
@NotNull
+ @Deprecated
public ItemReplacer replaceLoreExact(@NotNull String placeholder, @NotNull List replacer) {
- if (this.getLore() == null) return this;
-
- this.replace(placeholder, () -> String.join(Tags.LINE_BREAK.getFullName(), replacer));
- //this.setLore(Lists.replace(this.packLore(), placeholder, replacer));
- return this;
+// this.replace(placeholder, () -> String.join(Tags.LINE_BREAK.getBracketsName(), replacer));
+// return this;
+ return this.replace(placeholder, replacer);
}
@NotNull
+ @Deprecated
public ItemReplacer replaceLore(@NotNull String placeholder, @NotNull Supplier> replacer) {
- //if (this.getLore() == null) return this;
-
- this.replace(placeholder, () -> String.join(Tags.LINE_BREAK.getFullName(), replacer.get()));
- //this.setLore(Lists.replace(this.packLore(), placeholder, replacer));
- return this;
+// this.replace(placeholder, () -> String.join(Tags.LINE_BREAK.getBracketsName(), replacer.get()));
+// return this;
+ return this.replace(placeholder, replacer.get());
}
@NotNull
+ @Deprecated
public ItemReplacer injectLore(@NotNull String placeholder, @NotNull List replacer) {
- if (this.getLore() == null) return this;
-
- this.setLore(Lists.replace(this.packLore(), placeholder, replacer));
- return this;
+// this.injectLoreCache.put(placeholder, replacer);
+// if (this.getLore() == null) return this;
+//
+// this.setLore(Lists.replace(this.packLore(), placeholder, replacer));
+// return this;
+ return this.replace(placeholder, replacer);
}
+
+
@NotNull
+ @Deprecated
public ItemReplacer injectPlaceholderAPI(@NotNull Player player) {
- if (this.papi != null) {
- this.replace(str -> PlaceholderAPI.setPlaceholders(player, str));
- }
- return this;
+//// if (player != null) {
+// this.replace(str -> PlaceholderAPI.setPlaceholders(player, str));
+//// }
+// return this;
+ return this.replacePlaceholderAPI(player);
}
@NotNull
+ @Deprecated
public ItemReplacer replaceLoreTrail(@NotNull String placeholder, @NotNull List replacer) {
if (this.getLore() == null) return this;
@@ -251,23 +294,23 @@ public class ItemReplacer {
@NotNull
public List packLore() {
- if (this.getLore() == null) return new ArrayList<>();
+ if (this.lore == null) return new ArrayList<>();
- return Splitter.on("\n").splitToList(this.getLore());
+ return Splitter.on("\n").splitToList(this.lore);
}
@NotNull
public List packTrimmedLore() {
- List lore = NightMessage.asLegacy(this.packLore());
+ List lore = this.packLore();
if (this.isTrimLore()) {
lore = Lists.stripEmpty(lore);
}
- return lore;
+ return NightMessage.asLegacy(lore);
}
@Nullable
public String getDisplayName() {
- return displayName;
+ return this.displayName;
}
@NotNull
@@ -278,7 +321,7 @@ public class ItemReplacer {
@Nullable
public String getLore() {
- return lore;
+ return this.lore;
}
@NotNull
diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java
index df644ac..c7daec7 100644
--- a/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java
+++ b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java
@@ -22,7 +22,7 @@ import java.util.function.Consumer;
public class ItemUtil {
- private static final String TEXTURES_HOST = "http://textures.minecraft.net/texture/";
+ public static final String TEXTURES_HOST = "http://textures.minecraft.net/texture/";
@NotNull
public static String getItemName(@NotNull ItemStack item) {
diff --git a/src/main/java/su/nightexpress/nightcore/util/Lists.java b/src/main/java/su/nightexpress/nightcore/util/Lists.java
index 563da82..8dd0bb4 100644
--- a/src/main/java/su/nightexpress/nightcore/util/Lists.java
+++ b/src/main/java/su/nightexpress/nightcore/util/Lists.java
@@ -98,6 +98,7 @@ public class Lists {
@NotNull
public static List stripEmpty(@NotNull List original) {
List stripped = new ArrayList<>();
+
for (int index = 0; index < original.size(); index++) {
String line = original.get(index);
if (line.isEmpty()) {
@@ -106,6 +107,7 @@ public class Lists {
}
stripped.add(line);
}
+
return stripped;
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/Players.java b/src/main/java/su/nightexpress/nightcore/util/Players.java
index 219b9b9..b2e3255 100644
--- a/src/main/java/su/nightexpress/nightcore/util/Players.java
+++ b/src/main/java/su/nightexpress/nightcore/util/Players.java
@@ -14,7 +14,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.integration.VaultHook;
-import su.nightexpress.nightcore.util.message.NexParser;
import su.nightexpress.nightcore.util.text.NightMessage;
import su.nightexpress.nightcore.util.text.TextRoot;
@@ -133,24 +132,10 @@ public class Players {
return Plugins.hasVault() ? VaultHook.getSuffix(player) : "";
}
- @Deprecated
- public static void sendRichMessage(@NotNull CommandSender sender, @NotNull String message) {
- if (!(sender instanceof Player)) {
- sender.sendMessage(Colorizer.apply(NexParser.toPlainText(message)));
- return;
- }
- NexParser.toMessage(message).send(sender);
- }
-
public static void sendModernMessage(@NotNull CommandSender sender, @NotNull String message) {
NightMessage.create(message).send(sender);
}
- @Deprecated
- public static void sendActionBar(@NotNull Player player, @NotNull String msg) {
- player.spigot().sendMessage(ChatMessageType.ACTION_BAR, NexParser.toMessage(msg).build());
- }
-
public static void sendActionBarText(@NotNull Player player, @NotNull String message) {
sendActionBar(player, NightMessage.create(message));
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/StringUtil.java b/src/main/java/su/nightexpress/nightcore/util/StringUtil.java
index ad26cb0..1cc3fa9 100644
--- a/src/main/java/su/nightexpress/nightcore/util/StringUtil.java
+++ b/src/main/java/su/nightexpress/nightcore/util/StringUtil.java
@@ -7,6 +7,7 @@ import su.nightexpress.nightcore.util.random.Rnd;
import su.nightexpress.nightcore.util.regex.TimedMatcher;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.regex.Pattern;
@@ -102,6 +103,36 @@ public class StringUtil {
return buf.toString();
}
+ public static String replacePlaceholders(@NotNull String string, @NotNull Map> placeholders) {
+ if (string.isBlank()) return string;
+
+ StringBuilder builder = new StringBuilder();
+
+ char[] chars = string.toCharArray();
+ int length = string.length();
+ //int index = 0;
+ for (int index = 0; index < length; index++) {
+ if (index == length - 1) continue;
+
+ char letter = string.charAt(index);
+ if (letter == '%') {
+ int indexNext = string.indexOf(letter, index + 1);
+ if (indexNext != -1) {
+ String key = string.substring(index + 1, indexNext);
+ Supplier supplier = placeholders.get(key);
+ if (supplier != null) {
+ builder.append(supplier.get());
+ index = indexNext;
+ continue;
+ }
+ }
+ }
+ builder.append(letter);
+ }
+
+ return builder.toString();
+ }
+
/*@Nullable
public static String parseQuotedContent(@NotNull String string) {
char quote = string.charAt(0);
diff --git a/src/main/java/su/nightexpress/nightcore/util/message/NexComponent.java b/src/main/java/su/nightexpress/nightcore/util/message/NexComponent.java
deleted file mode 100644
index cdf46be..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/message/NexComponent.java
+++ /dev/null
@@ -1,158 +0,0 @@
-package su.nightexpress.nightcore.util.message;
-
-import net.md_5.bungee.api.chat.*;
-import net.md_5.bungee.api.chat.hover.content.Item;
-import net.md_5.bungee.api.chat.hover.content.Text;
-import org.bukkit.Material;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.inventory.meta.ItemMeta;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.Colorizer;
-import su.nightexpress.nightcore.util.ItemNbt;
-
-import java.util.List;
-
-@Deprecated
-public class NexComponent {
-
- private final String text;
-
- public HoverEvent hoverEvent;
- public ClickEvent clickEvent;
-
- private String font;
- private String insertion;
-
- public NexComponent(@NotNull String text) {
- this.text = Colorizer.apply(text);
- }
-
- @NotNull
- public String getText() {
- return this.text;
- }
-
- @Nullable
- public String getFont() {
- return font;
- }
-
- public void setFont(@Nullable String font) {
- this.font = font;
- }
-
- @Nullable
- public String getInsertion() {
- return insertion;
- }
-
- public void setInsertion(@Nullable String insertion) {
- this.insertion = insertion;
- }
-
- @Nullable
- public HoverEvent getHoverEvent() {
- return this.hoverEvent;
- }
-
- @Nullable
- public ClickEvent getClickEvent() {
- return this.clickEvent;
- }
-
- @NotNull
- public NexComponent addClickEvent(@NotNull ClickEvent.Action action, @NotNull String value) {
- return switch (action) {
- case OPEN_URL -> this.openURL(value);
- case OPEN_FILE, CHANGE_PAGE -> this;
- case RUN_COMMAND -> this.runCommand(value);
- case SUGGEST_COMMAND -> this.suggestCommand(value);
- case COPY_TO_CLIPBOARD -> this.copyToClipboard(value);
- };
- }
-
- @NotNull
- public NexComponent addHoverEvent(@NotNull HoverEvent.Action action, @NotNull String value) {
- return switch (action) {
- case SHOW_ITEM -> {
- ItemStack item = ItemNbt.decompress(value);
- yield this.showItem(item == null ? new ItemStack(Material.AIR) : item);
- }
- case SHOW_TEXT -> this.showText(value);
- default -> this;
- };
- }
-
- @NotNull
- public NexComponent showText(@NotNull String text) {
- return this.showText(text.split(NexParser.TAG_NEWLINE));
- }
-
- @NotNull
- public NexComponent showText(@NotNull List text) {
- return this.showText(text.toArray(new String[0]));
- }
-
- @NotNull
- public NexComponent showText(@NotNull String... text) {
- BaseComponent[] base = NexMessage.fromLegacyText(Colorizer.apply(String.join("\n", text)));
- this.hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(base));
- return this;
- }
-
- @NotNull
- public NexComponent showItem(@NotNull ItemStack is) {
- ItemMeta meta = is.getItemMeta();
- Item item = new Item(is.getType().getKey().getKey(), is.getAmount(), ItemTag.ofNbt(meta == null ? null : meta.getAsString()));
- this.hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_ITEM, item);
- return this;
- }
-
- @NotNull
- public NexComponent runCommand(@NotNull String command) {
- this.clickEvent = new ClickEvent(ClickEvent.Action.RUN_COMMAND, command);
- return this;
- }
-
- @NotNull
- public NexComponent suggestCommand(@NotNull String command) {
- this.clickEvent = new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, command);
- return this;
- }
-
- @NotNull
- public NexComponent openURL(@NotNull String url) {
- this.clickEvent = new ClickEvent(ClickEvent.Action.OPEN_URL, url);
- return this;
- }
-
- @NotNull
- public NexComponent copyToClipboard(@NotNull String text) {
- this.clickEvent = new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, text);
- return this;
- }
-
- @NotNull
- public TextComponent build() {
- TextComponent component = new TextComponent(NexMessage.fromLegacyText(this.getText()));
- if (this.hoverEvent != null) {
- component.setHoverEvent(this.getHoverEvent());
- }
- if (this.clickEvent != null) {
- component.setClickEvent(this.getClickEvent());
- }
- component.setFont(this.getFont());
- component.setInsertion(this.getInsertion());
- return component;
- }
-
- @Override
- public String toString() {
- return "NexComponent{" +
- "text='" + text + '\'' +
- ", hoverEvent=" + hoverEvent +
- ", clickEvent=" + clickEvent +
- '}';
- }
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/message/NexMessage.java b/src/main/java/su/nightexpress/nightcore/util/message/NexMessage.java
deleted file mode 100644
index d3b74d1..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/message/NexMessage.java
+++ /dev/null
@@ -1,230 +0,0 @@
-package su.nightexpress.nightcore.util.message;
-
-import com.google.common.base.Preconditions;
-import net.md_5.bungee.api.ChatColor;
-import net.md_5.bungee.api.chat.BaseComponent;
-import net.md_5.bungee.api.chat.ComponentBuilder;
-import net.md_5.bungee.api.chat.TextComponent;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.util.Colorizer;
-import su.nightexpress.nightcore.util.Reflex;
-
-import java.lang.reflect.Method;
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.regex.Pattern;
-import java.util.stream.Stream;
-
-@Deprecated
-public class NexMessage {
-
- //private static final Pattern URL = Pattern.compile("(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$");
-
- private String message;
- private final Map components;
-
- public NexMessage(@NotNull String message) {
- this.message = Colorizer.apply(message);
- this.components = new HashMap<>();
-
- // Originally was in 'fromLegacyText' method of the TextComponent class.
- /*Matcher matcher = RegexUtil.getMatcher(URL, Colorizer.strip(this.message));
- while (RegexUtil.matcherFind(matcher)) {
- String url = matcher.group(0);
- String link = url.startsWith("http") ? url : "http://" + url;
-
- this.addComponent(url, url).openURL(link);
- }*/
- }
-
- @NotNull
- public NexComponent addComponent(@NotNull String placeholder, @NotNull String text) {
- NexComponent component = new NexComponent(text);
- String tag = "{@" + this.components.size() + "}";
-
- this.components.put(tag, component);
- this.message = this.message.replaceFirst(Pattern.quote(placeholder) + "(?!\\w)", tag);
- return component;
- }
-
- @NotNull
- public BaseComponent[] build() {
- return this.build(this.message);
- }
-
- @NotNull
- private BaseComponent[] build(@NotNull String line) {
- ComponentBuilder builder = new ComponentBuilder();
-
- StringBuilder text = new StringBuilder();
- for (int index = 0; index < line.length(); index++) {
- char letter = line.charAt(index);
- if (letter == '{') {
- int indexEnd = line.indexOf("}", index);
- if (indexEnd > index && ++indexEnd <= line.length()) {
- String varRaw = line.substring(index, indexEnd);
- if (varRaw.charAt(1) == '@') {
- if (!text.isEmpty()) {
- append(builder, fromLegacyText(text.toString()), ComponentBuilder.FormatRetention.ALL);
- text = new StringBuilder();
- }
-
- index += varRaw.length() - 1;
-
- NexComponent component = this.components.get(varRaw);
- if (component == null) continue;
-
- append(builder, component.build(), ComponentBuilder.FormatRetention.ALL);
- continue;
- }
- }
- }
- text.append(letter);
- }
- if (!text.isEmpty()) {
- append(builder, fromLegacyText(text.toString()), ComponentBuilder.FormatRetention.ALL);
- }
- TO_RETAIN.clear();
- return builder.create();
- }
-
- public void send(@NotNull CommandSender sender) {
- if (sender instanceof Player player) {
- for (String line : this.message.split("\n")) {
- player.spigot().sendMessage(this.build(line));
- }
- }
- }
-
- public void send(@NotNull CommandSender... senders) {
- Stream.of(senders).forEach(this::send);
- }
-
- public void send(@NotNull Collection senders) {
- senders.forEach(this::send);
- }
-
- // Фикс форматирования компонентов на основе https://github.com/SpigotMC/BungeeCord/pull/3344/
- // Так как этот фикс не встроен в API спигота, и все равно работает не так, как нужно, будем использовать свой.
-
- private static final Set TO_RETAIN = ConcurrentHashMap.newKeySet();
- private static final Method GET_DUMMY = Reflex.getMethod(ComponentBuilder.class, "getDummy");
-
- @NotNull
- public static ComponentBuilder append(@NotNull ComponentBuilder orig,
- @NotNull BaseComponent[] components,
- @NotNull ComponentBuilder.FormatRetention retention) {
- Preconditions.checkArgument(components.length != 0, "No components to append");
- for (BaseComponent component : components) {
- append(orig, component, retention);
- }
- return orig;
- }
-
- @NotNull
- public static ComponentBuilder append(@NotNull ComponentBuilder orig,
- @NotNull BaseComponent component,
- @NotNull ComponentBuilder.FormatRetention retention) {
- List parts = orig.getParts();
- BaseComponent previous = parts.isEmpty() ? null : parts.get(parts.size() - 1);
- if (previous == null) {
- previous = GET_DUMMY == null ? null : (BaseComponent) Reflex.invokeMethod(GET_DUMMY, orig);
- Reflex.setFieldValue(orig, "dummy", null);
- }
-
- BaseComponent inheritance = TO_RETAIN.stream().filter(has -> has.equals(component)).findFirst().orElse(null);
- if (previous != null && inheritance != null) {
- component.copyFormatting(previous, retention, false);
- TO_RETAIN.remove(inheritance);
- }
-
- parts.add(component);
- orig.resetCursor();
- return orig;
- }
-
- public static BaseComponent[] fromLegacyText(@NotNull String message) {
- return fromLegacyText(message, ChatColor.WHITE);
- }
-
- public static BaseComponent[] fromLegacyText(@NotNull String message, @NotNull ChatColor defaultColor) {
- ArrayList components = new ArrayList<>();
- StringBuilder builder = new StringBuilder();
- TextComponent component = new TextComponent();
-
- for (int index = 0; index < message.length(); index++) {
- char letter = message.charAt(index);
- if (letter == ChatColor.COLOR_CHAR) {
- if (++index >= message.length()) break;
-
- letter = message.charAt(index);
- if (letter >= 'A' && letter <= 'Z') {
- letter += 32;
- }
-
- ChatColor format;
- if (letter == 'x' && index + 12 < message.length()) {
- StringBuilder hex = new StringBuilder("#");
- for (int indexHex = 0; indexHex < 6; indexHex++) {
- hex.append(message.charAt(index + 2 + (indexHex * 2)));
- }
- try {
- format = ChatColor.of(hex.toString());
- }
- catch (IllegalArgumentException ex) {
- format = null;
- }
-
- index += 12;
- }
- else {
- format = ChatColor.getByChar( letter );
- }
- if (format == null) continue;
-
- if (builder.length() > 0) {
- TextComponent old = component;
- component = new TextComponent(old);
- old.setText(builder.toString());
- builder = new StringBuilder();
- components.add(old);
- }
-
- if (format == ChatColor.BOLD) {
- component.setBold( true );
- }
- else if (format == ChatColor.ITALIC) {
- component.setItalic(true);
- }
- else if (format == ChatColor.UNDERLINE) {
- component.setUnderlined(true);
- }
- else if (format == ChatColor.STRIKETHROUGH) {
- component.setStrikethrough(true);
- }
- else if (format == ChatColor.MAGIC) {
- component.setObfuscated(true);
- }
- else {
- if (format == ChatColor.RESET) {
- format = defaultColor;
- }
- component = new TextComponent();
- component.setColor(format);
- }
- continue;
- }
- builder.append(letter);
- }
-
- if (!component.hasFormatting()) {
- TO_RETAIN.add(component);
- }
-
- component.setText(builder.toString());
- components.add(component);
- return components.toArray(new BaseComponent[0]);
- }
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/message/NexParser.java b/src/main/java/su/nightexpress/nightcore/util/message/NexParser.java
deleted file mode 100644
index 49ba9a2..0000000
--- a/src/main/java/su/nightexpress/nightcore/util/message/NexParser.java
+++ /dev/null
@@ -1,136 +0,0 @@
-package su.nightexpress.nightcore.util.message;
-
-import net.md_5.bungee.api.chat.ClickEvent;
-import net.md_5.bungee.api.chat.HoverEvent;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import su.nightexpress.nightcore.util.Colorizer;
-import su.nightexpress.nightcore.util.regex.TimedMatcher;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-@Deprecated
-public class NexParser {
-
- private static final String OPTION_PATTERN = ":(?:'|\")(.*?)(?:'|\")(?=>|\\s|$)";
-
- private static final Pattern PATTERN_OPTIONS = Pattern.compile("<\\?(.*?)\\?>(.*?)(?:<\\/>)+");
- private static final Map PATTERN_CLICKS = new HashMap<>();
- private static final Map PATTERN_HOVERS = new HashMap<>();
- private static final Pattern PATTERN_FONT = Pattern.compile("font" + OPTION_PATTERN);
- private static final Pattern PATTERN_INSERTION = Pattern.compile("insertion" + OPTION_PATTERN);
-
- public static final String TAG_NEWLINE = "";
-
- static {
- for (ClickEvent.Action action : ClickEvent.Action.values()) {
- PATTERN_CLICKS.put(action, Pattern.compile(action.name().toLowerCase() + OPTION_PATTERN));
- }
- for (HoverEvent.Action action : HoverEvent.Action.values()) {
- PATTERN_HOVERS.put(action, Pattern.compile(action.name().toLowerCase() + OPTION_PATTERN));
- }
- }
-
- public static boolean contains(@NotNull String message) {
- TimedMatcher matcher = TimedMatcher.create(PATTERN_OPTIONS, message);
- return matcher.find();
- }
-
- @NotNull
- public static String removeFrom(@NotNull String message) {
- return strip(message, false);
- }
-
- @NotNull
- public static String toPlainText(@NotNull String message) {
- return strip(message, true);
- }
-
- @NotNull
- private static String strip(@NotNull String message, boolean toPlain) {
- TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_OPTIONS, message);
- while (timedMatcher.find()) {
- Matcher matcher = timedMatcher.getMatcher();
- String matchFull = matcher.group(0);
- if (toPlain) {
- String matchOptions = matcher.group(1).trim();
- String matchText = matcher.group(2);
- message = message.replace(matchFull, matchText);
- }
- else message = message.replace(matchFull, "");
- }
- return message;
- }
-
- public static String[] getPlainParts(@NotNull String message) {
- //message = StringUtil.color(message.replace("\n", " "));
- return PATTERN_OPTIONS.split(message);
- }
-
- public static String[] getComponentParts(@NotNull String message) {
- List components = new ArrayList<>();
-
- TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_OPTIONS, message);
- while (timedMatcher.find()) {
- components.add(timedMatcher.getMatcher().group(0));
- }
-
- return components.toArray(new String[0]);
- }
-
- @NotNull
- public static NexMessage toMessage(@NotNull String message) {
- message = Colorizer.apply(message);
-
- TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_OPTIONS, message);
- Map parameters = new HashMap<>();
- while (timedMatcher.find()) {
- Matcher matcher = timedMatcher.getMatcher();
- String matchFull = matcher.group(0);
- String matchOptions = matcher.group(1).trim();
- String matchText = matcher.group(2);
-
- message = message.replace(matchFull, matchText);
- parameters.put(matchText, matchOptions);
- }
-
- NexMessage nexMessage = new NexMessage(message);
- for (Map.Entry entry : parameters.entrySet()) {
- String text = entry.getKey();
- String options = entry.getValue();
-
- NexComponent component = nexMessage.addComponent(text, text);
- for (Map.Entry entryParams : PATTERN_CLICKS.entrySet()) {
- String paramValue = getOption(entryParams.getValue(), options);
- if (paramValue == null) continue;
-
- component.addClickEvent(entryParams.getKey(), paramValue);
- break;
- }
- for (Map.Entry entryParams : PATTERN_HOVERS.entrySet()) {
- String paramValue = getOption(entryParams.getValue(), options);
- if (paramValue == null) continue;
-
- component.addHoverEvent(entryParams.getKey(), paramValue);
- break;
- }
- component.setFont(getOption(PATTERN_FONT, options));
- component.setInsertion(getOption(PATTERN_INSERTION, options));
- }
-
- return nexMessage;
- }
-
- @Nullable
- private static String getOption(@NotNull Pattern pattern, @NotNull String from) {
- TimedMatcher timedMatcher = TimedMatcher.create(pattern, from);
- if (!timedMatcher.find()) return null;
-
- return timedMatcher.getMatcher().group(1).stripLeading();
- }
-}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java b/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java
index fea94a3..a04c0ea 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java
@@ -3,8 +3,8 @@ package su.nightexpress.nightcore.util.text;
import net.md_5.bungee.api.chat.BaseComponent;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.util.Colorizer;
-import su.nightexpress.nightcore.util.Placeholders;
import su.nightexpress.nightcore.util.text.tag.TagPool;
+import su.nightexpress.nightcore.util.text.tag.Tags;
import java.util.ArrayList;
import java.util.List;
@@ -48,6 +48,8 @@ public class NightMessage {
return from(string, tagPool).parseIfAbsent();
}
+
+
@NotNull
public static String clean(@NotNull String string) {
return create(string, TagPool.NONE).toLegacy();
@@ -58,6 +60,27 @@ public class NightMessage {
return Colorizer.strip(clean(string));
}
+ /**
+ * Removes all known tags from the given string. Does not affect legacy color codes.
+ * @param string A string to remove tags from.
+ * @return String with no tags formations.
+ */
+ @NotNull
+ public static String stripTags(@NotNull String string) {
+ return stripTags(string, TagPool.NONE);
+ }
+
+ /**
+ * Removes tags from the given string according to a TagPool configuration. Does not affect legacy color codes.
+ * @param string A string to remove tags from.
+ * @param tagPool List of allowed tags.
+ * @return String with allowed tags only in the original tag format Text.
+ */
+ @NotNull
+ public static String stripTags(@NotNull String string, @NotNull TagPool tagPool) {
+ return from(string, tagPool).strip();
+ }
+
@NotNull
public static String asJson(@NotNull String string) {
return create(string).toJson();
@@ -77,7 +100,7 @@ public class NightMessage {
public static List asLegacy(@NotNull List string) {
List list = new ArrayList<>();
for (String str : string) {
- for (String br : str.split(Placeholders.TAG_LINE_BREAK)) {
+ for (String br : Tags.LINE_BREAK.split(str)) {
list.add(asLegacy(br));
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java b/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java
index e34d440..9cd7062 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/TextGroup.java
@@ -10,10 +10,7 @@ import su.nightexpress.nightcore.util.text.tag.decorator.ColorDecorator;
import su.nightexpress.nightcore.util.text.tag.decorator.Decorator;
import su.nightexpress.nightcore.util.text.tag.decorator.GradientColorDecorator;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
+import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class TextGroup implements ComponentBuildable {
@@ -28,7 +25,7 @@ public class TextGroup implements ComponentBuildable {
public TextGroup(@NotNull String name) {
this.name = name;
this.childrens = new ArrayList<>();
- this.decorators = new HashSet<>();
+ this.decorators = new LinkedHashSet<>();
}
@NotNull
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java b/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java
index cbf04bf..58bd238 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java
@@ -18,6 +18,7 @@ import su.nightexpress.nightcore.util.text.tag.impl.ResetTag;
import su.nightexpress.nightcore.util.text.tag.impl.ShortHexColorTag;
import su.nightexpress.nightcore.util.text.tag.impl.TranslationTag;
+import java.util.function.Consumer;
import java.util.function.UnaryOperator;
public class TextRoot {
@@ -156,12 +157,18 @@ public class TextRoot {
return this.component == null ? this.parse() : this.component;
}
+ public enum Mode {
+ PARSE, STRIP
+ }
+
@NotNull
public BaseComponent parse() {
this.rootGroup = new TextGroup(ROOT_NAME);
this.currentGroup = this.rootGroup;
- int length = string.length();
+ this.doJob(Mode.PARSE, letter -> this.currentNode().append(letter));
+
+ /*int length = string.length();
for (int index = 0; index < length; index++) {
char letter = string.charAt(index);
@@ -217,13 +224,142 @@ public class TextRoot {
}
this.currentNode().append(letter);
- }
+ }*/
this.component = this.rootGroup.toComponent();
+ // Clean memory
+ this.rootGroup = null;
+ this.currentGroup = null;
+ this.currentNode = null;
+
return this.component;
}
+ @NotNull
+ public String strip() {
+ StringBuilder builder = new StringBuilder();
+
+ this.doJob(Mode.STRIP, builder::append);
+
+ /*int length = string.length();
+ for (int index = 0; index < length; index++) {
+ char letter = string.charAt(index);
+
+ Tag:
+ if (letter == Tag.OPEN_BRACKET && index != (length - 1)) {
+ int indexEnd = indexOfIgnoreEscaped(string, Tag.CLOSE_BRACKET, index);
+ if (indexEnd == -1) break Tag;
+
+ char next = string.charAt(index + 1);
+ if (next == Tag.CLOSE_BRACKET) break Tag;
+
+ boolean closeTag = false;
+ if (next == Tag.CLOSE_SLASH) {
+ closeTag = true;
+ index++;
+ }
+
+ String bracketsContent = string.substring(index + 1, indexEnd);
+ String tagName = bracketsContent;
+
+ // Check for content tags
+ int semicolonIndex = bracketsContent.indexOf(':');
+ if (semicolonIndex >= 0) {
+ tagName = bracketsContent.substring(0, semicolonIndex);
+ }
+ else if (tagName.startsWith(ShortHexColorTag.NAME)) {
+ tagName = ShortHexColorTag.NAME;
+ }
+
+ Tag tag = Tags.getTag(tagName);
+ if (tag != null) {
+ if (!tagPool.isGoodTag(tag)) {
+ index = indexEnd;
+ continue;
+ }
+ }
+
+ // Move cursor back to '/' of invalid closing tag.
+ if (closeTag) {
+ index--;
+ }
+ }
+
+ builder.append(letter);
+ }*/
+
+ return builder.toString();
+ }
+
+ private void doJob(@NotNull Mode mode, @NotNull Consumer consumer) {
+ int length = string.length();
+ for (int index = 0; index < length; index++) {
+ char letter = string.charAt(index);
+
+ Tag:
+ if (letter == Tag.OPEN_BRACKET && index != (length - 1)) {
+ int indexEnd = indexOfIgnoreEscaped(string, Tag.CLOSE_BRACKET, index);//string.indexOf(Tag.CLOSE_BRACKET, index);
+ //System.out.println("indexEnd = " + indexEnd);
+ if (indexEnd == -1) break Tag;
+
+ char next = string.charAt(index + 1);
+ if (next == Tag.CLOSE_BRACKET) break Tag;
+
+ boolean closeTag = false;
+ if (next == Tag.CLOSE_SLASH) {
+ closeTag = true;
+ index++;
+ }
+
+ String bracketsContent = string.substring(index + 1, indexEnd);
+ //System.out.println("bracketsContent = " + bracketsContent);
+
+ String tagName = bracketsContent;
+ String tagContent = null;
+
+ // Check for content tags
+ int semicolonIndex = bracketsContent.indexOf(':');
+ if (semicolonIndex >= 0) {
+ tagName = bracketsContent.substring(0, semicolonIndex);
+ tagContent = bracketsContent.substring(semicolonIndex + 1);
+ //System.out.println("tagName = " + tagName);
+ //System.out.println("tagContent = " + tagContent);
+ }
+ else if (tagName.startsWith(ShortHexColorTag.NAME)) {
+ tagName = ShortHexColorTag.NAME;
+ tagContent = bracketsContent;
+ }
+
+ Tag tag = Tags.getTag(tagName);
+ //System.out.println("found tag = " + tag);
+
+ if (tag != null) {
+ if (mode == Mode.PARSE) {
+ if (tagPool.isGoodTag(tag)) {
+ this.proceedTag(tag, closeTag, tagContent);
+ }
+ index = indexEnd;
+ continue;
+ }
+ else {
+ if (!tagPool.isGoodTag(tag)) {
+ index = indexEnd;
+ continue;
+ }
+ }
+ }
+
+ // Move cursor back to '/' of invalid closing tag.
+ if (closeTag) {
+ index--;
+ }
+ }
+
+ consumer.accept(letter);
+ }
+ }
+
private void proceedTag(@NotNull Tag tag, boolean closeTag, @Nullable String tagContent) {
if (tag instanceof PlaceholderTag placeholderTag) {
if (!closeTag) {
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java
index e2a1556..afd7d79 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java
@@ -81,7 +81,6 @@ public class Tags {
}
public static void registerTag(@NotNull Tag tag) {
- REGISTRY.put(tag.getName(), tag);
for (String alias : tag.getAliases()) {
REGISTRY.put(alias, tag);
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java
index 7261a38..5db08f2 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java
@@ -25,6 +25,7 @@ public class Tag {
for (String alias : aliases) {
this.aliases.add(alias.toLowerCase());
}
+ this.aliases.add(this.name);
}
@NotNull
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java
index 73e75de..1652ea1 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java
@@ -16,6 +16,14 @@ public class GradientTag extends Tag implements ContentTag {
super(NAME);
}
+ @NotNull
+ public String enclose(@NotNull String hexStart, @NotNull String hexEnd, @NotNull String text) {
+ String tagOpen = brackets(this.getName() + ":" + hexStart + ":" + hexEnd);
+ String tagClose = this.getClosingName();
+
+ return tagOpen + text + tagClose;
+ }
+
@Override
@Nullable
public GradientColorDecorator parse(@NotNull String content) {
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java
index 51d3404..c6c9c9a 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java
@@ -37,15 +37,8 @@ public class HoverTag extends ComplexTag implements ContentTag {
@NotNull
public String enclose(@NotNull String text, @NotNull HoverEvent.Action action, @NotNull String content) {
- //content = content.replace("'", "\\'");
-
- //String tagOpen = brackets(NAME + ":" + action.name().toLowerCase() + ":'" + content + "'");
- //String tagClose = this.getClosingName();
-
String data = action.name().toLowerCase() + ":'" + this.escapeQuotes(content) + "'";
return this.encloseContent(text, data);
-
- //return tagOpen + text + tagClose;
}
@Override
@@ -68,7 +61,7 @@ public class HoverTag extends ComplexTag implements ContentTag {
if (action == HoverEvent.Action.SHOW_TEXT) {
return new ShowTextDecorator(value);
}
- else if (action == HoverEvent.Action.SHOW_ITEM) {
+ else if (action == HoverEvent.Action.SHOW_ITEM) {
return new ShowItemDecorator(value);
}
return null;
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java
index 63fdbac..f8a02ec 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java
@@ -15,4 +15,11 @@ public class LineBreakTag extends Tag implements PlaceholderTag {
public String getValue() {
return "\n";
}
+
+ public String[] split(@NotNull String string) {
+ for (String alias : this.getAliases()) {
+ string = string.replace(brackets(alias), "\n");
+ }
+ return string.split("\n");
+ }
}
diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java
index 1093da9..edd48a4 100644
--- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java
+++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java
@@ -1,7 +1,6 @@
package su.nightexpress.nightcore.util.text.tag.impl;
import su.nightexpress.nightcore.util.text.tag.api.SimpleTag;
-import su.nightexpress.nightcore.util.text.tag.api.Tag;
public class ResetTag extends SimpleTag { // TODO Must be just Tag, SimpleTag for compatibility