版本更新至:4.04

调整:命令帮助的格式现在可以在语言文件中更改了。
调整:@CommandRegister 现在可以直接标注在 BaseSubCommand 成员变量上进行注册了(详见 TabooLibPluginMainCommand 写法)。
调整:TagAPI,TagManager 作废,但部分方法仍可使用。
新增:BaseSubCommand 类新增 getPermission 方法用于判断子命令权限
新增:TagDataHandler 类用于代替 TagManager 类
新增:TagPacket 类用于代替 TagAPI 类
修复:前后缀以及昵称的各种不兼容问题
修复:ItemUtils 工具载入物品时因 material 值不存在而导致的报错
删除:me.skymc.taboolib.team.TagUtils 类永久删除
This commit is contained in:
坏黑 2018-05-23 04:36:51 +08:00
parent ffa2d616c4
commit 0acf324b15
29 changed files with 1996 additions and 1844 deletions

View File

@ -84,4 +84,4 @@ public class TDependency {
private static int getDownloadPoolSize() {
return Main.getInst().getConfig().getInt("DOWNLOAD-POOL-SIZE", 4);
}
}
}

View File

@ -1,113 +1,61 @@
package com.ilummc.tlib.inject;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ilummc.tlib.annotations.TConfig;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.fileutils.ConfigUtils;
import com.google.gson.annotations.SerializedName;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.annotations.Config;
import com.ilummc.tlib.bean.Property;
import org.apache.commons.lang3.Validate;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
public class TConfigInjector {
public static void fixUnicode(YamlConfiguration configuration) {
try {
Field field = YamlConfiguration.class.getDeclaredField("yamlOptions");
field.setAccessible(true);
field.set(configuration, NoUnicodeDumperOption.INSTANCE);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
private static final class NoUnicodeDumperOption extends DumperOptions {
private static final NoUnicodeDumperOption INSTANCE = new NoUnicodeDumperOption();
@Override
public void setAllowUnicode(boolean allowUnicode) {
super.setAllowUnicode(false);
}
@Override
public boolean isAllowUnicode() {
return false;
}
@Override
public void setLineBreak(LineBreak lineBreak) {
super.setLineBreak(LineBreak.getPlatformLineBreak());
}
}
public static Object loadConfig(Plugin plugin, Class<?> clazz) {
try {
TConfig config = clazz.getAnnotation(TConfig.class);
Config config = clazz.getAnnotation(Config.class);
Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name());
if (!file.exists()) {
if (config.fromJar()) {
plugin.saveResource(config.name(), true);
} else {
saveConfig(plugin, clazz.newInstance());
}
}
Object obj = unserialize(plugin, clazz);
if (config.readOnly()) {
saveConfig(plugin, obj);
}
return obj;
if (!file.exists()) if (config.fromJar()) plugin.saveResource(config.name(), true);
else saveConfig(plugin, clazz.newInstance());
return unserialize(plugin, clazz);
} catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName());
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解");
} catch (Exception e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName());
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败");
}
return null;
}
public static void reloadConfig(Plugin plugin, Object object) {
try {
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name());
Map<String, Object> map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file));
Object obj = ConfigUtils.mapToObj(map, object);
if (config.readOnly()) {
saveConfig(plugin, obj);
}
} catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName());
} catch (Exception e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), object.getClass().getSimpleName());
}
}
public static Object unserialize(Plugin plugin, Class<?> clazz) {
try {
TConfig config = clazz.getAnnotation(TConfig.class);
Config config = clazz.getAnnotation(Config.class);
Validate.notNull(config);
return ConfigUtils.confToObj(
ConfigUtils.mapToConf(
ConfigUtils.yamlToMap(
Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz);
return new GsonBuilder().disableHtmlEscaping().excludeFieldsWithModifiers(config.excludeModifiers())
.create().fromJson(new Gson().toJson(new Yaml()
.dump(Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz);
} catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-FILE", plugin.toString(), clazz.getSimpleName());
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解或文件不存在");
return null;
} catch (Exception e) {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e1) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName());
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败");
return null;
}
}
@ -115,29 +63,95 @@ public class TConfigInjector {
public static Map<String, Object> serialize(Plugin plugin, Object object) {
try {
TConfig config = object.getClass().getAnnotation(TConfig.class);
Config config = object.getClass().getAnnotation(Config.class);
Validate.notNull(config);
return ConfigUtils.objToMap(ConfigUtils.objToConf(object).getValues(false), config.excludeModifiers());
return new Serializer(new LinkedHashMap<>(), object, config.excludeModifiers()).get();
} catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.SAVE-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName());
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败:没有 @Config 注解");
} catch (Exception e) {
TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), object.getClass().getSimpleName());
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败");
}
return null;
}
public static void saveConfig(Plugin plugin, Object object) throws IOException, NullPointerException {
TConfig config = object.getClass().getAnnotation(TConfig.class);
Config config = object.getClass().getAnnotation(Config.class);
Validate.notNull(config);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Map map = gson.fromJson(gson.toJson(object), HashMap.class);
YamlConfiguration configuration = (YamlConfiguration) ConfigUtils.mapToConf(map);
Object obj = serialize(plugin, object);
Validate.notNull(obj);
File target = new File(plugin.getDataFolder(), config.name());
if (!target.exists()) {
target.createNewFile();
}
byte[] arr = configuration.saveToString().getBytes(config.charset());
if (!target.exists()) target.createNewFile();
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
String str = yaml.dump(obj);
byte[] arr = str.getBytes(config.charset());
Files.write(arr, target);
}
private static final List<Class<?>> primitiveType = Lists.newArrayList(Integer.class,
Double.class, Float.class, Boolean.class, Short.class, Byte.class, Character.class, Long.class, String.class);
private static class Serializer {
private HashMap<String, Object> map;
private Object o;
private int modifiers;
private Serializer(HashMap<String, Object> map, Object o, int modifiers) {
this.map = map;
this.o = o;
this.modifiers = modifiers;
}
private HashMap<String, Object> get() {
for (Field field : o.getClass().getDeclaredFields()) {
if ((field.getModifiers() & modifiers) == 0 && !field.isSynthetic())
try {
SerializedName node = field.getAnnotation(SerializedName.class);
if (!field.isAccessible()) field.setAccessible(true);
Object obj = field.get(o);
map.put(node == null ? field.getName() : node.value(), serialize(obj));
} catch (Exception ignored) {
}
}
return map;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private Object serialize(Object o) {
try {
if (o.getClass().isPrimitive() || primitiveType.contains(o.getClass())) {
return o;
} else if (o.getClass().isArray()) {
List list = new ArrayList<>();
int len = (int) o.getClass().getField("length").get(o);
for (int i = 0; i < len; i++) {
list.add(serialize(Array.get(o, i)));
}
return list;
} else if (o instanceof Collection) {
return ((Collection) o).stream().map(this::serialize).collect(Collectors.toList());
} else if (o instanceof Map) {
Map map = new LinkedHashMap<>();
((Map) o).forEach((o1, o2) -> map.put((String) o1, serialize(o2)));
return map;
} else if (o instanceof ConfigurationSerializable) {
Map map = new LinkedHashMap<>();
map.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY,
ConfigurationSerialization.getAlias((Class<? extends ConfigurationSerializable>) o.getClass()));
map.putAll(((ConfigurationSerializable) o).serialize());
return map;
} else if (o instanceof Property) {
return serialize(((Property) o).get());
} else {
return new Serializer(new HashMap<>(), o, modifiers).get();
}
} catch (Exception ignored) {
return null;
}
}
}
}

View File

@ -8,6 +8,7 @@ import me.skymc.taboolib.anvil.AnvilContainerAPI;
import me.skymc.taboolib.bstats.Metrics;
import me.skymc.taboolib.commands.TabooLibMainCommand;
import me.skymc.taboolib.commands.internal.BaseMainCommand;
import me.skymc.taboolib.commands.internal.TBaseCommand;
import me.skymc.taboolib.commands.language.Language2Command;
import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand;
import me.skymc.taboolib.commands.plugin.TabooLibPluginMainCommand;
@ -21,6 +22,7 @@ import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.inventory.speciaitem.SpecialItem;
import me.skymc.taboolib.itagapi.TagDataHandler;
import me.skymc.taboolib.javashell.JavaShell;
import me.skymc.taboolib.listener.*;
import me.skymc.taboolib.message.ChatCatcher;
@ -28,7 +30,6 @@ import me.skymc.taboolib.mysql.hikari.HikariHandler;
import me.skymc.taboolib.mysql.protect.MySQLConnection;
import me.skymc.taboolib.nms.item.DabItemUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.packet.PacketUtils;
import me.skymc.taboolib.permission.PermissionUtils;
import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.taboolib.sign.SignUtils;
@ -36,8 +37,6 @@ import me.skymc.taboolib.skript.SkriptHandler;
import me.skymc.taboolib.string.StringUtils;
import me.skymc.taboolib.string.language2.Language2;
import me.skymc.taboolib.support.SupportPlaceholder;
import me.skymc.taboolib.team.TagAPI;
import me.skymc.taboolib.team.TagUtils;
import me.skymc.taboolib.timecycle.TimeCycleManager;
import me.skymc.taboolib.update.UpdateTask;
import me.skymc.tlm.TLM;
@ -150,6 +149,8 @@ public class Main extends JavaPlugin implements Listener {
JavaShell.javaShellSetup();
// 注册脚本
SkriptHandler.getInst();
// 注册头衔
TagDataHandler.init(this);
// 载入语言文件
exampleLanguage2 = new Language2("Language2", this);
@ -180,10 +181,6 @@ public class Main extends JavaPlugin implements Listener {
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
new SupportPlaceholder(getInst(), "taboolib").hook();
}
// 载入 ProtocolLib 扩展
if (PacketUtils.isProtocolLibEnabled()) {
TagAPI.inst();
}
// 载入 SpecialItem 接口
SpecialItem.getInst().loadItems();
// 载入 TLM 接口
@ -244,9 +241,6 @@ public class Main extends JavaPlugin implements Listener {
// 提示信息
TLocale.Logger.error("NOTIFY.SUCCESS-DISABLE");
// 清理头衔
TagUtils.delete();
// 结束连接
if (connection != null && connection.isConnection()) {
connection.closeConnection();
@ -332,8 +326,8 @@ public class Main extends JavaPlugin implements Listener {
getCommand("language2").setExecutor(new Language2Command());
getCommand("taboolibrarymodule").setExecutor(new TLMCommands());
getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand());
BaseMainCommand.createCommandExecutor("taboolib", new TabooLibMainCommand());
BaseMainCommand.createCommandExecutor("taboolibplugin", new TabooLibPluginMainCommand());
TBaseCommand.registerCommand("taboolib", new TabooLibMainCommand());
TBaseCommand.registerCommand("taboolibplugin", new TabooLibPluginMainCommand());
}
private void registerListener() {

View File

@ -224,7 +224,7 @@ public class Metrics {
playerAmount = Bukkit.getOnlinePlayers().size();
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = org.bukkit.Bukkit.getVersion();
String bukkitVersion = Bukkit.getVersion();
bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1);
// OS/Java specific data

View File

@ -2,10 +2,9 @@ package me.skymc.taboolib.commands.internal;
import com.google.common.base.Preconditions;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.Ref;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.commands.internal.type.CommandField;
import me.skymc.taboolib.commands.internal.type.CommandRegister;
import me.skymc.taboolib.commands.internal.type.CommandType;
import me.skymc.taboolib.string.ArrayUtils;
@ -47,6 +46,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
public static void loadCommandRegister(BaseMainCommand baseMainCommand) {
List<Method> methods = new ArrayList<>();
List<CommandField> fields = new ArrayList<>();
baseMainCommand.getLinkClasses().forEach(clazz -> Arrays.stream(clazz.getDeclaredMethods()).filter(method -> method.getAnnotation(CommandRegister.class) != null).forEach(methods::add));
if (methods.size() > 0) {
methods.sort(Comparator.comparingDouble(a -> a.getAnnotation(CommandRegister.class).priority()));
@ -58,8 +58,19 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
}
});
}
if (methods.size() > 0) {
TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-REGISTER", baseMainCommand.getRegisterCommand().getPlugin().getName(), baseMainCommand.getRegisterCommand().getName(), String.valueOf(methods.size()));
baseMainCommand.getLinkClasses().forEach(clazz -> Arrays.stream(clazz.getDeclaredFields()).filter(field -> field.getAnnotation(CommandRegister.class) != null && field.getType().equals(BaseSubCommand.class)).forEach(field -> fields.add(new CommandField(field, clazz))));
if (fields.size() > 0) {
fields.sort(Comparator.comparingDouble(commandField -> commandField.getField().getAnnotation(CommandRegister.class).priority()));
fields.forEach(commandField -> {
try {
commandField.getField().setAccessible(true);
baseMainCommand.registerSubCommand((BaseSubCommand) commandField.getField().get(commandField.getParent().newInstance()));
} catch (Exception ignored) {
}
});
}
if (methods.size() + fields.size() > 0) {
TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-REGISTER", baseMainCommand.getRegisterCommand().getPlugin().getName(), baseMainCommand.getRegisterCommand().getName(), String.valueOf(methods.size() + fields.size()));
}
}
@ -94,7 +105,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
helpCommand(sender, label);
} else {
for (BaseSubCommand subCommand : subCommands) {
if (subCommand == null || !args[0].equalsIgnoreCase(subCommand.getLabel())) {
if (subCommand == null || !args[0].equalsIgnoreCase(subCommand.getLabel()) || !hasPermission(sender, subCommand)) {
continue;
}
if (!isConfirmType(sender, subCommand.getType())) {
@ -113,7 +124,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
@Override
public void run() {
List<BaseSubCommand> commandCompute = subCommands.stream().filter(Objects::nonNull).sorted((b, a) -> Double.compare(StringUtils.similarDegree(args[0], a.getLabel()), StringUtils.similarDegree(args[0], b.getLabel()))).collect(Collectors.toList());
List<BaseSubCommand> commandCompute = subCommands.stream().filter(x -> x != null && hasPermission(sender, x)).sorted((b, a) -> Double.compare(StringUtils.similarDegree(args[0], a.getLabel()), StringUtils.similarDegree(args[0], b.getLabel()))).collect(Collectors.toList());
if (commandCompute.size() > 0) {
TLocale.sendTo(sender, "COMMANDS.INTERNAL.ERROR-COMMAND", args[0], commandCompute.get(0).getCommandString(label).trim());
}
@ -125,7 +136,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) {
return args.length == 1 ? subCommands.stream().filter(internalCommandExecutor -> internalCommandExecutor != null && (args[0].isEmpty() || internalCommandExecutor.getLabel().toLowerCase().startsWith(args[0].toLowerCase()))).map(ISubCommand::getLabel).collect(Collectors.toList()) : null;
return args.length == 1 ? subCommands.stream().filter(subCommand -> subCommand != null && hasPermission(commandSender, subCommand) && (args[0].isEmpty() || subCommand.getLabel().toLowerCase().startsWith(args[0].toLowerCase()))).map(ISubCommand::getLabel).collect(Collectors.toList()) : null;
}
@Override
@ -162,7 +173,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
sender.sendMessage(getEmptyLine());
sender.sendMessage(getCommandTitle());
sender.sendMessage(getEmptyLine());
subCommands.stream().map(subCommand -> subCommand == null ? getEmptyLine() : subCommand.getCommandString(label)).forEach(sender::sendMessage);
subCommands.stream().filter(subCommands -> hasPermission(sender, subCommands)).map(subCommand -> subCommand == null ? getEmptyLine() : subCommand.getCommandString(label)).forEach(sender::sendMessage);
sender.sendMessage(getEmptyLine());
}
@ -178,4 +189,8 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
} catch (Exception ignored) {
}
}
private boolean hasPermission(CommandSender sender, BaseSubCommand baseSubCommand) {
return baseSubCommand == null || baseSubCommand.getPermission() == null || sender.hasPermission(baseSubCommand.getPermission());
}
}

View File

@ -1,8 +1,10 @@
package me.skymc.taboolib.commands.internal;
import me.skymc.taboolib.commands.internal.type.CommandArgument;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.commands.internal.type.CommandType;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
@ -23,23 +25,16 @@ public abstract class BaseSubCommand implements ISubCommand {
return false;
}
public String getPermission() {
return null;
}
public boolean isParameterConform(String[] args) {
return IntStream.range(0, getArguments().length).noneMatch(i -> getArguments()[i].isRequired() && (args == null || args.length <= i));
}
public String getCommandString(String label) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" §f/");
stringBuilder.append(label);
stringBuilder.append(" ");
stringBuilder.append(getLabel());
stringBuilder.append(" ");
for (CommandArgument parameter : getArguments()) {
stringBuilder.append(parameter.toString());
stringBuilder.append(" ");
}
stringBuilder.append("§6- §e");
stringBuilder.append(getDescription());
return stringBuilder.toString();
String stringBuilder = Arrays.stream(getArguments()).map(parameter -> parameter.toString() + " ").collect(Collectors.joining());
return TLocale.asString("COMMANDS.INTERNAL.COMMAND-HELP", label, getLabel(), stringBuilder.trim(), getDescription());
}
}

View File

@ -0,0 +1,19 @@
package me.skymc.taboolib.commands.internal;
/**
* @Author sky
* @Since 2018-05-23 2:43
*/
public class TBaseCommand {
/**
* 向服务端注册 BaseMainCommand
*
* @param command 命令全称需在 plugin.yml 内注册
* @param baseMainCommand 命令对象
* @return {@link BaseMainCommand}
*/
public static BaseMainCommand registerCommand(String command, BaseMainCommand baseMainCommand) {
return BaseMainCommand.createCommandExecutor(command, baseMainCommand);
}
}

View File

@ -1,5 +1,7 @@
package me.skymc.taboolib.commands.internal.type;
import com.ilummc.tlib.resources.TLocale;
import java.util.Objects;
/**
@ -30,7 +32,7 @@ public class CommandArgument {
@Override
public String toString() {
return required ? "§7[§8" + name + "§7]" : "§7<§8" + name + "§7>";
return required ? TLocale.asString("COMMANDS.INTERNAL.COMMAND-ARGUMENT-REQUIRE", name) : TLocale.asString("COMMANDS.INTERNAL.COMMAND-ARGUMENT", name);
}
@Override

View File

@ -0,0 +1,26 @@
package me.skymc.taboolib.commands.internal.type;
import java.lang.reflect.Field;
/**
* @Author sky
* @Since 2018-05-23 3:07
*/
public class CommandField {
private final Field field;
private final Class<?> parent;
public CommandField(Field field, Class<?> parent) {
this.field = field;
this.parent = parent;
}
public Field getField() {
return field;
}
public Class<?> getParent() {
return parent;
}
}

View File

@ -9,7 +9,7 @@ import java.lang.annotation.Target;
* @Author sky
* @Since 2018-05-09 22:38
*/
@Target(ElementType.METHOD)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandRegister {

View File

@ -6,6 +6,7 @@ import me.skymc.taboolib.commands.internal.BaseMainCommand;
import me.skymc.taboolib.commands.internal.BaseSubCommand;
import me.skymc.taboolib.commands.internal.ISubCommand;
import me.skymc.taboolib.commands.internal.type.CommandArgument;
import me.skymc.taboolib.commands.internal.type.CommandRegister;
import me.skymc.taboolib.plugin.PluginUtils;
import me.skymc.taboolib.string.ArrayUtils;
import org.bukkit.Bukkit;
@ -13,7 +14,6 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@ -24,12 +24,9 @@ import java.util.stream.Collectors;
*/
public class TabooLibPluginMainCommand extends BaseMainCommand {
public TabooLibPluginMainCommand() {
listCommand();
infoCommand();
loadCommand();
unloadCommand();
reloadCommand();
@Override
public String getCommandTitle() {
return TLocale.asString("COMMANDS.TPLUGIN.COMMAND-TITLE");
}
@Override
@ -43,195 +40,191 @@ public class TabooLibPluginMainCommand extends BaseMainCommand {
}
}
@CommandRegister(priority = 1)
BaseSubCommand load = new BaseSubCommand() {
@Override
public String getLabel() {
return "load";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.LOAD.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.LOAD.ARGUMENTS.0"), true)};
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = ArrayUtils.arrayJoin(args, 0);
if (PluginUtils.getPluginByName(name) != null) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name);
} else {
switch (PluginUtils.load(name)) {
case "loaded": {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-SUCCESS", name);
break;
}
default: {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-FAIL", name);
}
}
}
}
};
@CommandRegister(priority = 2)
BaseSubCommand unload = new BaseSubCommand() {
@Override
public String getLabel() {
return "unload";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.ARGUMENTS.0"), true)};
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = ArrayUtils.arrayJoin(args, 0);
Plugin plugin = PluginUtils.getPluginByName(name);
if (plugin == null) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN", name);
} else if (PluginUtils.isIgnored(plugin)) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN-IGNORED", name);
} else {
switch (PluginUtils.unload(plugin)) {
case "unloaded": {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-SUCCESS", name);
break;
}
default: {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-FAIL", name);
}
}
}
}
};
@CommandRegister(priority = 3)
BaseSubCommand reload = new BaseSubCommand() {
@Override
public String getLabel() {
return "reload";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.RELOAD.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.RELOAD.ARGUMENTS.0"), true)};
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = ArrayUtils.arrayJoin(args, 0);
Plugin plugin = PluginUtils.getPluginByName(name);
if (plugin == null) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN", name);
} else if (PluginUtils.isIgnored(plugin)) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN-IGNORED", name);
} else {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.TRY-RELOAD");
PluginUtils.reload(plugin);
}
}
};
@CommandRegister(priority = 4)
BaseSubCommand info = new BaseSubCommand() {
@Override
public String getLabel() {
return "info";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.INFO.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.INFO.ARGUMENTS.0"), true)};
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = ArrayUtils.arrayJoin(args, 0);
Plugin plugin = PluginUtils.getPluginByName(name);
if (plugin == null) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name);
} else {
try {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INFO-PLUGIN",
plugin.getName(),
String.valueOf(plugin.getDescription().getDescription()),
String.valueOf(plugin.getDescription().getAuthors()),
String.valueOf(plugin.getDescription().getDepend()),
String.valueOf(plugin.getDescription().getSoftDepend()),
String.valueOf(plugin.getDescription().getMain()),
String.valueOf(plugin.getDescription().getVersion()),
String.valueOf(plugin.getDescription().getWebsite()),
String.valueOf(plugin.getDescription().getCommands().keySet()));
} catch (Exception ignored) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name);
}
}
}
};
@CommandRegister(priority = 5)
BaseSubCommand list = new BaseSubCommand() {
@Override
public String getLabel() {
return "list";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.LIST.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[0];
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
List<String> pluginList = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList());
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LIST.LIST-PLUGIN", String.valueOf(Bukkit.getPluginManager().getPlugins().length), Joiner.on(", ").join(pluginList));
}
};
// *********************************
//
// Private Methods
//
// *********************************
private boolean isPluginCommand(String label) {
return "info".equalsIgnoreCase(label) || "load".equalsIgnoreCase(label) || "unload".equalsIgnoreCase(label) || "reload".equalsIgnoreCase(label);
}
@Override
public String getCommandTitle() {
return TLocale.asString("COMMANDS.TPLUGIN.COMMAND-TITLE");
}
void loadCommand() {
registerSubCommand(new BaseSubCommand() {
@Override
public String getLabel() {
return "load";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.LOAD.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.LOAD.ARGUMENTS.0"), true)};
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = ArrayUtils.arrayJoin(args, 0);
if (PluginUtils.getPluginByName(name) != null) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name);
} else {
switch (PluginUtils.load(name)) {
case "loaded": {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-SUCCESS", name);
break;
}
default: {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-FAIL", name);
}
}
}
}
});
}
void unloadCommand() {
registerSubCommand(new BaseSubCommand() {
@Override
public String getLabel() {
return "unload";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.ARGUMENTS.0"), true)};
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = ArrayUtils.arrayJoin(args, 0);
Plugin plugin = PluginUtils.getPluginByName(name);
if (plugin == null) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN", name);
} else if (PluginUtils.isIgnored(plugin)) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN-IGNORED", name);
} else {
switch (PluginUtils.unload(plugin)) {
case "unloaded": {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-SUCCESS", name);
break;
}
default: {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-FAIL", name);
}
}
}
}
});
}
void reloadCommand() {
registerSubCommand(new BaseSubCommand() {
@Override
public String getLabel() {
return "reload";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.RELOAD.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.RELOAD.ARGUMENTS.0"), true)};
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = ArrayUtils.arrayJoin(args, 0);
Plugin plugin = PluginUtils.getPluginByName(name);
if (plugin == null) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN", name);
} else if (PluginUtils.isIgnored(plugin)) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN-IGNORED", name);
} else {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.TRY-RELOAD");
PluginUtils.reload(plugin);
}
}
});
}
void infoCommand() {
registerSubCommand(new BaseSubCommand() {
@Override
public String getLabel() {
return "info";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.INFO.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.INFO.ARGUMENTS.0"), true)};
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = ArrayUtils.arrayJoin(args, 0);
Plugin plugin = PluginUtils.getPluginByName(name);
if (plugin == null) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name);
} else {
try {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INFO-PLUGIN",
plugin.getName(),
String.valueOf(plugin.getDescription().getDescription()),
String.valueOf(plugin.getDescription().getAuthors()),
String.valueOf(plugin.getDescription().getDepend()),
String.valueOf(plugin.getDescription().getSoftDepend()),
String.valueOf(plugin.getDescription().getMain()),
String.valueOf(plugin.getDescription().getVersion()),
String.valueOf(plugin.getDescription().getWebsite()),
String.valueOf(plugin.getDescription().getCommands().keySet()));
} catch (Exception ignored) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name);
}
}
}
});
}
void listCommand() {
registerSubCommand(new BaseSubCommand() {
@Override
public String getLabel() {
return "list";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.LIST.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[0];
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
List<String> pluginList = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList());
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LIST.LIST-PLUGIN", String.valueOf(Bukkit.getPluginManager().getPlugins().length), Joiner.on(", ").join(pluginList));
}
});
}
}

View File

@ -49,7 +49,7 @@ public class SaveCommand extends SubCommand {
return;
}
ChatCatcher.call((Player) sender, new ChatCatcher.Catcher() {
ChatCatcher.call((Player) sender, new Catcher() {
@Override
public void cancel() {

View File

@ -2,8 +2,7 @@ package me.skymc.taboolib.commands.taboolib;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.team.TagAPI;
import me.skymc.taboolib.team.TagManager;
import me.skymc.taboolib.itagapi.TagDataHandler;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -27,8 +26,7 @@ public class TagDeleteCommand extends SubCommand {
return;
}
TagManager.getInst().unloadData(player);
TagAPI.removePlayerDisplayName(player);
TagDataHandler.getHandler().reset(player);
if (sender instanceof Player) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-DELETE", args[1]);

View File

@ -3,6 +3,7 @@ package me.skymc.taboolib.commands.taboolib;
import com.ilummc.tlib.resources.TLocale;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.itagapi.TagDataHandler;
import me.skymc.taboolib.team.TagAPI;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
@ -27,12 +28,9 @@ public class TagDisplayCommand extends SubCommand {
return;
}
String value = getArgs(2).replace("&", "§");
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
value = PlaceholderAPI.setPlaceholders(player, value);
}
String value = TLocale.Translate.setPlaceholders(player, getArgs(2));
TagDataHandler.getHandler().setDisplay(player, value);
TagAPI.setPlayerDisplayName(player, value);
if (sender instanceof Player) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-DISPLAY-SET", args[1], value);
}

View File

@ -1,9 +1,8 @@
package me.skymc.taboolib.commands.taboolib;
import com.ilummc.tlib.resources.TLocale;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.team.TagManager;
import me.skymc.taboolib.itagapi.TagDataHandler;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -14,28 +13,25 @@ import org.bukkit.entity.Player;
*/
public class TagPrefixCommand extends SubCommand {
public TagPrefixCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length < 3) {
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
return;
}
Player player = Bukkit.getPlayerExact(args[1]);
if (player == null) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.INVALID-PLAYER", args[1]);
return;
}
String value = getArgs(2).replace("&", "§");
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
value = PlaceholderAPI.setPlaceholders(player, value);
}
TagManager.getInst().setPrefix(player, value);
if (sender instanceof Player) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-PREFIX-SET", args[1], value);
}
}
public TagPrefixCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length < 3) {
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
return;
}
Player player = Bukkit.getPlayerExact(args[1]);
if (player == null) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.INVALID-PLAYER", args[1]);
return;
}
String value = TLocale.Translate.setPlaceholders(player, getArgs(2));
TagDataHandler.getHandler().setPrefix(player, value);
if (sender instanceof Player) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-PREFIX-SET", args[1], value);
}
}
}

View File

@ -1,9 +1,8 @@
package me.skymc.taboolib.commands.taboolib;
import com.ilummc.tlib.resources.TLocale;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.team.TagManager;
import me.skymc.taboolib.itagapi.TagDataHandler;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -27,12 +26,9 @@ public class TagSuffixCommand extends SubCommand {
return;
}
String value = getArgs(2).replace("&", "§");
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
value = PlaceholderAPI.setPlaceholders(player, value);
}
TagManager.getInst().setSuffix(player, value);
String value = TLocale.Translate.setPlaceholders(player, getArgs(2));
TagDataHandler.getHandler().setSuffix(player, value);
if (sender instanceof Player) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-SUFFIX-SET", args[1], value);
}

View File

@ -1,6 +1,6 @@
package me.skymc.taboolib.inventory;
import com.ilummc.tlib.resources.TLocale;
import lombok.Getter;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
@ -9,6 +9,7 @@ import me.skymc.taboolib.itemnbtapi.NBTItem;
import me.skymc.taboolib.itemnbtapi.NBTList;
import me.skymc.taboolib.itemnbtapi.NBTListCompound;
import me.skymc.taboolib.itemnbtapi.NBTType;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.string.Language;
import org.bukkit.Color;
@ -28,235 +29,226 @@ import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.IntStream;
public class ItemUtils {
private static FileConfiguration itemdir = null;
private static FileConfiguration itemCache = null;
private static File finalItemsFolder;
private static LinkedHashMap<String, String> itemlib = new LinkedHashMap<>();
private static LinkedHashMap<String, ItemStack> itemCaches = new LinkedHashMap<>();
private static LinkedHashMap<String, ItemStack> itemCachesFinal = new LinkedHashMap<>();
public static FileConfiguration getItemdir() {
return itemdir;
}
public static FileConfiguration getItemCache() {
return itemCache;
}
public static File getFinalItemsFolder() {
return finalItemsFolder;
}
public static LinkedHashMap<String, String> getItemlib() {
return itemlib;
}
public static LinkedHashMap<String, ItemStack> getItemCaches() {
return itemCaches;
}
public static LinkedHashMap<String, ItemStack> getItemCachesFinal() {
return itemCachesFinal;
}
/**
* 获取物品缓存
* 检测顺序
* 1. 固定物品库
* 2. 动态物品库
*
* @param name 物品名称
* @return
*/
public static ItemStack getCacheItem(String name) {
// 检测固定物品库是否存在该物品
if (itemCachesFinal.containsKey(name)) {
return itemCachesFinal.get(name);
}
// 返回动态物品库
return itemCaches.get(name);
}
public static boolean isExists(String name) {
return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name);
}
public static void LoadLib() {
try {
reloadItemName();
reloadItemCache();
itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR")));
} catch (Exception e) {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ITEMS", e.toString());
}
}
public static void loadItemsFile(File file, boolean finalFile) {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), file);
for (String name : conf.getConfigurationSection("").getKeys(false)) {
if (isExists(name)) {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ITEMS", name);
} else if (finalFile) {
itemCachesFinal.put(name, loadItem(conf, name));
} else {
itemCaches.put(name, loadItem(conf, name));
}
}
}
public static void reloadItemCache() {
itemCaches.clear();
itemCachesFinal.clear();
loadItemsFile(getItemCacheFile(), false);
// 创建固定物品库
finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems");
if (!finalItemsFolder.exists()) {
finalItemsFolder.mkdir();
}
// 检查固定物品库中的物品
Arrays.stream(finalItemsFolder.listFiles()).forEach(file -> loadItemsFile(file, true));
TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-CACHES", String.valueOf(itemCaches.size() + itemCachesFinal.size()));
}
public static void reloadItemName() {
FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration();
itemlib.clear();
conf.getConfigurationSection("").getKeys(false).forEach(a -> itemlib.put(a, conf.getString(a)));
TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-NAMES", String.valueOf(itemlib.size()));
}
public static File getItemCacheFile() {
File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml");
if (!itemCacheFile.exists()) {
Main.getInst().saveResource("items.yml", true);
}
return itemCacheFile;
}
public static String getCustomName(ItemStack item) {
if (item == null || item.getType().equals(Material.AIR)) {
return TLocale.asString("ITEM-UTILS.EMPTY-ITEM");
}
int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0;
return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data);
}
public static ItemStack getItemFromDir(String name) {
if (itemdir != null) {
return itemdir.getItemStack("item." + name);
}
return null;
}
@SuppressWarnings("deprecation")
@Getter
private static FileConfiguration itemdir = null;
@Getter
private static FileConfiguration itemCache = null;
@Getter
private static File finalItemsFolder;
@Getter
private static LinkedHashMap<String, String> itemlib = new LinkedHashMap<>();
@Getter
private static LinkedHashMap<String, ItemStack> itemCaches = new LinkedHashMap<>();
@Getter
private static LinkedHashMap<String, ItemStack> itemCachesFinal = new LinkedHashMap<>();
/**
* 获取物品缓存
* 检测顺序
* 1. 固定物品库
* 2. 动态物品库
*
* @param name 物品名称
* @return
*/
public static ItemStack getCacheItem(String name) {
// 检测固定物品库是否存在该物品
if (itemCachesFinal.containsKey(name)) {
return itemCachesFinal.get(name);
}
// 返回动态物品库
return itemCaches.get(name);
}
public static boolean isExists(String name) {
return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name);
}
public static void LoadLib() {
try {
reloadItemName();
reloadItemCache();
itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR")));
} catch (Exception e) {
MsgUtils.warn("物品库载入失败: &4" + e.getMessage());
}
}
public static void loadItemsFile(File file, boolean finalFile) {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), file);
for (String name : conf.getConfigurationSection("").getKeys(false)) {
if (isExists(name)) {
MsgUtils.warn("无法载入载入物品 &4" + name + "&c, 因为它已经存在了");
} else if (finalFile) {
itemCachesFinal.put(name, loadItem(conf, name));
} else {
itemCaches.put(name, loadItem(conf, name));
}
}
}
public static void reloadItemCache() {
itemCaches.clear();
itemCachesFinal.clear();
loadItemsFile(getItemCacheFile(), false);
// 创建固定物品库
finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems");
if (!finalItemsFolder.exists()) {
finalItemsFolder.mkdir();
}
// 检查固定物品库中的物品
for (File file : finalItemsFolder.listFiles()) {
loadItemsFile(file, true);
}
MsgUtils.send("载入 " + (itemCaches.size() + itemCachesFinal.size()) + " 项缓存物品");
}
public static void reloadItemName() {
FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration();
itemlib.clear();
for (String a : conf.getConfigurationSection("").getKeys(false)) {
itemlib.put(a, conf.getString(a));
}
MsgUtils.send("载入 " + itemlib.size() + " 项物品名称");
}
public static File getItemCacheFile() {
File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml");
if (!itemCacheFile.exists()) {
Main.getInst().saveResource("items.yml", true);
}
return itemCacheFile;
}
public static String getCustomName(ItemStack item) {
if (item == null || item.getType().equals(Material.AIR)) {
return "";
}
int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0;
return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data);
}
public static ItemStack getItemFromDir(String name) {
if (itemdir != null) {
return itemdir.getItemStack("item." + name);
}
return null;
}
@SuppressWarnings("deprecation")
public static ItemStack item(int n, int a, int d) {
return new ItemStack(n, a, (short) d);
}
public static ItemStack setName(ItemStack i, String n) {
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(n);
i.setItemMeta(meta);
return i;
}
public static ItemStack Enchant(ItemStack i, Enchantment e, int l) {
ItemMeta meta = i.getItemMeta();
meta.addEnchant(e, l, false);
i.setItemMeta(meta);
return i;
}
public static ItemStack addFlag(ItemStack i, ItemFlag f) {
ItemMeta meta = i.getItemMeta();
meta.addItemFlags(f);
i.setItemMeta(meta);
return i;
}
public static boolean isNull(ItemStack item) {
return item == null || item.getType().equals(Material.AIR);
return item == null || item.getType().equals(Material.AIR);
}
public static boolean isName(ItemStack i, String a) {
return isNamed(i) && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null && i.getItemMeta().getDisplayName().equals(a);
}
public static boolean isNameAs(ItemStack i, String a) {
return isNamed(i) && i.getItemMeta().getDisplayName().contains(a);
}
public static String asString(String args, Player placeholderPlayer) {
if (placeholderPlayer == null) {
return args.replace("&", "§");
}
return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§"));
if (placeholderPlayer == null) {
return args.replace("&", "§");
}
return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§"));
}
public static List<String> asString(List<String> args, Player placeholderPlayer) {
IntStream.range(0, args.size()).forEach(i -> args.set(i, asString(args.get(i), placeholderPlayer)));
return args;
for (int i = 0 ; i < args.size() ; i ++) {
args.set(i, asString(args.get(i), placeholderPlayer));
}
return args;
}
public static ItemFlag asItemFlag(String flag) {
try {
return ItemFlag.valueOf(flag);
} catch (Exception e) {
return null;
}
try {
return ItemFlag.valueOf(flag);
}
catch (Exception e) {
return null;
}
}
@SuppressWarnings("deprecation")
public static Material asMaterial(String args) {
try {
Material material = Material.getMaterial(args);
return material != null ? material : Material.getMaterial(Integer.valueOf(args));
} catch (Exception e) {
return Material.STONE;
}
public static Material asMaterial(String args) {
try {
Material material = Material.getMaterial(args);
return material != null ? material : Material.getMaterial(Integer.valueOf(args));
}
catch (Exception e) {
return Material.STONE;
}
}
@SuppressWarnings({ "deprecation" })
public static Enchantment asEnchantment(String enchant) {
try {
Enchantment enchantment = Enchantment.getByName(enchant);
return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant));
}
catch (Exception e) {
return null;
}
}
@SuppressWarnings({"deprecation"})
public static Enchantment asEnchantment(String enchant) {
try {
Enchantment enchantment = Enchantment.getByName(enchant);
return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant));
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("deprecation")
public static PotionEffectType asPotionEffectType(String potion) {
try {
PotionEffectType type = PotionEffectType.getByName(potion);
return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion));
} catch (Exception e) {
return null;
}
public static PotionEffectType asPotionEffectType(String potion) {
try {
PotionEffectType type = PotionEffectType.getByName(potion);
return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion));
}
catch (Exception e) {
return null;
}
}
public static Color asColor(String color) {
try {
return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2]));
} catch (Exception e) {
return Color.fromBGR(0, 0, 0);
}
try {
return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2]));
}
catch (Exception e) {
return Color.fromBGR(0, 0, 0);
}
}
public static String asAttribute(String name) {
switch (name.toLowerCase()) {
case "damage":
@ -273,292 +265,321 @@ public class ItemUtils {
return "generic.armor";
case "luck":
return "generic.luck";
default:
return null;
}
return null;
}
/**
* 包含介绍
*
*
* @param i 物品
* @param a 关键字
*/
public static boolean hasLore(ItemStack i, String a) {
return isLored(i) && i.getItemMeta().getLore().toString().contains(a);
}
/**
* 如果已描述
*
*
* @param i
* @return
*/
public static boolean isLored(ItemStack i) {
return i != null && i.getItemMeta() != null && i.getItemMeta().getLore() != null;
}
/**
* 如果已命名
*
*
* @param i
* @return
*/
public static boolean isNamed(ItemStack i) {
public static boolean isNamed(ItemStack i) {
return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null;
}
/**
* 添加描述
*
* @param is 物品
*
* @param is 物品
* @param lore 描述
*/
public static ItemStack addLore(ItemStack is, String lore) {
ItemMeta meta = is.getItemMeta();
List<String> _lore = meta.hasLore() ? meta.getLore() : Collections.emptyList();
_lore.add(lore.replaceAll("&", "§"));
ItemMeta meta = is.getItemMeta();
List<String> _lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
_lore.add(lore.replaceAll("&", "§"));
is.setItemMeta(meta);
return is;
}
/**
* 移除描述
*
* @param is 物品
*
* @param is 物品
* @param line 行数
*/
public static ItemStack delLore(ItemStack is, int line) {
ItemMeta meta = is.getItemMeta();
ItemMeta meta = is.getItemMeta();
if (meta.hasLore()) {
List<String> l = meta.getLore();
if (l.size() >= line) {
l.remove(line);
meta.setLore(l);
is.setItemMeta(meta);
}
List<String> l = meta.getLore();
if (l.size() >= line) {
l.remove(line);
meta.setLore(l);
is.setItemMeta(meta);
}
}
return is;
}
/**
* 获取介绍所在行数
*
*
* @param i 物品
* @param a 关键字
*/
public static int getLore(ItemStack i, String a) {
return isLored(i) ? IntStream.range(0, i.getItemMeta().getLore().size()).filter(j -> i.getItemMeta().getLore().get(j).contains(a)).findFirst().orElse(0) : 0;
if (isLored(i)) {
for (int j = 0; j < i.getItemMeta().getLore().size() ; j++) {
if (i.getItemMeta().getLore().get(j).contains(a)) {
return j;
}
}
}
return 0;
}
/**
* 添加耐久
*
*
* @param i 物品
* @param d 耐久
*/
public static ItemStack addDurability(ItemStack i, int d) {
i.setDurability((short) (i.getDurability() + d));
int min = i.getDurability();
int max = i.getType().getMaxDurability();
if (min >= max) {
i.setType(Material.AIR);
}
return i;
i.setDurability((short) (i.getDurability() + d));
int min = i.getDurability();
int max = i.getType().getMaxDurability();
if (min >= max) {
i.setType(Material.AIR);
}
return i;
}
/**
* 替换描述
*
* @param i 物品
*
* @param i 物品
* @param l1 关键字1
* @param l2 关键字2
*/
public static ItemStack repalceLore(ItemStack i, String l1, String l2) {
if (!isLored(i)) {
return i;
} else {
ItemMeta meta = i.getItemMeta();
List<String> lore = meta.getLore();
IntStream.range(0, lore.size()).forEach(j -> lore.set(j, lore.get(j).replace(l1, l2)));
meta.setLore(lore);
i.setItemMeta(meta);
}
return i;
if (!isLored(i)) {
return i;
}
else {
ItemMeta meta = i.getItemMeta();
List<String> lore = meta.getLore();
for (int j = 0 ; j < lore.size() ; j++) {
lore.set(j, lore.get(j).replace(l1, l2));
}
meta.setLore(lore);
i.setItemMeta(meta);
}
return i;
}
public static ItemStack loadItem(FileConfiguration f, String s) {
return loadItem(f, s, null);
return loadItem(f, s, null);
}
public static ItemStack loadItem(FileConfiguration f, String s, Player papiPlayer) {
return loadItem(f.getConfigurationSection(s), papiPlayer);
return loadItem(f.getConfigurationSection(s), papiPlayer);
}
public static ItemStack loadItem(ConfigurationSection section, Player papiPlayer) {
if (section.get("bukkit") instanceof ItemStack) {
return section.getItemStack("bukkit");
}
// 材质
ItemStack item = new ItemStack(asMaterial(section.get("material").toString()));
// 数量
item.setAmount(section.contains("amount") ? section.getInt("amount") : 1);
// 耐久
item.setDurability((short) section.getInt("data"));
// 元数据
ItemMeta meta = item.getItemMeta();
// 展示名
if (section.contains("name")) {
meta.setDisplayName(asString(section.getString("name"), papiPlayer));
}
// 描述
if (section.contains("lore")) {
meta.setLore(asString(section.getStringList("lore"), papiPlayer));
}
// 附魔
if (section.contains("enchants")) {
for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) {
Enchantment enchant = asEnchantment(preEnchant);
if (enchant != null) {
meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true);
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ENCHANTS", preEnchant);
}
}
}
// 标签
if (section.contains("flags") && TabooLib.getVerint() > 10700) {
for (String preFlag : section.getStringList("flags")) {
ItemFlag flag = asItemFlag(preFlag);
if (flag != null) {
meta.addItemFlags(flag);
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-FLAG", preFlag);
}
}
}
// 皮革
if (meta instanceof LeatherArmorMeta && section.contains("color")) {
((LeatherArmorMeta) meta).setColor(asColor(section.getString("color")));
}
// 药水
if (meta instanceof PotionMeta && section.contains("potions")) {
PotionMeta potionMeta = (PotionMeta) meta;
for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) {
PotionEffectType potionEffectType = asPotionEffectType(prePotionName);
if (potionEffectType != null) {
potionMeta.addCustomEffect(new PotionEffect(
potionEffectType,
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]),
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true);
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", prePotionName);
}
}
}
// 元数据
item.setItemMeta(meta);
// 数据
NBTItem nbt = new NBTItem(item);
// 物品标签
if (section.contains("nbt")) {
for (String name : section.getConfigurationSection("nbt").getKeys(false)) {
Object obj = section.get("nbt." + name);
if (obj instanceof String) {
nbt.setString(name, obj.toString());
} else if (obj instanceof Double) {
nbt.setDouble(name, Double.valueOf(obj.toString()));
} else if (obj instanceof Integer) {
nbt.setInteger(name, Integer.valueOf(obj.toString()));
} else if (obj instanceof Long) {
nbt.setLong(name, Long.valueOf(obj.toString()));
} else {
nbt.setObject(name, obj);
}
}
}
// 物品属性
if (section.contains("attributes")) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
for (String hand : section.getConfigurationSection("attributes").getKeys(false)) {
for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) {
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = attr.addCompound();
Object num = section.get("attributes." + hand + "." + name);
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
} else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_attr.setInteger("Operation", 0);
}
_attr.setString("AttributeName", asAttribute(name));
_attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
_attr.setString("Name", asAttribute(name));
if (!"all".equals(hand)) {
_attr.setString("Slot", hand);
}
} catch (Exception ignored) {
}
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name);
}
}
}
}
return nbt.getItem();
if (section.get("bukkit") instanceof ItemStack) {
return section.getItemStack("bukkit");
}
// 材质
ItemStack item = new ItemStack(asMaterial(section.get("material").toString()));
// 数量
item.setAmount(section.contains("amount") ? section.getInt("amount") : 1);
// 耐久
item.setDurability((short) section.getInt("data"));
// 元数据
ItemMeta meta = item.getItemMeta();
// 展示名
if (section.contains("name")) {
meta.setDisplayName(asString(section.getString("name"), papiPlayer));
}
// 描述
if (section.contains("lore")) {
meta.setLore(asString(section.getStringList("lore"), papiPlayer));
}
// 附魔
if (section.contains("enchants")) {
for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) {
Enchantment enchant = asEnchantment(preEnchant);
if (enchant != null) {
meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true);
}
else {
MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称");
MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔");
}
}
}
// 标签
if (section.contains("flags") && TabooLib.getVerint() > 10700) {
for (String preFlag : section.getStringList("flags")) {
ItemFlag flag = asItemFlag(preFlag);
if (flag != null) {
meta.addItemFlags(flag);
}
else {
MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称");
MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签");
}
}
}
// 皮革
if (meta instanceof LeatherArmorMeta && section.contains("color")) {
((LeatherArmorMeta) meta).setColor(asColor(section.getString("color")));
}
// 药水
if (meta instanceof PotionMeta && section.contains("potions")) {
PotionMeta potionMeta = (PotionMeta) meta;
for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) {
PotionEffectType potionEffectType = asPotionEffectType(prePotionName);
if (potionEffectType != null) {
potionMeta.addCustomEffect(new PotionEffect(
potionEffectType,
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]),
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true);
}
else {
MsgUtils.warn("&8" + potionEffectType + " &c不是一个有效的药水名称");
MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水");
}
}
}
// 元数据
item.setItemMeta(meta);
// 数据
NBTItem nbt = new NBTItem(item);
// 物品标签
if (section.contains("nbt")) {
for (String name : section.getConfigurationSection("nbt").getKeys(false)) {
Object obj = section.get("nbt." + name);
if (obj instanceof String) {
nbt.setString(name, obj.toString());
}
else if (obj instanceof Double) {
nbt.setDouble(name, Double.valueOf(obj.toString()));
}
else if (obj instanceof Integer) {
nbt.setInteger(name, Integer.valueOf(obj.toString()));
}
else if (obj instanceof Long) {
nbt.setLong(name, Long.valueOf(obj.toString()));
}
else {
nbt.setObject(name, obj);
}
}
}
// 物品属性
if (section.contains("attributes")) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
for (String hand : section.getConfigurationSection("attributes").getKeys(false)) {
for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) {
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = attr.addCompound();
Object num = section.get("attributes." + hand + "." + name);
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
}
else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_attr.setInteger("Operation", 0);
}
_attr.setString("AttributeName", asAttribute(name));
_attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setString("Name", asAttribute(name));
if (!hand.equals("all")) {
_attr.setString("Slot", hand);
}
}
catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
}
}
else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
}
}
}
}
return nbt.getItem();
}
public static NBTItem setAttribute(NBTItem nbt, String name, Object num, String hand) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = null;
for (int i = 0; i < attr.size(); i++) {
NBTListCompound nlc = attr.getCompound(i);
if (nlc.getString("AttributeName").equals(asAttribute(name))) {
_attr = nlc;
}
}
if (_attr == null) {
_attr = attr.addCompound();
}
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
} else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_attr.setInteger("Operation", 0);
}
_attr.setString("AttributeName", asAttribute(name));
_attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
_attr.setString("Name", asAttribute(name));
if (!"all".equals(hand)) {
_attr.setString("Slot", hand);
}
} catch (NumberFormatException ignored) {
}
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name);
}
return nbt;
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = null;
for (int i = 0 ; i < attr.size() ; i++) {
NBTListCompound nlc = attr.getCompound(i);
if (nlc.getString("AttributeName").equals(asAttribute(name))) {
_attr = nlc;
}
}
if (_attr == null) {
_attr = attr.addCompound();
}
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
}
else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_attr.setInteger("Operation", 0);
}
_attr.setString("AttributeName", asAttribute(name));
_attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setString("Name", asAttribute(name));
if (!hand.equals("all")) {
_attr.setString("Slot", hand);
}
}
catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
}
}
else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
}
return nbt;
}
@Deprecated
public static void putO(ItemStack item, Inventory inv, int i) {
inv.setItem(i, item);
inv.setItem(i + 1, item);
inv.setItem(i + 2, item);
inv.setItem(i + 9, item);
inv.setItem(i + 10, null);
inv.setItem(i + 11, item);
inv.setItem(i + 18, item);
inv.setItem(i + 19, item);
inv.setItem(i + 20, item);
}
inv.setItem(i, item);
inv.setItem(i+1, item);
inv.setItem(i+2, item);
inv.setItem(i+9, item);
inv.setItem(i+10, null);
inv.setItem(i+11, item);
inv.setItem(i+18, item);
inv.setItem(i+19, item);
inv.setItem(i+20, item);
}
}

View File

@ -0,0 +1,191 @@
package me.skymc.taboolib.itagapi;
import com.google.common.base.Preconditions;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.packet.PacketUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import java.util.HashMap;
import java.util.UUID;
/**
* @Author sky
* @Since 2018-05-23 0:37
*/
public class TagDataHandler implements Listener {
private static TagDataHandler handler;
private HashMap<UUID, TagPlayerData> playersData = new HashMap<>();
public static void init(Plugin plugin) {
Preconditions.checkArgument(handler == null, "TagDataHandler is already instanced!");
handler = new TagDataHandler();
// 注册监听
Bukkit.getPluginManager().registerEvents(handler, plugin);
// 启动相关功能
new BukkitRunnable() {
@Override
public void run() {
if (PacketUtils.isProtocolLibEnabled()) {
TagPacket.inst();
}
}
}.runTask(plugin);
}
public TagPlayerData unregisterPlayerData(Player player) {
return playersData.remove(player.getUniqueId());
}
public TagPlayerData getPlayerData(Player player) {
return playersData.get(player.getUniqueId());
}
public TagPlayerData getPlayerDataComputeIfAbsent(Player player) {
return playersData.computeIfAbsent(player.getUniqueId(), x -> new TagPlayerData(player));
}
public String getPrefix(Player player) {
return getPlayerDataComputeIfAbsent(player).getPrefix();
}
public String getSuffix(Player player) {
return getPlayerDataComputeIfAbsent(player).getSuffix();
}
public String getDisplay(Player player) {
return getPlayerDataComputeIfAbsent(player).getNameDisplay();
}
public void setPrefix(Player player, String prefix) {
updatePlayerVariable(getPlayerDataComputeIfAbsent(player).setPrefix(prefix));
updatePlayerListName(player);
}
public void setSuffix(Player player, String suffix) {
updatePlayerVariable(getPlayerDataComputeIfAbsent(player).setSuffix(suffix));
updatePlayerListName(player);
}
public void setPrefixAndSuffix(Player player, String prefix, String suffix) {
updatePlayerVariable(getPlayerDataComputeIfAbsent(player).setPrefix(prefix).setSuffix(suffix));
updatePlayerListName(player);
}
public void setDisplay(Player player, String display) {
TagPlayerData playerData = getPlayerDataComputeIfAbsent(player);
cancelPlayerVariable(player, playerData);
player.setDisplayName(playerData.setNameDisplay(display).getNameDisplay());
updatePlayerVariable(playerData);
updatePlayerListName(player);
Bukkit.getScheduler().runTask(Main.getInst(), () -> TagPacket.refreshPlayer(player));
}
public void resetVariable(Player player) {
updatePlayerVariable(getPlayerDataComputeIfAbsent(player).reset());
updatePlayerListName(player);
}
public void resetDisplay(Player player) {
setDisplay(player, player.getName());
}
public void reset(Player player) {
updatePlayerVariable(getPlayerDataComputeIfAbsent(player).reset());
setDisplay(player, player.getName());
}
// *********************************
//
// Private Methods
//
// *********************************
private void downloadPlayerVariable(Player player) {
Scoreboard scoreboard = TagUtils.getScoreboardComputeIfAbsent(player);
playersData.values().forEach(playerData -> updateTeamVariable(scoreboard, playerData));
}
private void updatePlayerVariable(TagPlayerData playerData) {
Bukkit.getOnlinePlayers().forEach(online -> updateTeamVariable(TagUtils.getScoreboardComputeIfAbsent(online), playerData));
}
private void updatePlayerListName(Player player) {
TagPlayerData playerData = getPlayerDataComputeIfAbsent(player);
player.setPlayerListName(!playerData.getNameDisplay().equals(player.getName()) ? playerData.getPrefix() + playerData.getNameDisplay() + playerData.getSuffix() : playerData.getNameDisplay());
}
private void updateTeamVariable(Scoreboard scoreboard, TagPlayerData playerData) {
Team entryTeam = TagUtils.getTeamComputeIfAbsent(scoreboard, playerData.getTeamHash());
entryTeam.addEntry(playerData.getNameDisplay());
entryTeam.setPrefix(playerData.getPrefix());
entryTeam.setSuffix(playerData.getSuffix());
TagUtils.cleanEmptyTeamInScoreboard(scoreboard);
}
private void cancelPlayerVariable(Player player, TagPlayerData playerData) {
if (playerData == null) {
return;
}
for (Player online : Bukkit.getOnlinePlayers()) {
Scoreboard scoreboard = TagUtils.getScoreboardComputeIfAbsent(player);
TagUtils.cleanEntryInScoreboard(scoreboard, playerData.getNameDisplay());
TagUtils.cleanEmptyTeamInScoreboard(scoreboard);
}
}
// *********************************
//
// Listeners
//
// *********************************
@EventHandler
public void onJoin(PlayerJoinEvent e) {
downloadPlayerVariable(e.getPlayer());
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
cancelPlayerVariable(e.getPlayer(), unregisterPlayerData(e.getPlayer()));
}
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent e) {
if (e.getMessage().equalsIgnoreCase("/scoreboardinfo") && e.getPlayer().hasPermission("itagapi.info")) {
e.setCancelled(true);
e.getPlayer().sendMessage("§7计分板信息:");
Scoreboard scoreboard = TagUtils.getScoreboardComputeIfAbsent(e.getPlayer());
for (Team team : scoreboard.getTeams()) {
e.getPlayer().sendMessage("§7队伍: §f" + team.getName());
e.getPlayer().sendMessage("§f - §7前缀: §f" + team.getPrefix());
e.getPlayer().sendMessage("§f - §7后缀: §f" + team.getSuffix());
e.getPlayer().sendMessage("§f - §7成员: §f");
team.getEntries().forEach(entry -> e.getPlayer().sendMessage("§f - §f" + entry));
}
}
}
// *********************************
//
// Getter and Setter
//
// *********************************
public static TagDataHandler getHandler() {
return handler;
}
}

View File

@ -0,0 +1,136 @@
package me.skymc.taboolib.itagapi;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.EnumWrappers;
import com.comphenix.protocol.wrappers.PlayerInfoData;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.google.common.base.Preconditions;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.events.itag.AsyncPlayerReceiveNameTagEvent;
import me.skymc.taboolib.events.itag.PlayerReceiveNameTagEvent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.*;
import java.util.stream.IntStream;
/**
* @Author sky
* @Since 2018-05-09 21:03
*/
class TagPacket implements Listener {
private static final int[] uuidSplit = new int[]{0, 8, 12, 16, 20, 32};
private static boolean loaded = false;
private static HashMap<Integer, Player> entityIdMap = new HashMap<>();
TagPacket() {
}
public static void inst() {
assert !loaded : "TagAPI is already instanced!";
loaded = true;
Bukkit.getServer().getOnlinePlayers().forEach(player -> entityIdMap.put(player.getEntityId(), player));
Bukkit.getPluginManager().registerEvents(new TagPacket(), Main.getInst());
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(Main.getInst(), PacketType.Play.Server.PLAYER_INFO) {
@Override
public void onPacketSending(PacketEvent event) {
if (event.getPacket().getPlayerInfoAction().read(0) != EnumWrappers.PlayerInfoAction.ADD_PLAYER) {
return;
}
List<PlayerInfoData> newPlayerInfo = new ArrayList<>();
for (PlayerInfoData playerInfo : event.getPacket().getPlayerInfoDataLists().read(0)) {
Player player;
if (playerInfo == null || playerInfo.getProfile() == null || (player = Bukkit.getServer().getPlayer(playerInfo.getProfile().getUUID())) == null) {
// Unknown Player
newPlayerInfo.add(playerInfo);
continue;
}
newPlayerInfo.add(new PlayerInfoData(getSentName(player.getEntityId(), playerInfo.getProfile(), event.getPlayer()), playerInfo.getPing(), playerInfo.getGameMode(), playerInfo.getDisplayName()));
}
event.getPacket().getPlayerInfoDataLists().write(0, newPlayerInfo);
}
});
}
static String getPlayerDisplayName(Player player) {
return TagDataHandler.getHandler().getPlayerDataComputeIfAbsent(player).getNameDisplay();
}
static void refreshPlayer(Player player) {
Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!");
Preconditions.checkNotNull(player, "player");
player.getWorld().getPlayers().forEach(playerFor -> refreshPlayer(player, playerFor));
}
static void refreshPlayer(final Player player, final Player forWhom) {
Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!");
Preconditions.checkNotNull(player, "player");
Preconditions.checkNotNull(forWhom, "forWhom");
if (player != forWhom && player.getWorld() == forWhom.getWorld() && forWhom.canSee(player)) {
forWhom.hidePlayer(player);
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.getInst(), () -> forWhom.showPlayer(player), 2);
}
}
static void refreshPlayer(Player player, Set<Player> forWhom) {
Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!");
Preconditions.checkNotNull(player, "player");
Preconditions.checkNotNull(forWhom, "forWhom");
forWhom.forEach(playerFor -> refreshPlayer(player, playerFor));
}
private static WrappedGameProfile getSentName(int sentEntityId, WrappedGameProfile sent, Player destinationPlayer) {
Preconditions.checkState(Bukkit.getServer().isPrimaryThread(), "Can only process events on main thread.");
Player namedPlayer = entityIdMap.get(sentEntityId);
if (namedPlayer == null) {
// They probably were dead when we reloaded
return sent;
}
PlayerReceiveNameTagEvent oldEvent = new PlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, sent.getName());
Bukkit.getServer().getPluginManager().callEvent(oldEvent);
StringBuilder builtUUID = new StringBuilder();
if (!sent.getId().contains("-")) {
IntStream.range(0, uuidSplit.length - 1).forEach(i -> builtUUID.append(sent.getId(), uuidSplit[i], uuidSplit[i + 1]).append("-"));
} else {
builtUUID.append(sent.getId());
}
AsyncPlayerReceiveNameTagEvent newEvent = new AsyncPlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, getPlayerDisplayName(namedPlayer), UUID.fromString(builtUUID.toString()));
Bukkit.getServer().getPluginManager().callEvent(newEvent);
return new WrappedGameProfile(newEvent.getUUID(), newEvent.getTag().substring(0, Math.min(newEvent.getTag().length(), 16)));
}
// *********************************
//
// Listeners
//
// *********************************
@EventHandler
public void onJoin(PlayerJoinEvent event) {
entityIdMap.put(event.getPlayer().getEntityId(), event.getPlayer());
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
entityIdMap.remove(event.getPlayer().getEntityId());
}
}

View File

@ -0,0 +1,84 @@
package me.skymc.taboolib.itagapi;
import com.ilummc.tlib.util.Strings;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.Objects;
import java.util.UUID;
/**
* @Author sky
* @Since 2018-05-21 15:07
*/
public class TagPlayerData {
private final UUID uuid;
private String nameDisplay;
private String prefix;
private String suffix;
public TagPlayerData(Player player) {
this.uuid = player.getUniqueId();
this.nameDisplay = player.getName();
this.prefix = "";
this.suffix = "";
}
public String getTeamHash() {
return String.valueOf(Objects.hash(prefix));
}
public TagPlayerData reset() {
this.nameDisplay = getNameOrigin();
this.prefix = "";
this.suffix = "";
return this;
}
@Override
public String toString() {
return Strings.replaceWithOrder("TagPlayerData'{'uuid={0}, nameDisplay=''{1}'', prefix=''{2}'', suffix=''{3}'''}'", uuid, nameDisplay, prefix, suffix);
}
// *********************************
//
// Getter and Setter
//
// *********************************
public UUID getUUID() {
return uuid;
}
public String getNameOrigin() {
return Bukkit.getPlayer(uuid).getName();
}
public String getNameDisplay() {
return nameDisplay == null ? "" : nameDisplay;
}
public String getPrefix() {
return prefix == null ? "" : prefix;
}
public String getSuffix() {
return suffix == null ? "" : suffix;
}
public TagPlayerData setNameDisplay(String nameDisplay) {
this.nameDisplay = nameDisplay.length() > 16 ? nameDisplay.substring(0, 16) : nameDisplay;
return this;
}
public TagPlayerData setPrefix(String prefix) {
this.prefix = prefix.length() > 16 ? prefix.substring(0, 16) : prefix;
return this;
}
public TagPlayerData setSuffix(String suffix) {
this.suffix = suffix.length() > 16 ? suffix.substring(0, 16) : suffix;
return this;
}
}

View File

@ -0,0 +1,62 @@
package me.skymc.taboolib.itagapi;
import com.ilummc.tlib.logger.TLogger;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import java.util.Optional;
/**
* @Author sky
* @Since 2018-05-21 15:09
*/
public class TagUtils {
public static void cleanTeamInScoreboard(Scoreboard scoreboard) {
try {
scoreboard.getTeams().forEach(Team::unregister);
} catch (Exception e) {
TLogger.getGlobalLogger().error("TagUtils.cleanTeamInScoreboard() 异常: " + e.toString());
}
}
public static void cleanEntryInScoreboard(Scoreboard scoreboard, String entry) {
try {
Optional.ofNullable(scoreboard.getEntryTeam(entry)).ifPresent(x -> x.removeEntry(entry));
} catch (Exception e) {
TLogger.getGlobalLogger().error("TagUtils.cleanEntryInScoreboard() 异常: " + e.toString());
}
}
public static void cleanEmptyTeamInScoreboard(Scoreboard scoreboard) {
try {
scoreboard.getTeams().stream().filter(team -> team.getEntries().size() == 0).forEach(Team::unregister);
} catch (Exception e) {
TLogger.getGlobalLogger().error("TagUtils.cleanEmptyTeamInScoreboard() 异常: " + e.toString());
}
}
public static Scoreboard getScoreboardComputeIfAbsent(Player player) {
Scoreboard scoreboard = player.getScoreboard();
if (scoreboard == null) {
player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
return player.getScoreboard();
}
public static Scoreboard getScoreboardAndCleanTeams(Player player) {
Scoreboard scoreboard = getScoreboardComputeIfAbsent(player);
cleanTeamInScoreboard(scoreboard);
return scoreboard;
}
public static Team getTeamComputeIfAbsent(Scoreboard scoreboard, String teamName) {
Team team = scoreboard.getTeam(teamName);
if (team == null) {
scoreboard.registerNewTeam(teamName);
}
return scoreboard.getTeam(teamName);
}
}

View File

@ -313,7 +313,7 @@ public class NMSUtil18 {
class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class);
class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class);
class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE);
class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", org.bukkit.inventory.ItemStack.class);
class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", ItemStack.class);
class_CraftItemStack_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack);
class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack);
class_ItemStack_createStackMethod = class_ItemStack.getMethod("createStack", class_NBTTagCompound);
@ -526,7 +526,7 @@ public class NMSUtil18 {
return NMSUtil18.class.getClassLoader().loadClass(className);
}
public static Object getHandle(org.bukkit.inventory.ItemStack stack) {
public static Object getHandle(ItemStack stack) {
Object handle = null;
try {
handle = class_CraftItemStack_getHandleField.get(stack);
@ -536,7 +536,7 @@ public class NMSUtil18 {
return handle;
}
public static Object getHandle(org.bukkit.World world) {
public static Object getHandle(World world) {
if (world == null) {
return null;
}
@ -549,7 +549,7 @@ public class NMSUtil18 {
return handle;
}
public static Object getHandle(org.bukkit.entity.Entity entity) {
public static Object getHandle(Entity entity) {
if (entity == null) {
return null;
}
@ -575,7 +575,7 @@ public class NMSUtil18 {
return handle;
}
public static boolean isDone(org.bukkit.Chunk chunk) {
public static boolean isDone(Chunk chunk) {
Object chunkHandle = getHandle(chunk);
boolean done = false;
try {
@ -586,7 +586,7 @@ public class NMSUtil18 {
return done;
}
public static Object getHandle(org.bukkit.Chunk chunk) {
public static Object getHandle(Chunk chunk) {
Object handle = null;
try {
handle = class_CraftChunk_getHandleMethod.invoke(chunk);
@ -596,7 +596,7 @@ public class NMSUtil18 {
return handle;
}
public static Object getHandle(org.bukkit.entity.Player player) {
public static Object getHandle(Player player) {
Object handle = null;
try {
handle = class_CraftPlayer_getHandleMethod.invoke(player);
@ -652,17 +652,17 @@ public class NMSUtil18 {
return dir;
}
public static org.bukkit.entity.Entity getBukkitEntity(Object entity) {
public static Entity getBukkitEntity(Object entity) {
if (entity == null) {
return null;
}
try {
Method getMethod = entity.getClass().getMethod("getBukkitEntity");
Object bukkitEntity = getMethod.invoke(entity);
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) {
if (!(bukkitEntity instanceof Entity)) {
return null;
}
return (org.bukkit.entity.Entity) bukkitEntity;
return (Entity) bukkitEntity;
} catch (Throwable ex) {
ex.printStackTrace();
}

View File

@ -377,7 +377,7 @@ public class NMSUtil19 {
class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class);
class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class);
class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE);
class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", org.bukkit.inventory.ItemStack.class);
class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", ItemStack.class);
class_CraftItemStack_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack);
class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack);
class_World_addEntityMethod = class_World.getMethod("addEntity", class_Entity, CreatureSpawnEvent.SpawnReason.class);
@ -931,7 +931,7 @@ public class NMSUtil19 {
return NMSUtils.class.getClassLoader().loadClass(className);
}
public static Object getHandle(org.bukkit.Server server) {
public static Object getHandle(Server server) {
Object handle = null;
try {
handle = class_CraftServer_getServerMethod.invoke(server);
@ -941,7 +941,7 @@ public class NMSUtil19 {
return handle;
}
public static Object getHandle(org.bukkit.inventory.ItemStack stack) {
public static Object getHandle(ItemStack stack) {
Object handle = null;
try {
handle = class_CraftItemStack_getHandleField.get(stack);
@ -951,7 +951,7 @@ public class NMSUtil19 {
return handle;
}
public static Object getHandle(org.bukkit.World world) {
public static Object getHandle(World world) {
if (world == null) {
return null;
}
@ -964,7 +964,7 @@ public class NMSUtil19 {
return handle;
}
public static Object getHandle(org.bukkit.entity.Entity entity) {
public static Object getHandle(Entity entity) {
if (entity == null) {
return null;
}
@ -990,7 +990,7 @@ public class NMSUtil19 {
return handle;
}
public static boolean isDone(org.bukkit.Chunk chunk) {
public static boolean isDone(Chunk chunk) {
Object chunkHandle = getHandle(chunk);
boolean done = false;
try {
@ -1001,7 +1001,7 @@ public class NMSUtil19 {
return done;
}
public static Object getHandle(org.bukkit.Chunk chunk) {
public static Object getHandle(Chunk chunk) {
Object handle = null;
try {
handle = class_CraftChunk_getHandleMethod.invoke(chunk);
@ -1011,7 +1011,7 @@ public class NMSUtil19 {
return handle;
}
public static Object getHandle(org.bukkit.entity.Player player) {
public static Object getHandle(Player player) {
Object handle = null;
try {
handle = class_CraftPlayer_getHandleMethod.invoke(player);
@ -1068,7 +1068,7 @@ public class NMSUtil19 {
return dir;
}
public static org.bukkit.entity.Entity getBukkitEntity(Object entity)
public static Entity getBukkitEntity(Object entity)
{
if (entity == null) {
return null;
@ -1076,10 +1076,10 @@ public class NMSUtil19 {
try {
Method getMethod = entity.getClass().getMethod("getBukkitEntity");
Object bukkitEntity = getMethod.invoke(entity);
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) {
if (!(bukkitEntity instanceof Entity)) {
return null;
}
return (org.bukkit.entity.Entity)bukkitEntity;
return (Entity)bukkitEntity;
} catch (Throwable ex) {
ex.printStackTrace();
}

View File

@ -1,6 +1,9 @@
package me.skymc.taboolib.string.language2;
import lombok.Getter;
import me.skymc.taboolib.string.language2.value.*;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
@ -12,101 +15,97 @@ import java.util.List;
* @since 2018-03-08 22:45:56
*/
public class Language2Format implements Language2Line {
private Language2Value language2Value;
private List<Language2Line> language2Lines = new ArrayList<>();
public Language2Format(Player player, Language2Value value) {
language2Value = value;
// 语言类型
Language2Type type = Language2Type.TEXT;
// 递交数据
List<String> values = new LinkedList<>();
// 遍历内容
for (String line : value.getLanguageValue()) {
// 文本类型
if (line.contains("[text]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.TEXT;
}
// 大标题
else if (line.contains("[title]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.TITLE;
}
// 小标题
else if (line.contains("[action]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.ACTION;
}
// JSON
else if (line.contains("[json]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.JSON;
}
// JSON2
else if (line.contains("[json2]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.JSON2;
}
// 音效
else if (line.contains("[sound]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.SOUND;
}
// 书本
else if (line.contains("[book]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.BOOK;
} else if (line.contains("[return]")) {
// 递交数据
parseValue(player, values, type);
}
// 默认
else {
// 追加内容
values.add(line);
}
}
}
public Language2Value getLanguage2Value() {
return language2Value;
}
public List<Language2Line> getLanguage2Lines() {
return language2Lines;
}
/**
* 识别内容
*
* @param player 玩家
* @param list 数据
* @param type 类型
*/
private void parseValue(Player player, List<String> list, Language2Type type) {
if (list.size() == 0) {
return;
}
// 变量转换
List<String> listPlaceholder = language2Value.setPlaceholder(list, player);
// 大标题
@Getter
private Language2Value language2Value = null;
@Getter
private List<Language2Line> language2Lines = new ArrayList<>();
public Language2Format(Player player, Language2Value value) {
language2Value = value;
// 语言类型
Language2Type type = Language2Type.TEXT;
// 递交数据
List<String> values = new LinkedList<>();
// 遍历内容
for (String line : value.getLanguageValue()) {
// 文本类型
if (line.contains("[text]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.TEXT;
}
// 大标题
else if (line.contains("[title]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.TITLE;
}
// 小标题
else if (line.contains("[action]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.ACTION;
}
// JSON
else if (line.contains("[json]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.JSON;
}
// JSON2
else if (line.contains("[json2]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.JSON2;
}
// 音效
else if (line.contains("[sound]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.SOUND;
}
// 书本
else if (line.contains("[book]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.BOOK;
}
else if (line.contains("[return]")) {
// 递交数据
parseValue(player, values, type);
}
// 默认
else {
// 追加内容
values.add(line);
}
}
}
/**
* 识别内容
*
* @param player 玩家
* @param list 数据
* @param type 类型
*/
private void parseValue(Player player, List<String> list, Language2Type type) {
if (list.size() == 0) {
return;
}
// 变量转换
List<String> listPlaceholder = language2Value.setPlaceholder(list, player);
// 大标题
switch (type) {
case TITLE:
language2Lines.add(new Language2Title(this, listPlaceholder));
@ -134,19 +133,23 @@ public class Language2Format implements Language2Line {
default:
language2Lines.add(new Language2Text(this, listPlaceholder));
break;
}
// 清理数据
list.clear();
listPlaceholder.clear();
}
}
// 清理数据
list.clear();
listPlaceholder.clear();
}
@Override
public void send(Player player) {
language2Lines.forEach(line -> line.send(player));
}
@Override
public void send(Player player) {
for (Language2Line line : language2Lines) {
line.send(player);
}
}
@Override
public void console() {
language2Lines.forEach(Language2Line::console);
}
@Override
public void console() {
for (Language2Line line : language2Lines) {
line.console();
}
}
}

View File

@ -1,90 +1,41 @@
package me.skymc.taboolib.team;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.EnumWrappers;
import com.comphenix.protocol.wrappers.PlayerInfoData;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.google.common.base.Preconditions;
import com.ilummc.tlib.bungee.api.ChatColor;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.events.itag.AsyncPlayerReceiveNameTagEvent;
import me.skymc.taboolib.events.itag.PlayerReceiveNameTagEvent;
import me.skymc.taboolib.itagapi.TagDataHandler;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.*;
import java.util.stream.IntStream;
import java.util.Set;
/**
* @Author sky
* @Since 2018-05-09 21:03
*/
public class TagAPI implements Listener {
@Deprecated
public class TagAPI {
private static final int[] uuidSplit = new int[]{0, 8, 12, 16, 20, 32};
private static boolean loaded = false;
private static HashMap<Integer, Player> entityIdMap = new HashMap<>();
private static HashMap<UUID, String> playerData = new HashMap<>();
/**
* 该工具于 2018年5月23日02:31:14 失效
* 新工具类: {@link TagDataHandler}
*/
TagAPI() {
}
public static void inst() {
assert !loaded : "TagAPI is already instanced!";
loaded = true;
Bukkit.getServer().getOnlinePlayers().forEach(player -> entityIdMap.put(player.getEntityId(), player));
Bukkit.getPluginManager().registerEvents(new TagAPI(), Main.getInst());
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(Main.getInst(), PacketType.Play.Server.PLAYER_INFO) {
@Override
public void onPacketSending(PacketEvent event) {
if (event.getPacket().getPlayerInfoAction().read(0) != EnumWrappers.PlayerInfoAction.ADD_PLAYER) {
return;
}
List<PlayerInfoData> newPlayerInfo = new ArrayList<>();
for (PlayerInfoData playerInfo : event.getPacket().getPlayerInfoDataLists().read(0)) {
Player player;
if (playerInfo == null || playerInfo.getProfile() == null || (player = Bukkit.getServer().getPlayer(playerInfo.getProfile().getUUID())) == null) {
// Unknown Player
newPlayerInfo.add(playerInfo);
continue;
}
newPlayerInfo.add(new PlayerInfoData(getSentName(player.getEntityId(), playerInfo.getProfile(), event.getPlayer()), playerInfo.getPing(), playerInfo.getGameMode(), playerInfo.getDisplayName()));
}
event.getPacket().getPlayerInfoDataLists().write(0, newPlayerInfo);
}
});
}
public static String getPlayerDisplayName(Player player) {
return playerData.getOrDefault(player.getUniqueId(), player.getName());
return TagDataHandler.getHandler().getDisplay(player);
}
public static void setPlayerDisplayName(Player player, String name) {
String nameColored = ChatColor.translateAlternateColorCodes('&', name);
player.setDisplayName(nameColored);
player.setPlayerListName(nameColored);
playerData.put(player.getUniqueId(), nameColored);
Bukkit.getScheduler().runTask(Main.getInst(), () -> refreshPlayer(player));
TagDataHandler.getHandler().setDisplay(player, name);
}
public static void removePlayerDisplayName(Player player) {
player.setDisplayName(null);
player.setPlayerListName(null);
playerData.remove(player.getUniqueId());
Bukkit.getScheduler().runTask(Main.getInst(), () -> refreshPlayer(player));
TagDataHandler.getHandler().setDisplay(player, player.getName());
}
public static void refreshPlayer(Player player) {
@ -112,50 +63,4 @@ public class TagAPI implements Listener {
forWhom.forEach(playerFor -> refreshPlayer(player, playerFor));
}
private static WrappedGameProfile getSentName(int sentEntityId, WrappedGameProfile sent, Player destinationPlayer) {
Preconditions.checkState(Bukkit.getServer().isPrimaryThread(), "Can only process events on main thread.");
Player namedPlayer = entityIdMap.get(sentEntityId);
if (namedPlayer == null) {
// They probably were dead when we reloaded
return sent;
}
PlayerReceiveNameTagEvent oldEvent = new PlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, sent.getName());
Bukkit.getServer().getPluginManager().callEvent(oldEvent);
StringBuilder builtUUID = new StringBuilder();
if (!sent.getId().contains("-")) {
IntStream.range(0, uuidSplit.length - 1).forEach(i -> builtUUID.append(sent.getId(), uuidSplit[i], uuidSplit[i + 1]).append("-"));
} else {
builtUUID.append(sent.getId());
}
AsyncPlayerReceiveNameTagEvent newEvent = new AsyncPlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, getPlayerDisplayName(namedPlayer), UUID.fromString(builtUUID.toString()));
Bukkit.getServer().getPluginManager().callEvent(newEvent);
updatePlayerTag(namedPlayer, newEvent);
return new WrappedGameProfile(newEvent.getUUID(), newEvent.getTag().substring(0, Math.min(newEvent.getTag().length(), 16)));
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
entityIdMap.put(event.getPlayer().getEntityId(), event.getPlayer());
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
entityIdMap.remove(event.getPlayer().getEntityId());
}
private static void updatePlayerTag(Player namedPlayer, AsyncPlayerReceiveNameTagEvent newEvent) {
TagManager.PlayerData playerData = TagManager.getInst().getPlayerData(namedPlayer);
if (playerData.isEmpty()) {
return;
}
TagManager.getInst().unloadData(namedPlayer);
playerData.setName(newEvent.getTag());
TagManager.getInst().uploadData(namedPlayer);
}
}

View File

@ -2,6 +2,7 @@ package me.skymc.taboolib.team;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.itagapi.TagDataHandler;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@ -18,16 +19,16 @@ import java.util.UUID;
* @author sky
* @since 2018-03-17 21:43:49
*/
public class TagManager implements Listener {
@Deprecated
public class TagManager {
/**
* 该工具于 2018年5月23日02:31:14 失效
* 新工具类: {@link TagDataHandler}
*/
private static TagManager inst;
private HashMap<UUID, PlayerData> playerData = new HashMap<>();
private TagManager() {
Bukkit.getPluginManager().registerEvents(this, Main.getInst());
}
public static TagManager getInst() {
synchronized (TagManager.class) {
if (inst == null) {
@ -38,146 +39,37 @@ public class TagManager implements Listener {
}
public HashMap<UUID, PlayerData> getPlayerData() {
return playerData;
return new HashMap<>(0);
}
/**
* 设置玩家前缀
*
* @param player 名称
* @param prefix 前缀
*/
public void setPrefix(Player player, String prefix) {
getPlayerData(player).setPrefix(prefix);
uploadData(player);
TagDataHandler.getHandler().setPrefix(player, prefix);
}
/**
* 设置玩家后缀
*
* @param player 玩家
* @param suffix 后缀
*/
public void setSuffix(Player player, String suffix) {
getPlayerData(player).setSuffix(suffix);
uploadData(player);
TagDataHandler.getHandler().setSuffix(player, suffix);
}
/**
* 获取玩家前缀
*
* @param player 玩家
* @return String
*/
public String getPrefix(Player player) {
return getPlayerData(player).getPrefix();
return TagDataHandler.getHandler().getPrefix(player);
}
/**
* 获取玩家后缀
*
* @param player 玩家
* @return String
*/
public String getSuffix(Player player) {
return getPlayerData(player).getSuffix();
return TagDataHandler.getHandler().getSuffix(player);
}
/**
* 获取玩家数据
*
* @param player 玩家
* @return {@link PlayerData}
*/
public PlayerData getPlayerData(Player player) {
return playerData.computeIfAbsent(player.getUniqueId(), k -> new PlayerData(player));
return new PlayerData(player);
}
/**
* 注销称号数据
*
* @param targetPlayer
*/
public void unloadData(Player targetPlayer) {
PlayerData data = getPlayerData(targetPlayer);
for (Player player : Bukkit.getOnlinePlayers()) {
Scoreboard scoreboard = getScoreboard(player);
Team team = scoreboard.getTeam(data.getName());
if (team != null) {
team.unregister();
}
}
data.reset();
TagDataHandler.getHandler().resetVariable(targetPlayer);
}
/**
* 将该玩家的数据向服务器所有玩家更新
*
* @param targetPlayer 玩家
*/
public void uploadData(Player targetPlayer) {
PlayerData data = getPlayerData(targetPlayer);
String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix();
String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix();
// 如果没有称号数据
if (prefix.isEmpty() && suffix.isEmpty()) {
unloadData(targetPlayer);
return;
}
for (Player player : Bukkit.getOnlinePlayers()) {
Scoreboard scoreboard = getScoreboard(player);
Team team = getTeam(scoreboard, data);
team.setPrefix(prefix);
team.setSuffix(suffix);
}
}
/**
* 下载服务器内的称号数据到该玩家
*
* @param targetPlayer 玩家
*/
public void downloadData(Player targetPlayer) {
Scoreboard scoreboard = getScoreboard(targetPlayer);
for (Player player : Bukkit.getOnlinePlayers()) {
PlayerData data = getPlayerData(player);
String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix();
String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix();
// 如果没有称号数据
if (prefix.isEmpty() && suffix.isEmpty()) {
continue;
}
Team team = getTeam(scoreboard, data);
team.setPrefix(prefix);
team.setSuffix(suffix);
}
}
@EventHandler
public void onJoin(PlayerJoinEvent e) {
downloadData(e.getPlayer());
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
unloadData(e.getPlayer());
}
private Scoreboard getScoreboard(Player player) {
Scoreboard scoreboard = player.getScoreboard();
if (scoreboard == null) {
player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
return scoreboard;
}
private Team getTeam(Scoreboard scoreboard, PlayerData data) {
Team team = scoreboard.getTeam(String.valueOf(data.getPrefix()));
if (team == null) {
team = scoreboard.registerNewTeam(String.valueOf(data.getPrefix()));
team.addEntry(data.getName());
}
return team;
}
static class PlayerData {

View File

@ -1,131 +0,0 @@
package me.skymc.taboolib.team;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
/**
* @author sky
* @since 2018-03-17 21:36:52
*/
public class TagUtils {
/**
* 设置玩家前后缀
*
* @param p 玩家
* @param prefix 前缀
* @param suffix 后缀
*/
public static void setTag(Player p, String prefix, String suffix) {
// 判断长度
if (prefix.length() > 16) {
prefix = prefix.substring(0, 16);
}
if (suffix.length() > 16) {
suffix = suffix.substring(0, 16);
}
// 获取计分板
Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard();
Team t = board.getTeam(p.getName());
if (t == null) {
t = board.registerNewTeam(p.getName());
}
// 更新称号
t.setPrefix(prefix);
t.setSuffix(suffix);
t.addEntry(p.getName());
// 更新玩家
for (Player o : Bukkit.getOnlinePlayers()) {
if (!board.equals(o.getScoreboard())) {
o.setScoreboard(board);
}
}
}
/**
* 注销玩家前后缀
*
* @param p 玩家
*/
public static void unregisterTag(Player p) {
Team team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam(p.getName());
if (team != null) {
team.unregister();
}
}
/**
* 注销所有在线玩家前后缀
*/
public static void unregisterAll() {
for (Player o : Bukkit.getOnlinePlayers()) {
unregisterTag(o);
}
}
/**
* 删除所有前后缀
*/
public static void delete() {
for (Team t : Bukkit.getScoreboardManager().getMainScoreboard().getTeams()) {
t.unregister();
}
}
/**
* 设置全服玩家前后缀
*
* @param prefix 前缀
* @param suffix 后缀
*/
public static void registerAll(String prefix, String suffix) {
for (Player o : Bukkit.getOnlinePlayers()) {
setTag(o, prefix, suffix);
}
}
/**
* 刷新计分板数据
*/
public static void refresh() {
Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard();
for (Player o : Bukkit.getOnlinePlayers()) {
o.setScoreboard(board);
}
}
/**
* 获取玩家前缀
*
* @param p 玩家
* @return String
*/
public static String getPrefix(Player p) {
Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard();
Team t = board.getTeam(p.getName());
if (t != null) {
return t.getPrefix();
}
return null;
}
/**
* 获取玩玩家后缀
*
* @param p 玩家
* @return String
*/
public static String getSuffix(Player p) {
Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard();
Team t = board.getTeam(p.getName());
if (t != null) {
return t.getSuffix();
}
return null;
}
}

View File

@ -164,6 +164,9 @@ COMMANDS:
- '&8[&3&lTabooLib&8] &7你可能想要:'
- '&8[&3&lTabooLib&8] &7{1}'
COMMAND-REGISTER: '&7自动为插件 &f{0} &7的命令 &f{1} &7注册 &f{2} &7条子命令'
COMMAND-HELP: ' §f/{0} {1} {2} §6- §e{3}'
COMMAND-ARGUMENT: '§7<§8{0}§7>'
COMMAND-ARGUMENT-REQUIRE: '§7[§8{0}§7]'
PARAMETER:
UNKNOWN: '&8[&3&lTabooLib&8] &4指令错误'
INSUFFICIENT: '&8[&3&lTabooLib&8] &4参数不足'