This commit is contained in:
Izzel_Aliz 2018-06-12 20:10:11 +08:00
commit 12334bc5a0
70 changed files with 3027 additions and 1965 deletions

View File

@ -8,25 +8,17 @@
[![](https://img.shields.io/github/stars/Bkm016/TabooLib.svg?style=flat-square&label=Stars)](https://github.com/Bkm016/TabooLib) [![](https://img.shields.io/github/stars/Bkm016/TabooLib.svg?style=flat-square&label=Stars)](https://github.com/Bkm016/TabooLib)
[![](https://jitpack.io/v/Bkm016/TabooLib.svg)](https://jitpack.io/#Bkm016/TabooLib) [![](https://jitpack.io/v/Bkm016/TabooLib.svg)](https://jitpack.io/#Bkm016/TabooLib)
## 安装 TabooLib
#### 服务器有网络:
1. 在[这里](https://github.com/bkm016/TabooLib/releases)下载最新版的 **TabooLib**
2. 正常步骤安装
#### 服务器无网络:
1. 重复上面步骤
2. 在[这里](https://skymc.oss-cn-shanghai.aliyuncs.com/plugins/libs.rar)下载 **TabooLib** 所需要的第三方库
3. 解压后覆盖 **"plugins"** 文件夹(注意不是丢到 **"plugins"** 文件夹里)
#### 服务端为 1.7.10 版本
1. 重复上面步骤
2. 查阅[文档](https://blog.yumc.pw/posts/Fix-Thermos-Load-Plugin-Class-Not-Found/), 获取解决办法
## 插件文档 ## 插件文档
[TabooLib 文档](https://bkm016.github.io/TabooLib/#/) [TabooLib 文档](https://bkm016.github.io/TabooLib/#/)
## 下载 TabooLib 插件
在 [这里](https://github.com/bkm016/TabooLib/releases) 根据您服务器的网络状态下载**在线**或**离线**版本
离线版为 **offline** 结尾的 **jar** 文件
如果你的服务器是 **1.7.10** 版本,在 [这里](https://pcd.ac.cn/2018/05/19/71/) 修复因 **SpecialSource** 版本过低导致插件无法载入的问题
## 添加 TabooLib 为库 ## 添加 TabooLib 为库
### Maven ### Maven

View File

@ -6,7 +6,7 @@
<groupId>me.skymc</groupId> <groupId>me.skymc</groupId>
<artifactId>TabooLib</artifactId> <artifactId>TabooLib</artifactId>
<version>4.02</version> <version>4.09</version>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -175,6 +175,13 @@
<scope>system</scope> <scope>system</scope>
<systemPath>${basedir}/libs/Vault.jar</systemPath> <systemPath>${basedir}/libs/Vault.jar</systemPath>
</dependency> </dependency>
<dependency>
<groupId>bossbar</groupId>
<artifactId>bossbar</artifactId>
<version>1</version>
<scope>system</scope>
<systemPath>${basedir}/libs/BossBarAPI.jar</systemPath>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -13,6 +13,7 @@ import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader; import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.IO; import com.ilummc.tlib.util.IO;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.fileutils.FileUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -49,7 +50,7 @@ public class TLib {
libsFolder.mkdirs(); libsFolder.mkdirs();
} }
try { try {
String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/lang/internal.yml")), Charset.forName("utf-8")); String yamlText = new String(IO.readFully(FileUtils.getResource("lang/internal.yml")), Charset.forName("utf-8"));
internalLanguage = new YamlConfiguration(); internalLanguage = new YamlConfiguration();
internalLanguage.loadFromString(yamlText); internalLanguage.loadFromString(yamlText);
} catch (IOException | InvalidConfigurationException ignored) { } catch (IOException | InvalidConfigurationException ignored) {
@ -71,13 +72,14 @@ public class TLib {
TLocaleLoader.init(); TLocaleLoader.init();
PlaceholderHook.init(); PlaceholderHook.init();
TLocaleLoader.load(Main.getInst(), false); TLocaleLoader.load(Main.getInst(), false);
TDependencyInjector.inject(Main.getInst(), tLib); }
public static void initPost() {
TDependencyInjector.inject(Main.getInst(), TLib.getTLib());
try { try {
Pool.init(); Pool.init();
} catch (Throwable ignored) { } catch (Throwable ignored) {
} }
} }
public static void unload() { public static void unload() {

View File

@ -6,6 +6,7 @@ import com.ilummc.tlib.bungee.api.chat.TextComponent;
import com.ilummc.tlib.bungee.api.chat.TranslatableComponent; import com.ilummc.tlib.bungee.api.chat.TranslatableComponent;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
/** /**

View File

@ -52,8 +52,8 @@ public class TDependency {
} }
private static boolean downloadMaven(String url, String groupId, String artifactId, String version, File target, String dl) { private static boolean downloadMaven(String url, String groupId, String artifactId, String version, File target, String dl) {
if (Main.getInst().getConfig().getBoolean("OFFLINE-MODE")) { if (Main.isOfflineVersion()) {
TLocale.Logger.warn("DEPENDENCY.OFFLINE-DEPENDENCY-WARN"); TLocale.Logger.warn("DEPENDENCY.DOWNLOAD-OFFLINE");
return false; return false;
} }
AtomicBoolean failed = new AtomicBoolean(false); AtomicBoolean failed = new AtomicBoolean(false);

View File

@ -13,9 +13,23 @@ import org.bukkit.plugin.java.JavaPlugin;
import java.io.File; import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.HashMap;
public class TDependencyInjector { public class TDependencyInjector {
public static Dependency[] getDependencies(Object o) {
Dependency[] dependencies = new Dependency[0];
Dependencies d = o.getClass().getAnnotation(Dependencies.class);
if (d != null) {
dependencies = d.value();
}
Dependency d2 = o.getClass().getAnnotation(Dependency.class);
if (d2 != null) {
dependencies = new Dependency[]{d2};
}
return dependencies;
}
public static void inject(Plugin plugin, Object o) { public static void inject(Plugin plugin, Object o) {
TLocaleLoader.load(plugin, true); TLocaleLoader.load(plugin, true);
injectDependencies(plugin, o); injectDependencies(plugin, o);
@ -135,17 +149,7 @@ public class TDependencyInjector {
} }
private static void injectDependencies(Plugin plugin, Object o) { private static void injectDependencies(Plugin plugin, Object o) {
Dependency[] dependencies = new Dependency[0]; Dependency[] dependencies = getDependencies(o);
{
Dependencies d = o.getClass().getAnnotation(Dependencies.class);
if (d != null) {
dependencies = d.value();
}
Dependency d2 = o.getClass().getAnnotation(Dependency.class);
if (d2 != null) {
dependencies = new Dependency[]{d2};
}
}
if (dependencies.length != 0) { if (dependencies.length != 0) {
TLocale.Logger.info("DEPENDENCY.LOADING-START", plugin.getName()); TLocale.Logger.info("DEPENDENCY.LOADING-START", plugin.getName());
for (Dependency dependency : dependencies) { for (Dependency dependency : dependencies) {
@ -167,5 +171,4 @@ public class TDependencyInjector {
TLocale.Logger.info("DEPENDENCY.LOAD-COMPLETE"); TLocale.Logger.info("DEPENDENCY.LOAD-COMPLETE");
} }
} }
} }

View File

@ -2,20 +2,30 @@ package com.ilummc.tlib.resources;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.TLib;
import com.ilummc.tlib.bungee.api.ChatColor; import com.ilummc.tlib.bungee.api.ChatColor;
import com.ilummc.tlib.bungee.api.chat.BaseComponent;
import com.ilummc.tlib.bungee.api.chat.TextComponent;
import com.ilummc.tlib.bungee.chat.ComponentSerializer;
import com.ilummc.tlib.inject.TLoggerManager; import com.ilummc.tlib.inject.TLoggerManager;
import com.ilummc.tlib.util.Ref; import com.ilummc.tlib.util.Ref;
import com.ilummc.tlib.util.Strings; import com.ilummc.tlib.util.Strings;
import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.nms.NMSUtil19;
import me.skymc.taboolib.nms.NMSUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/**
* @author IzzelAliz
*/
public class TLocale { public class TLocale {
private TLocale() { private TLocale() {
@ -128,4 +138,23 @@ public class TLocale {
} }
} }
public static class Tellraw extends TLocale {
private static final Field playerConnection = NMSUtils.getFieldSilent(NMSUtil19.class_EntityPlayer, "playerConnection");
private static final Method sendPacket = NMSUtils.getMethodSilent(NMSUtil19.class_PlayerConnection, "sendPacket", NMSUtil19.class_Packet);
private static final Constructor<?> PacketPlayOutChat = NMSUtils.getConstructorSilent(NMSUtil19.class_PacketPlayOutChat, NMSUtil19.class_IChatBaseComponent);
public static void send(CommandSender sender, String rawMessage) {
if (sender instanceof Player) {
try {
sendPacket.invoke(playerConnection.get(NMSUtils.getHandle(sender)), PacketPlayOutChat.newInstance(rawMessage));
} catch (Exception e) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + sender.getName() + " " + rawMessage);
}
} else {
sender.sendMessage(TextComponent.toLegacyText(ComponentSerializer.parse(rawMessage)));
}
}
}
} }

View File

@ -10,6 +10,7 @@ import me.skymc.taboocode.TabooCodeLang;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.fileutils.FileUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -29,8 +30,10 @@ public class TLocaleLoader {
public static void init() { public static void init() {
ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT"); ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT");
ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON"); ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON");
ConfigurationSerialization.registerClass(TLocaleBook.class, "BOOK");
ConfigurationSerialization.registerClass(TLocaleSound.class, "SOUND"); ConfigurationSerialization.registerClass(TLocaleSound.class, "SOUND");
ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE"); ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE");
ConfigurationSerialization.registerClass(TLocaleBossBar.class, "BAR");
ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION"); ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION");
} }
@ -140,7 +143,7 @@ public class TLocaleLoader {
} }
private static YamlConfiguration getLocaleAtStream(Plugin plugin, File localeFile) { private static YamlConfiguration getLocaleAtStream(Plugin plugin, File localeFile) {
InputStream localeInputSteam = plugin.getClass().getResourceAsStream("/lang/" + localeFile.getName()); InputStream localeInputSteam = FileUtils.getResource(plugin, "lang/" + localeFile.getName());
try { try {
String yamlText = new String(IO.readFully(localeInputSteam), Charset.forName("utf-8")); String yamlText = new String(IO.readFully(localeInputSteam), Charset.forName("utf-8"));
YamlConfiguration yaml = new YamlConfiguration(); YamlConfiguration yaml = new YamlConfiguration();

View File

@ -0,0 +1,91 @@
package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps;
import com.ilummc.tlib.bungee.chat.ComponentSerializer;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.bookformatter.BookFormatter;
import me.skymc.taboolib.bookformatter.builder.BookBuilder;
import me.skymc.taboolib.json.tellraw.TellrawJson;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import javax.annotation.concurrent.ThreadSafe;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Author sky
* @Since 2018-05-27 0:05
*/
@ThreadSafe
@SerializableAs("BOOK")
public class TLocaleBook extends TLocaleSerialize {
/*
BookTest:
- ==: BOOK
pages:
0:
- '第一页内容'
- '[ <变量1@page-1> ]'
1:
- '第二页内容'
- '[ <变量2@page-2> ]'
args:
page-1:
hover: '展示内容1'
command: '/say %player_name% NB1'
page-2:
hover: '展示内容2'
suggest: '/say %player_name% NB2'
*/
private final List<TellrawJson> pages;
private final Map<String, Object> map;
private final boolean papi;
public TLocaleBook(List<TellrawJson> pages, Map<String, Object> map, boolean papi) {
this.pages = pages;
this.map = map;
this.papi = papi;
}
@Override
public Map<String, Object> serialize() {
return Maps.newHashMap(map);
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (!(sender instanceof Player)) {
return;
}
new BukkitRunnable() {
@Override
public void run() {
BookBuilder bookBuilder = BookFormatter.writtenBook();
pages.stream().map(jsonPage -> papi ? TLocale.Translate.setPlaceholders(sender, Strings.replaceWithOrder(jsonPage.toRawMessage(), args)) : TLocale.Translate.setColored(Strings.replaceWithOrder(jsonPage.toRawMessage(), args))).map(ComponentSerializer::parse).forEach(bookBuilder::addPages);
new BukkitRunnable() {
@Override
public void run() {
BookFormatter.forceOpen((Player) sender, bookBuilder.build());
}
}.runTask(Main.getInst());
}
}.runTaskAsynchronously(Main.getInst());
}
public static TLocaleBook valueOf(Map<String, Object> map) {
Map<String, Object> pages = map.containsKey("pages") ? (Map<String, Object>) map.get("pages") : new HashMap<>();
Map<String, Object> section = map.containsKey("args") ? (Map<String, Object>) map.get("args") : new HashMap<>();
List<TellrawJson> pageJsonList = pages.values().stream().map(page -> TLocaleJson.formatJson(section, page, TellrawJson.create())).collect(Collectors.toList());
return new TLocaleBook(pageJsonList, map, isPlaceholderEnabled(map));
}
}

View File

@ -0,0 +1,95 @@
package com.ilummc.tlib.resources.type;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.other.NumberUtils;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import org.inventivetalent.bossbar.BossBar;
import org.inventivetalent.bossbar.BossBarAPI;
import javax.annotation.concurrent.ThreadSafe;
import java.util.Map;
/**
* @Author sky
* @Since 2018-05-27 18:52
*/
@ThreadSafe
@SerializableAs("BAR")
public class TLocaleBossBar extends TLocaleSerialize {
/*
BossBar:
- ==: BAR
text: 'BossBar 血条公告'
color: BLUE
style: NOTCHED_20
progress: 1.0
timeout: 20
timeout-interval: 2
*/
private final String text;
private final BossBarAPI.Color color;
private final BossBarAPI.Style style;
private final float progress;
private final int timeout;
private final int timeoutInterval;
private final boolean papi;
public TLocaleBossBar(String text, BossBarAPI.Color color, BossBarAPI.Style style, float progress, int timeout, int timeoutInterval, boolean papi) {
this.text = text;
this.color = color;
this.style = style;
this.progress = progress;
this.timeout = timeout;
this.timeoutInterval = timeoutInterval;
this.papi = papi;
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (Bukkit.getPluginManager().getPlugin("BossBarAPI") == null) {
TLocale.Logger.error("LOCALE.BAR-PLUGIN-NOT-FOUND");
return;
}
if (sender instanceof Player) {
TextComponent textComponent = new TextComponent(papi ? TLocale.Translate.setPlaceholders(sender, Strings.replaceWithOrder(text, args)) : TLocale.Translate.setColored(Strings.replaceWithOrder(text, args)));
BossBar bossBar = BossBarAPI.addBar((Player) sender, textComponent, color, style, progress, timeout, timeoutInterval);
} else {
sender.sendMessage(text);
}
}
@Override
public Map<String, Object> serialize() {
return null;
}
public static TLocaleBossBar valueOf(Map<String, Object> map) {
return new TLocaleBossBar(map.getOrDefault("text", "§4* Invalid Text*").toString(), getColor(String.valueOf(map.get("color"))), getStyle(String.valueOf(map.get("style"))), (float) NumberUtils.getDouble(String.valueOf(map.getOrDefault("progress", 1))), NumberUtils.getInteger(String.valueOf(map.getOrDefault("timeout", 20))), NumberUtils.getInteger(String.valueOf(map.getOrDefault("timeout-interval", 2))), isPlaceholderEnabled(map));
}
private static BossBarAPI.Color getColor(String color) {
try {
return BossBarAPI.Color.valueOf(color);
} catch (Exception e) {
TLocale.Logger.error("LOCALE.BAR-STYLE-IDENTIFICATION-FAILED", e.toString());
return BossBarAPI.Color.WHITE;
}
}
private static BossBarAPI.Style getStyle(String style) {
try {
return BossBarAPI.Style.valueOf(style);
} catch (Exception e) {
TLocale.Logger.error("LOCALE.BAR-COLOR-IDENTIFICATION-FAILED", e.toString());
return BossBarAPI.Style.NOTCHED_20;
}
}
}

View File

@ -10,10 +10,12 @@ import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleSerialize; import com.ilummc.tlib.resources.TLocaleSerialize;
import com.ilummc.tlib.util.Strings; import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.jsonformatter.JSONFormatter; import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.json.tellraw.TellrawJson;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.string.VariableFormatter;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import javax.annotation.concurrent.ThreadSafe; import javax.annotation.concurrent.ThreadSafe;
import java.util.*; import java.util.*;
@ -21,6 +23,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ThreadSafe @ThreadSafe
@SerializableAs("JSON") @SerializableAs("JSON")
public class TLocaleJson extends TLocaleSerialize { public class TLocaleJson extends TLocaleSerialize {
@ -72,11 +75,11 @@ public class TLocaleJson extends TLocaleSerialize {
// 可能有很多个 BaseComponent于是为每个 component 单独设置各种事件 // 可能有很多个 BaseComponent于是为每个 component 单独设置各种事件
BaseComponent[] component = TextComponent.fromLegacyText(text); BaseComponent[] component = TextComponent.fromLegacyText(text);
arg.forEach((key, value) -> { arg.forEach((key, value) -> {
if ("suggest".equalsIgnoreCase(key)) { if (key.equalsIgnoreCase("suggest")) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, String.valueOf(value)))); Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, String.valueOf(value))));
} else if ("command".equalsIgnoreCase(key) || "commands".equalsIgnoreCase(key)) { } else if (key.equalsIgnoreCase("command") || "commands".equalsIgnoreCase(key)) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value)))); Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value))));
} else if ("hover".equalsIgnoreCase(key)) { } else if (key.equalsIgnoreCase("hover")) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(TLocale.Translate.setColored(String.valueOf(value))).create()))); Arrays.stream(component).forEach(baseComponent -> baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(TLocale.Translate.setColored(String.valueOf(value))).create())));
} }
}); });
@ -101,7 +104,7 @@ public class TLocaleJson extends TLocaleSerialize {
private static List<String> getTextList(Object textObj) { private static List<String> getTextList(Object textObj) {
if (textObj instanceof List) { if (textObj instanceof List) {
return ((List<?>) textObj).stream().map(Object::toString).map(s -> TLocale.Translate.setColored(s)).collect(Collectors.toList()); return ((List<?>) textObj).stream().map(Object::toString).map(TLocale.Translate::setColored).collect(Collectors.toList());
} else if (textObj instanceof String) { } else if (textObj instanceof String) {
return Lists.newArrayList(TLocale.Translate.setColored((String) textObj)); return Lists.newArrayList(TLocale.Translate.setColored((String) textObj));
} else { } else {
@ -125,11 +128,11 @@ public class TLocaleJson extends TLocaleSerialize {
} }
private void sendRawMessage(CommandSender sender, BaseComponent[] components) { private void sendRawMessage(CommandSender sender, BaseComponent[] components) {
if (sender instanceof Player) { TLocale.Tellraw.send(sender, ComponentSerializer.toString(components));
JSONFormatter.sendRawMessage((Player) sender, ComponentSerializer.toString(components));
} else {
sender.sendMessage(TextComponent.toLegacyText(components));
} }
private List<BaseComponent> replace(List<BaseComponent> component, CommandSender sender, String... args) {
return component.stream().map(c -> replace(c, sender, args)).collect(Collectors.toList());
} }
private BaseComponent[] replace(BaseComponent[] component, CommandSender sender, String... args) { private BaseComponent[] replace(BaseComponent[] component, CommandSender sender, String... args) {
@ -140,10 +143,6 @@ public class TLocaleJson extends TLocaleSerialize {
return components; return components;
} }
private List<BaseComponent> replace(List<BaseComponent> component, CommandSender sender, String... args) {
return component.stream().map(c -> replace(c, sender, args)).collect(Collectors.toList());
}
private BaseComponent replace(BaseComponent component, CommandSender sender, String... args) { private BaseComponent replace(BaseComponent component, CommandSender sender, String... args) {
if (component.getClickEvent() != null) { if (component.getClickEvent() != null) {
ClickEvent clickEvent = new ClickEvent(component.getClickEvent().getAction(), replace(sender, component.getClickEvent().getValue(), args)); ClickEvent clickEvent = new ClickEvent(component.getClickEvent().getAction(), replace(sender, component.getClickEvent().getValue(), args));
@ -166,4 +165,63 @@ public class TLocaleJson extends TLocaleSerialize {
String s = Strings.replaceWithOrder(text, args); String s = Strings.replaceWithOrder(text, args);
return papi ? PlaceholderHook.replace(sender, s) : s; return papi ? PlaceholderHook.replace(sender, s) : s;
} }
public static TellrawJson formatJson(Map<String, Object> section, Object textObject, TellrawJson pageJson) {
List<String> textList = textObject instanceof List ? (List<String>) textObject : Collections.singletonList(String.valueOf(textObject));
// 遍历本页文本
for (int i = 0; i < textList.size(); i++) {
// 捕捉变量
for (VariableFormatter.Variable variable : new VariableFormatter(textList.get(i), pattern).find().getVariableList()) {
// 如果是变量
if (variable.isVariable()) {
String[] split = variable.getText().split("@");
// @ 前面的字符串
String text = split.length > 1 ? split[0] : "§4* Invalid Text *";
// @ 后面的节点名
String node = split.length > 1 ? split[1] : null;
// 处理变量
formatNode(section, pageJson, text, node);
} else {
pageJson.append(variable.getText());
}
}
if (i + 1 < textList.size()) {
pageJson.newLine();
}
}
return pageJson;
}
private static void formatNode(Map<String, Object> section, TellrawJson pageJson, String text, String node) {
if (section.containsKey(node)) {
try {
Map<String, Object> args = (Map<String, Object>) section.get(node);
// 文本
pageJson.append(args.getOrDefault("text", text).toString());
// 功能
if (args.containsKey("item")) {
pageJson.hoverItem(ItemUtils.getCacheItem(args.get("item").toString()));
}
if (args.containsKey("hover")) {
pageJson.hoverText(args.get("hover").toString());
}
if (args.containsKey("suggest")) {
pageJson.clickSuggest(args.get("suggest").toString());
}
if (args.containsKey("command")) {
pageJson.clickCommand(args.get("command").toString());
}
if (args.containsKey("page")) {
pageJson.clickChangePage(NumberUtils.getInteger(args.get("page").toString()));
}
if (args.containsKey("url")) {
pageJson.clickOpenURL(args.get("url").toString());
}
} catch (Exception e) {
TLocale.Logger.error("LOCALE.BOOK-ARGUMENTS-IDENTIFICATION-FAILED", e.toString());
}
} else {
pageJson.append("§4* Invalid Argument *");
}
}
} }

View File

@ -2,6 +2,14 @@ package com.ilummc.tlib.util;
public class Strings { public class Strings {
public static boolean isBlank(String var) {
return var == null || var.trim().isEmpty();
}
public static boolean isEmpty(CharSequence var) {
return var == null || var.length() == 0;
}
/** /**
* 优化过的 String#replace比默认快了大概 5 * 优化过的 String#replace比默认快了大概 5
* *
@ -28,15 +36,13 @@ public class Strings {
return stringBuilder.toString(); return stringBuilder.toString();
} }
// *********************************
//
// Deprecated
//
// *********************************
public static String replaceWithOrder(String template, String... args) { public static String replaceWithOrder(String template, String... args) {
return replaceWithOrder(template, (Object[]) args); return replaceWithOrder(template, (Object[]) args);
} }
public static boolean isBlank(String var) {
return var == null || var.trim().isEmpty();
}
public static boolean isEmpty(CharSequence var) {
return var == null || var.length() == 0;
}
} }

View File

@ -1,12 +1,13 @@
package me.skymc.taboolib; package me.skymc.taboolib;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.TLib;
import com.ilummc.tlib.inject.TConfigWatcher; import com.ilummc.tlib.annotations.Dependency;
import com.ilummc.tlib.inject.TDependencyInjector;
import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.anvil.AnvilContainerAPI; import me.skymc.taboolib.anvil.AnvilContainerAPI;
import me.skymc.taboolib.bstats.Metrics; import me.skymc.taboolib.bstats.Metrics;
import me.skymc.taboolib.commands.TabooLibMainCommand; 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.language.Language2Command;
import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand; import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand;
import me.skymc.taboolib.commands.plugin.TabooLibPluginMainCommand; import me.skymc.taboolib.commands.plugin.TabooLibPluginMainCommand;
@ -17,17 +18,17 @@ import me.skymc.taboolib.database.PlayerDataManager;
import me.skymc.taboolib.economy.EcoUtils; import me.skymc.taboolib.economy.EcoUtils;
import me.skymc.taboolib.entity.EntityUtils; import me.skymc.taboolib.entity.EntityUtils;
import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.inventory.speciaitem.SpecialItem; import me.skymc.taboolib.inventory.speciaitem.SpecialItem;
import me.skymc.taboolib.itagapi.TagDataHandler;
import me.skymc.taboolib.javashell.JavaShell; import me.skymc.taboolib.javashell.JavaShell;
import me.skymc.taboolib.listener.*; import me.skymc.taboolib.listener.*;
import me.skymc.taboolib.message.ChatCatcher; import me.skymc.taboolib.message.ChatCatcher;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.mysql.hikari.HikariHandler; import me.skymc.taboolib.mysql.hikari.HikariHandler;
import me.skymc.taboolib.mysql.protect.MySQLConnection; import me.skymc.taboolib.mysql.protect.MySQLConnection;
import me.skymc.taboolib.nms.item.DabItemUtils; import me.skymc.taboolib.nms.item.DabItemUtils;
import me.skymc.taboolib.other.NumberUtils; import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.packet.PacketUtils;
import me.skymc.taboolib.permission.PermissionUtils; import me.skymc.taboolib.permission.PermissionUtils;
import me.skymc.taboolib.playerdata.DataUtils; import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.taboolib.sign.SignUtils; import me.skymc.taboolib.sign.SignUtils;
@ -35,8 +36,6 @@ import me.skymc.taboolib.skript.SkriptHandler;
import me.skymc.taboolib.string.StringUtils; import me.skymc.taboolib.string.StringUtils;
import me.skymc.taboolib.string.language2.Language2; import me.skymc.taboolib.string.language2.Language2;
import me.skymc.taboolib.support.SupportPlaceholder; 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.timecycle.TimeCycleManager;
import me.skymc.taboolib.update.UpdateTask; import me.skymc.taboolib.update.UpdateTask;
import me.skymc.tlm.TLM; import me.skymc.tlm.TLM;
@ -50,6 +49,8 @@ import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import java.io.File; import java.io.File;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Random; import java.util.Random;
/** /**
@ -57,6 +58,14 @@ import java.util.Random;
*/ */
public class Main extends JavaPlugin implements Listener { public class Main extends JavaPlugin implements Listener {
public Main() {
inst = this;
}
public enum StorageType {
LOCAL, SQL
}
private static Plugin inst; private static Plugin inst;
private static net.milkbowl.vault.economy.Economy Economy; private static net.milkbowl.vault.economy.Economy Economy;
@ -65,7 +74,7 @@ public class Main extends JavaPlugin implements Listener {
private static File serverDataFolder; private static File serverDataFolder;
private static StorageType storageType; private static StorageType storageType = StorageType.LOCAL;
private static boolean disable = false; private static boolean disable = false;
@ -75,60 +84,10 @@ public class Main extends JavaPlugin implements Listener {
private static boolean started; private static boolean started;
private static boolean isInternetOnline = false;
private FileConfiguration config = null; private FileConfiguration config = null;
public static Plugin getInst() {
return inst;
}
public static String getPrefix() {
return "§8[§3§lTabooLib§8] §7";
}
public static net.milkbowl.vault.economy.Economy getEconomy() {
return Economy;
}
public static void setEconomy(net.milkbowl.vault.economy.Economy economy) {
Economy = economy;
}
public static File getPlayerDataFolder() {
return playerDataFolder;
}
public static File getServerDataFolder() {
return serverDataFolder;
}
public static StorageType getStorageType() {
return storageType;
}
public static boolean isDisable() {
return disable;
}
public static MySQLConnection getConnection() {
return connection;
}
public static Language2 getExampleLanguage2() {
return exampleLanguage2;
}
public static boolean isStarted() {
return started;
}
public static Random getRandom() {
return NumberUtils.getRandom();
}
public static String getTablePrefix() {
return inst.getConfig().getString("MYSQL.PREFIX");
}
@Override @Override
public FileConfiguration getConfig() { public FileConfiguration getConfig() {
return config; return config;
@ -150,71 +109,31 @@ public class Main extends JavaPlugin implements Listener {
@Override @Override
public void onLoad() { public void onLoad() {
inst = this;
disable = false; disable = false;
// 载入配置 // 载入配置
saveDefaultConfig(); saveDefaultConfig();
// 载入牛逼玩意儿
// 加载依赖
TLib.init(); TLib.init();
TLib.injectPluginManager(); TLib.injectPluginManager();
// 网络检测
// 载入目录 testInternet();
// 创建文件夹
setupDataFolder(); setupDataFolder();
// 注册配置 // 创建数据库
DataUtils.addPluginData("TabooLibrary", null); setupDatabase();
// 载入离线库文件
// 启用数据库 setupLibraries();
if (getConfig().getBoolean("MYSQL.ENABLE")) { // 载入牛逼玩意儿
// 连接数据库 TLib.initPost();
connection = new MySQLConnection(getConfig().getString("MYSQL.HOST"), getConfig().getString("MYSQL.USER"), getConfig().getString("MYSQL.POST"), getConfig().getString("MYSQL.PASSWORD"), getConfig().getString("MYSQL.DATABASE"), 30, this);
// 连接成功
if (connection.isConnection()) {
// 创建表
connection.createTable(getTablePrefix() + "_playerdata", "username", "configuration");
connection.createTable(getTablePrefix() + "_plugindata", "name", "variable", "upgrade");
connection.createTable(getTablePrefix() + "_serveruuid", "uuid", "hash");
// 如果没有数据
if (!connection.isExists(getTablePrefix() + "_serveruuid", "uuid", TabooLib.getServerUID())) {
connection.intoValue(getTablePrefix() + "_serveruuid", TabooLib.getServerUID(), StringUtils.hashKeyForDisk(getDataFolder().getPath()));
} else {
String hash = connection.getValue(getTablePrefix() + "_serveruuid", "uuid", TabooLib.getServerUID(), "hash").toString();
// 如果这个值和我的值不同
if (!hash.equals(StringUtils.hashKeyForDisk(getDataFolder().getPath()))) {
TLocale.Logger.error("NOTIFY.ERROR-SERVER-KEY");
// 重新生成序列号
TabooLib.resetServerUID();
// 关服
Bukkit.shutdown();
}
}
} else {
// 提示
TLocale.Logger.error("NOTIFY.ERROR-CONNECTION-FAIL");
// 关服
Bukkit.shutdown();
}
// 储存方式
storageType = StorageType.SQL;
} else {
// 储存方式
storageType = StorageType.LOCAL;
}
} }
@Override @Override
public void onEnable() { public void onEnable() {
// 注册指令 // 注册命令
getCommand("language2").setExecutor(new Language2Command()); registerCommands();
getCommand("taboolibrarymodule").setExecutor(new TLMCommands());
getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand());
BaseMainCommand.createCommandExecutor("taboolib", new TabooLibMainCommand());
BaseMainCommand.createCommandExecutor("taboolibplugin", new TabooLibPluginMainCommand());
// 注册监听 // 注册监听
registerListener(); registerListener();
// 载入经济 // 载入经济
EcoUtils.setupEconomy(); EcoUtils.setupEconomy();
// 载入权限 // 载入权限
@ -229,6 +148,8 @@ public class Main extends JavaPlugin implements Listener {
JavaShell.javaShellSetup(); JavaShell.javaShellSetup();
// 注册脚本 // 注册脚本
SkriptHandler.getInst(); SkriptHandler.getInst();
// 注册头衔
TagDataHandler.init(this);
// 载入语言文件 // 载入语言文件
exampleLanguage2 = new Language2("Language2", this); exampleLanguage2 = new Language2("Language2", this);
@ -243,6 +164,7 @@ public class Main extends JavaPlugin implements Listener {
// 文件保存 // 文件保存
Bukkit.getScheduler().runTaskTimerAsynchronously(this, DataUtils::saveAllCaches, 20, 20 * 120); Bukkit.getScheduler().runTaskTimerAsynchronously(this, DataUtils::saveAllCaches, 20, 20 * 120);
Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> PlayerDataManager.saveAllCaches(true, false), 20, 20 * 60); Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> PlayerDataManager.saveAllCaches(true, false), 20, 20 * 60);
// 文件监控 // 文件监控
TLib.getTLib().getConfigWatcher().addListener(new File(getDataFolder(), "config.yml"), null, obj -> { TLib.getTLib().getConfigWatcher().addListener(new File(getDataFolder(), "config.yml"), null, obj -> {
reloadConfig(); reloadConfig();
@ -254,12 +176,10 @@ public class Main extends JavaPlugin implements Listener {
@Override @Override
public void run() { public void run() {
// 载入 PlaceholderAPI 扩展
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
new SupportPlaceholder(getInst(), "taboolib").hook(); new SupportPlaceholder(getInst(), "taboolib").hook();
} }
if (PacketUtils.isProtocolLibEnabled()) {
TagAPI.inst();
}
// 载入 SpecialItem 接口 // 载入 SpecialItem 接口
SpecialItem.getInst().loadItems(); SpecialItem.getInst().loadItems();
// 载入 TLM 接口 // 载入 TLM 接口
@ -320,20 +240,34 @@ public class Main extends JavaPlugin implements Listener {
// 提示信息 // 提示信息
TLocale.Logger.error("NOTIFY.SUCCESS-DISABLE"); TLocale.Logger.error("NOTIFY.SUCCESS-DISABLE");
// 清理头衔
TagUtils.delete();
// 结束连接 // 结束连接
if (connection != null && connection.isConnection()) { if (connection != null && connection.isConnection()) {
connection.closeConnection(); connection.closeConnection();
} }
// 卸载牛逼玩意儿
TLib.unload(); TLib.unload();
// 关闭服务器 // 关闭服务器
Bukkit.shutdown(); Bukkit.shutdown();
} }
private void testInternet() {
try {
InetAddress inetAddress = InetAddress.getByName(getConfig().getString("TEST-URL", "aliyun.com"));
isInternetOnline = inetAddress.isReachable(10000);
} catch (Exception ignored) {
}
if (!isInternetOnline() && !isOfflineVersion() && !isLibrariesExists()) {
TLocale.Logger.error("TLIB.LOAD-FAIL-OFFLINE", getDescription().getVersion());
// 死锁
try {
Thread.sleep(Long.MAX_VALUE);
} catch (Exception ignored) {
}
}
}
private void setupDataFolder() { private void setupDataFolder() {
playerDataFolder = new File(getConfig().getString("DATAURL.PLAYER-DATA")); playerDataFolder = new File(getConfig().getString("DATAURL.PLAYER-DATA"));
if (!playerDataFolder.exists()) { if (!playerDataFolder.exists()) {
@ -345,11 +279,61 @@ public class Main extends JavaPlugin implements Listener {
} }
} }
private void setupLibraries() {
if (!isOfflineVersion()) {
return;
}
for (Dependency dependency : TDependencyInjector.getDependencies(TLib.getTLib())) {
if (dependency.type() == Dependency.Type.LIBRARY && dependency.maven().matches(".*:.*:.*")) {
String fileName = String.join("-", dependency.maven().split(":")) + ".jar";
File targetFile = FileUtils.file(TLib.getTLib().getLibsFolder(), fileName);
InputStream inputStream = FileUtils.getResource("libs/" + fileName);
if (!targetFile.exists() && inputStream != null) {
FileUtils.inputStreamToFile(inputStream, FileUtils.file(TLib.getTLib().getLibsFolder(), fileName));
}
}
}
}
private void setupDatabase() {
DataUtils.addPluginData("TabooLibrary", null);
if (getConfig().getBoolean("MYSQL.ENABLE")) {
connection = new MySQLConnection(getConfig().getString("MYSQL.HOST"), getConfig().getString("MYSQL.USER"), getConfig().getString("MYSQL.POST"), getConfig().getString("MYSQL.PASSWORD"), getConfig().getString("MYSQL.DATABASE"), 30, this);
if (connection.isConnection()) {
connection.createTable(getTablePrefix() + "_playerdata", "username", "configuration");
connection.createTable(getTablePrefix() + "_plugindata", "name", "variable", "upgrade");
connection.createTable(getTablePrefix() + "_serveruuid", "uuid", "hash");
if (!connection.isExists(getTablePrefix() + "_serveruuid", "uuid", TabooLib.getServerUID())) {
connection.intoValue(getTablePrefix() + "_serveruuid", TabooLib.getServerUID(), StringUtils.hashKeyForDisk(getDataFolder().getPath()));
} else {
String hash = connection.getValue(getTablePrefix() + "_serveruuid", "uuid", TabooLib.getServerUID(), "hash").toString();
if (!hash.equals(StringUtils.hashKeyForDisk(getDataFolder().getPath()))) {
TLocale.Logger.error("NOTIFY.ERROR-SERVER-KEY");
TabooLib.resetServerUID();
Bukkit.shutdown();
}
}
} else {
TLocale.Logger.error("NOTIFY.ERROR-CONNECTION-FAIL");
Bukkit.shutdown();
}
storageType = StorageType.SQL;
}
}
private void registerCommands() {
getCommand("language2").setExecutor(new Language2Command());
getCommand("taboolibrarymodule").setExecutor(new TLMCommands());
getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand());
TBaseCommand.registerCommand("taboolib", new TabooLibMainCommand());
TBaseCommand.registerCommand("taboolibplugin", new TabooLibPluginMainCommand());
}
private void registerListener() { private void registerListener() {
getServer().getPluginManager().registerEvents(this, this); getServer().getPluginManager().registerEvents(this, this);
getServer().getPluginManager().registerEvents(new ListenerPlayerCommand(), this); getServer().getPluginManager().registerEvents(new ListenerPlayerCommand(), this);
getServer().getPluginManager().registerEvents(new ListenerPlayerJump(), this); getServer().getPluginManager().registerEvents(new ListenerPlayerJump(), this);
getServer().getPluginManager().registerEvents(new ListenerPlayerQuit(), this); getServer().getPluginManager().registerEvents(new ListenerPlayerJoinAndQuit(), this);
getServer().getPluginManager().registerEvents(new ChatCatcher(), this); getServer().getPluginManager().registerEvents(new ChatCatcher(), this);
getServer().getPluginManager().registerEvents(new DataUtils(), this); getServer().getPluginManager().registerEvents(new DataUtils(), this);
getServer().getPluginManager().registerEvents(new AnvilContainerAPI(), this); getServer().getPluginManager().registerEvents(new AnvilContainerAPI(), this);
@ -368,7 +352,73 @@ public class Main extends JavaPlugin implements Listener {
} }
} }
public enum StorageType { // *********************************
LOCAL, SQL //
// Getter and Setter
//
// *********************************
public static Plugin getInst() {
return inst;
}
public static String getPrefix() {
return "§8[§3§lTabooLib§8] §7";
}
public static net.milkbowl.vault.economy.Economy getEconomy() {
return Economy;
}
public static void setEconomy(net.milkbowl.vault.economy.Economy economy) {
Economy = economy;
}
public static File getPlayerDataFolder() {
return playerDataFolder;
}
public static File getServerDataFolder() {
return serverDataFolder;
}
public static StorageType getStorageType() {
return storageType;
}
public static boolean isDisable() {
return disable;
}
public static MySQLConnection getConnection() {
return connection;
}
public static Language2 getExampleLanguage2() {
return exampleLanguage2;
}
public static boolean isStarted() {
return started;
}
public static Random getRandom() {
return NumberUtils.getRandom();
}
public static String getTablePrefix() {
return inst.getConfig().getString("MYSQL.PREFIX");
}
public static boolean isInternetOnline() {
return isInternetOnline;
}
public static boolean isOfflineVersion() {
return inst.getResource("libs") != null;
}
public static boolean isLibrariesExists() {
return TLib.getTLib().getLibsFolder().listFiles().length > 0;
} }
} }

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib; package me.skymc.taboolib;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.playerdata.DataUtils; import me.skymc.taboolib.playerdata.DataUtils;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -37,17 +38,17 @@ public class TabooLib {
} }
public static double getPluginVersion() { public static double getPluginVersion() {
try { return NumberUtils.getDouble(Main.getInst().getDescription().getVersion());
return Double.valueOf(Main.getInst().getDescription().getVersion());
} catch (Exception e) {
return 0D;
}
} }
public static String getVersion() { public static String getVersion() {
return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
} }
public static int getVersionNumber() {
return getVerint();
}
public static String getServerUID() { public static String getServerUID() {
if (!DataUtils.getPluginData("TabooLibrary", null).contains("serverUID")) { if (!DataUtils.getPluginData("TabooLibrary", null).contains("serverUID")) {
DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString());
@ -59,20 +60,22 @@ public class TabooLib {
DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString());
} }
@Deprecated
public static int getVerint() { public static int getVerint() {
if (getVersion().startsWith("v1_7")) { String version = getVersion();
if (version.startsWith("v1_7")) {
return 10700; return 10700;
} else if (getVersion().startsWith("v1_8")) { } else if (version.startsWith("v1_8")) {
return 10800; return 10800;
} else if (getVersion().startsWith("v1_9")) { } else if (version.startsWith("v1_9")) {
return 10900; return 10900;
} else if (getVersion().startsWith("v1_10")) { } else if (version.startsWith("v1_10")) {
return 11000; return 11000;
} else if (getVersion().startsWith("v1_11")) { } else if (version.startsWith("v1_11")) {
return 11100; return 11100;
} else if (getVersion().startsWith("v1_12")) { } else if (version.startsWith("v1_12")) {
return 11200; return 11200;
} else if (getVersion().startsWith("v1_13")) { } else if (version.startsWith("v1_13")) {
return 11300; return 11300;
} }
return 0; return 0;

View File

@ -1,8 +1,10 @@
package me.skymc.taboolib.bookformatter; package me.skymc.taboolib.bookformatter;
import net.md_5.bungee.api.chat.BaseComponent; import com.ilummc.tlib.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent; import com.ilummc.tlib.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer; import com.ilummc.tlib.bungee.chat.ComponentSerializer;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -12,6 +14,7 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -31,8 +34,10 @@ public final class BookReflection {
private static final Method craftPlayerGetHandle; private static final Method craftPlayerGetHandle;
//This method takes an enum that represents the player's hand only in versions >= 1.9 /*
//In the other versions it only takes the nms item This method takes an enum that represents the player's hand only in versions >= 1.9
In the other versions it only takes the nms item
*/
private static final Method entityPlayerOpenBook; private static final Method entityPlayerOpenBook;
// only version >= 1.9 // only version >= 1.9
@ -115,18 +120,22 @@ public final class BookReflection {
* @param meta the book meta to change * @param meta the book meta to change
* @param components the pages of the book * @param components the pages of the book
*/ */
@SuppressWarnings("unchecked")//reflections = unchecked warnings public static void setPages(BookMeta meta, BaseComponent[]... components) {
public static void setPages(BookMeta meta, BaseComponent[][] components) { List<Object> pages = null;
try { try {
List<Object> pages = (List<Object>) craftMetaBookField.get(meta); pages = (List<Object>) craftMetaBookField.get(meta);
} catch (Exception e) {
TLogger.getGlobalLogger().error("Error while executing reflections, failed to get bookmeta (version: " + BookReflection.version + ")");
return;
}
pages.clear(); pages.clear();
for (BaseComponent[] c : components) { for (BaseComponent[] c : components) {
final String json = ComponentSerializer.toString(c); try {
//System.out.println("page:" + json); //Debug pages.add(chatSerializerA.invoke(null, ComponentSerializer.toString(c)));
pages.add(chatSerializerA.invoke(null, json));
}
} catch (Exception e) { } catch (Exception e) {
throw new UnsupportedVersionException(e); TLogger.getGlobalLogger().error("Error while executing reflections, submit to developers the following log (version: " + BookReflection.version + ")");
e.printStackTrace();
}
} }
} }
@ -136,17 +145,21 @@ public final class BookReflection {
* @param meta the book meta to change * @param meta the book meta to change
* @param components the pages of the book * @param components the pages of the book
*/ */
@SuppressWarnings("unchecked")//reflections = unchecked warnings public static void addPages(BookMeta meta, BaseComponent[]... components) {
public static void addPages(BookMeta meta, BaseComponent[][] components) { List<Object> pages = null;
try { try {
List<Object> pages = (List<Object>) craftMetaBookField.get(meta); pages = (List<Object>) craftMetaBookField.get(meta);
for (BaseComponent[] c : components) {
final String json = ComponentSerializer.toString(c);
//System.out.println("page:" + json); //Debug
pages.add(chatSerializerA.invoke(null, json));
}
} catch (Exception e) { } catch (Exception e) {
throw new UnsupportedVersionException(e); TLogger.getGlobalLogger().error("Error while executing reflections, failed to get bookmeta (version: " + BookReflection.version + ")");
return;
}
for (BaseComponent[] c : components) {
try {
pages.add(chatSerializerA.invoke(null, ComponentSerializer.toString(c)));
} catch (Exception e) {
TLogger.getGlobalLogger().error("Error while executing reflections, submit to developers the following log (version: " + BookReflection.version + ")");
e.printStackTrace();
}
} }
} }

View File

@ -1,6 +1,6 @@
package me.skymc.taboolib.bookformatter.action; package me.skymc.taboolib.bookformatter.action;
import net.md_5.bungee.api.chat.ClickEvent; import com.ilummc.tlib.bungee.api.chat.ClickEvent;
/** /**
* @author sky * @author sky
@ -86,12 +86,12 @@ public interface ClickAction {
@Override @Override
public ClickEvent.Action action() { public ClickEvent.Action action() {
return null; return action;
} }
@Override @Override
public String value() { public String value() {
return null; return value;
} }
} }
} }

View File

@ -1,10 +1,10 @@
package me.skymc.taboolib.bookformatter.action; package me.skymc.taboolib.bookformatter.action;
import com.ilummc.tlib.bungee.api.chat.BaseComponent;
import com.ilummc.tlib.bungee.api.chat.HoverEvent;
import com.ilummc.tlib.bungee.api.chat.TextComponent;
import me.skymc.taboolib.bookformatter.BookAchievement; import me.skymc.taboolib.bookformatter.BookAchievement;
import me.skymc.taboolib.bookformatter.BookReflection; import me.skymc.taboolib.bookformatter.BookReflection;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Achievement; import org.bukkit.Achievement;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -157,12 +157,12 @@ public interface HoverAction {
@Override @Override
public HoverEvent.Action action() { public HoverEvent.Action action() {
return null; return action;
} }
@Override @Override
public BaseComponent[] value() { public BaseComponent[] value() {
return new BaseComponent[0]; return value;
} }
} }
} }

View File

@ -1,7 +1,7 @@
package me.skymc.taboolib.bookformatter.builder; package me.skymc.taboolib.bookformatter.builder;
import com.ilummc.tlib.bungee.api.chat.BaseComponent;
import me.skymc.taboolib.bookformatter.BookReflection; import me.skymc.taboolib.bookformatter.BookReflection;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.BookMeta;
@ -125,4 +125,19 @@ public class BookBuilder {
book.setItemMeta(meta); book.setItemMeta(meta);
return book; return book;
} }
// *********************************
//
// Getter and Setter
//
// *********************************
public BookMeta getMeta() {
return meta;
}
public ItemStack getBook() {
return book;
}
} }

View File

@ -1,7 +1,7 @@
package me.skymc.taboolib.bookformatter.builder; package me.skymc.taboolib.bookformatter.builder;
import net.md_5.bungee.api.chat.BaseComponent; import com.ilummc.tlib.bungee.api.chat.*;
import net.md_5.bungee.api.chat.TextComponent; import me.skymc.taboolib.string.ArrayUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -14,7 +14,7 @@ import java.util.List;
*/ */
public class PageBuilder { public class PageBuilder {
private List<BaseComponent> text = new ArrayList<>(); private BaseComponent[] text = TextComponent.fromLegacyText("");
/** /**
* Adds a simple black-colored text to the page * Adds a simple black-colored text to the page
@ -22,7 +22,7 @@ public class PageBuilder {
* @return the PageBuilder's calling instance * @return the PageBuilder's calling instance
*/ */
public PageBuilder add(String text) { public PageBuilder add(String text) {
this.text.add(TextBuilder.of(text).build()); Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> this.text = ArrayUtils.arrayAppend(this.text, component));
return this; return this;
} }
@ -32,7 +32,7 @@ public class PageBuilder {
* @return the PageBuilder's calling instance * @return the PageBuilder's calling instance
*/ */
public PageBuilder add(BaseComponent component) { public PageBuilder add(BaseComponent component) {
this.text.add(component); this.text = ArrayUtils.arrayAppend(this.text, component);
return this; return this;
} }
@ -42,17 +42,7 @@ public class PageBuilder {
* @return the PageBuilder's calling instance * @return the PageBuilder's calling instance
*/ */
public PageBuilder add(BaseComponent... components) { public PageBuilder add(BaseComponent... components) {
this.text.addAll(Arrays.asList(components)); Arrays.stream(components).forEach(component -> this.text = ArrayUtils.arrayAppend(this.text, component));
return this;
}
/**
* Adds one or more components to the page
* @param components the components to add
* @return the PageBuilder's calling instance
*/
public PageBuilder add(Collection<BaseComponent> components) {
this.text.addAll(components);
return this; return this;
} }
@ -61,8 +51,7 @@ public class PageBuilder {
* @return the PageBuilder's calling instance * @return the PageBuilder's calling instance
*/ */
public PageBuilder newLine() { public PageBuilder newLine() {
this.text.add(new TextComponent("\n")); return add("\n");
return this;
} }
/** /**
@ -78,10 +67,9 @@ public class PageBuilder {
* @return an array of BaseComponents representing the page * @return an array of BaseComponents representing the page
*/ */
public BaseComponent[] build() { public BaseComponent[] build() {
return text.toArray(new BaseComponent[0]); return text;
} }
/** /**
* Creates a new PageBuilder instance wih the parameter as the initial text * Creates a new PageBuilder instance wih the parameter as the initial text
* @param text the initial text of the page * @param text the initial text of the page

View File

@ -1,11 +1,8 @@
package me.skymc.taboolib.bookformatter.builder; package me.skymc.taboolib.bookformatter.builder;
import com.ilummc.tlib.bungee.api.chat.*;
import me.skymc.taboolib.bookformatter.action.ClickAction; import me.skymc.taboolib.bookformatter.action.ClickAction;
import me.skymc.taboolib.bookformatter.action.HoverAction; import me.skymc.taboolib.bookformatter.action.HoverAction;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
/** /**
* @author sky * @author sky

View File

@ -224,7 +224,7 @@ public class Metrics {
playerAmount = Bukkit.getOnlinePlayers().size(); playerAmount = Bukkit.getOnlinePlayers().size();
} }
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; 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); bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1);
// OS/Java specific data // OS/Java specific data

View File

@ -1,14 +1,24 @@
package me.skymc.taboolib.commands; package me.skymc.taboolib.commands;
import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.commands.internal.BaseMainCommand; import me.skymc.taboolib.commands.internal.BaseMainCommand;
import me.skymc.taboolib.commands.internal.BaseSubCommand; import me.skymc.taboolib.commands.internal.BaseSubCommand;
import me.skymc.taboolib.commands.internal.type.CommandArgument; import me.skymc.taboolib.commands.internal.type.CommandArgument;
import me.skymc.taboolib.commands.internal.type.CommandRegister; import me.skymc.taboolib.commands.internal.type.CommandRegister;
import me.skymc.taboolib.commands.internal.type.CommandType;
import me.skymc.taboolib.commands.taboolib.*; import me.skymc.taboolib.commands.taboolib.*;
import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.plugin.PluginUtils;
import me.skymc.taboolib.update.UpdateTask;
import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
/** /**
* @Author sky * @Author sky
@ -22,8 +32,7 @@ public class TabooLibMainCommand extends BaseMainCommand {
} }
@CommandRegister(priority = 1) @CommandRegister(priority = 1)
void save() { BaseSubCommand save = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -49,12 +58,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 2) @CommandRegister(priority = 2)
void item() { BaseSubCommand item = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -84,12 +91,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 3) @CommandRegister(priority = 3)
void itemInfo() { BaseSubCommand itemInfo = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -110,12 +115,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new InfoCommand(sender, args); new InfoCommand(sender, args);
} }
}); };
}
@CommandRegister(priority = 3.1) @CommandRegister(priority = 3.1)
void infoList() { BaseSubCommand infoList = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -141,12 +144,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 4) @CommandRegister(priority = 4)
void itemReload() { BaseSubCommand itemReload = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -169,17 +170,13 @@ public class TabooLibMainCommand extends BaseMainCommand {
ItemUtils.reloadItemName(); ItemUtils.reloadItemName();
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEMRELOAD.SUCCESS-RELOAD"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEMRELOAD.SUCCESS-RELOAD");
} }
}); };
}
@CommandRegister(priority = 5) @CommandRegister(priority = 5)
void emptyLine1() { BaseSubCommand emptyLine1 = null;
registerSubCommand(null);
}
@CommandRegister(priority = 6) @CommandRegister(priority = 6)
void attributes() { BaseSubCommand attributes = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -200,12 +197,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new AttributesCommand(sender, args); new AttributesCommand(sender, args);
} }
}); };
}
@CommandRegister(priority = 7) @CommandRegister(priority = 7)
void enchants() { BaseSubCommand enchants = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -226,12 +221,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new EnchantCommand(sender, args); new EnchantCommand(sender, args);
} }
}); };
}
@CommandRegister(priority = 8) @CommandRegister(priority = 8)
void potions() { BaseSubCommand potions = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -252,12 +245,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new PotionCommand(sender, args); new PotionCommand(sender, args);
} }
}); };
}
@CommandRegister(priority = 9) @CommandRegister(priority = 9)
void flags() { BaseSubCommand flags = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -278,12 +269,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new FlagCommand(sender, args); new FlagCommand(sender, args);
} }
}); };
}
@CommandRegister(priority = 10) @CommandRegister(priority = 10)
void slots() { BaseSubCommand slots = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -304,12 +293,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new AttributesCommand(sender, args); new AttributesCommand(sender, args);
} }
}); };
}
@CommandRegister(priority = 11) @CommandRegister(priority = 11)
void sounds() { BaseSubCommand sounds = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -335,17 +322,13 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 12) @CommandRegister(priority = 12)
void emptyLine2() { BaseSubCommand emptyLine2 = null;
registerSubCommand(null);
}
@CommandRegister(priority = 13) @CommandRegister(priority = 13)
void getVariable() { BaseSubCommand getVariable = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -374,12 +357,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 13.1) @CommandRegister(priority = 13.1)
void setVariable() { BaseSubCommand setVariable = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -409,17 +390,13 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 13.2) @CommandRegister(priority = 13.2)
void emptyLine3() { BaseSubCommand getEmptyLine3 = null;
registerSubCommand(null);
}
@CommandRegister(priority = 13.3) @CommandRegister(priority = 13.3)
void cycleList() { BaseSubCommand cycleList = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -440,12 +417,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new CycleListCommand(sender, args); new CycleListCommand(sender, args);
} }
}); };
}
@CommandRegister(priority = 14) @CommandRegister(priority = 14)
void cycleInfo() { BaseSubCommand cycleInfo = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -473,12 +448,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 15) @CommandRegister(priority = 15)
void cycleReset() { BaseSubCommand cycleReset = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -506,12 +479,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 16) @CommandRegister(priority = 16)
void cycleUpdate() { BaseSubCommand cycleUpdate = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -539,17 +510,13 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 17) @CommandRegister(priority = 17)
void emptyLine4() { BaseSubCommand getEmptyLine4 = null;
registerSubCommand(null);
}
@CommandRegister(priority = 18) @CommandRegister(priority = 18)
void shellLoad() { BaseSubCommand shellLoad = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -577,12 +544,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 19) @CommandRegister(priority = 19)
void shellUnload() { BaseSubCommand shellUnload = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -610,17 +575,13 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 20) @CommandRegister(priority = 20)
void emptyLine5() { BaseSubCommand getEmptyLine5 = null;
registerSubCommand(null);
}
@CommandRegister(priority = 20.5) @CommandRegister(priority = 20.5)
void tagDisplay() { BaseSubCommand tagDisplay = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -649,12 +610,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 21) @CommandRegister(priority = 21)
void tagPrefix() { BaseSubCommand tagPrefix = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -683,12 +642,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 22) @CommandRegister(priority = 22)
void tagSuffix() { BaseSubCommand tagSuffix = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -717,12 +674,10 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 23) @CommandRegister(priority = 23)
void tagDelete() { BaseSubCommand tagDelete = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -750,17 +705,13 @@ public class TabooLibMainCommand extends BaseMainCommand {
public boolean ignoredLabel() { public boolean ignoredLabel() {
return false; return false;
} }
}); };
}
@CommandRegister(priority = 24) @CommandRegister(priority = 24)
void emptyLine6() { BaseSubCommand getEmptyLine6 = null;
registerSubCommand(null);
}
@CommandRegister(priority = 25) @CommandRegister(priority = 25)
void importData() { BaseSubCommand importData = new BaseSubCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -781,6 +732,60 @@ public class TabooLibMainCommand extends BaseMainCommand {
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
new ImportCommand(sender, args); new ImportCommand(sender, args);
} }
}); };
@CommandRegister(priority = 26)
BaseSubCommand updatePlugin = new BaseSubCommand() {
@Override
public String getLabel() {
return "updatePlugin";
} }
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TABOOLIB.UPDATEPLUGIN.DESCRIPTION");
}
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[0];
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!UpdateTask.isHaveUpdate()) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-NOT-FOUND");
return;
}
File file = new File("plugins/update");
if (!file.exists()) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-NOT-SUPPORT");
return;
}
File pluginFile = PluginUtils.getPluginFile(Main.getInst());
if (pluginFile == null) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.FILE-NOT-FOUND");
return;
}
new BukkitRunnable() {
@Override
public void run() {
String url = Strings.replaceWithOrder("https://github.com/Bkm016/TabooLib/releases/download/{0}/TabooLib-{0}.jar", UpdateTask.getNewVersion());
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-START", url);
FileUtils.download(url, new File(file, pluginFile.getName()));
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-SUCCESS");
}
}.runTaskAsynchronously(Main.getInst());
}
@Override
public CommandType getType() {
return CommandType.CONSOLE;
}
};
} }

View File

@ -2,10 +2,9 @@ package me.skymc.taboolib.commands.internal;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.ilummc.tlib.resources.TLocale; 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.Main;
import me.skymc.taboolib.TabooLib; 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.CommandRegister;
import me.skymc.taboolib.commands.internal.type.CommandType; import me.skymc.taboolib.commands.internal.type.CommandType;
import me.skymc.taboolib.string.ArrayUtils; import me.skymc.taboolib.string.ArrayUtils;
@ -47,6 +46,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
public static void loadCommandRegister(BaseMainCommand baseMainCommand) { public static void loadCommandRegister(BaseMainCommand baseMainCommand) {
List<Method> methods = new ArrayList<>(); 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)); baseMainCommand.getLinkClasses().forEach(clazz -> Arrays.stream(clazz.getDeclaredMethods()).filter(method -> method.getAnnotation(CommandRegister.class) != null).forEach(methods::add));
if (methods.size() > 0) { if (methods.size() > 0) {
methods.sort(Comparator.comparingDouble(a -> a.getAnnotation(CommandRegister.class).priority())); 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) { 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))));
TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-REGISTER", baseMainCommand.getRegisterCommand().getPlugin().getName(), baseMainCommand.getRegisterCommand().getName(), String.valueOf(methods.size())); 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,11 +105,11 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
helpCommand(sender, label); helpCommand(sender, label);
} else { } else {
for (BaseSubCommand subCommand : subCommands) { for (BaseSubCommand subCommand : subCommands) {
if (subCommand == null || !args[0].equalsIgnoreCase(subCommand.getLabel())) { if (subCommand == null || !args[0].equalsIgnoreCase(subCommand.getLabel()) || !hasPermission(sender, subCommand)) {
continue; continue;
} }
if (!isConfirmType(sender, subCommand.getType())) { if (!isConfirmType(sender, subCommand.getType())) {
TLocale.sendTo(sender, "COMMANDS.INTERNAL.ONLY-PLAYER", args[0], TLocale.asString("COMMANDS.INTERNAL.TYPE-" + subCommand.getType())); TLocale.sendTo(sender, "COMMANDS.INTERNAL.TYPE-ERROR", args[0], TLocale.asString("COMMANDS.INTERNAL.TYPE-" + subCommand.getType()));
return true; return true;
} }
String[] subCommandArgs = ArrayUtils.removeFirst(args); String[] subCommandArgs = ArrayUtils.removeFirst(args);
@ -113,7 +124,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
@Override @Override
public void run() { 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) { if (commandCompute.size() > 0) {
TLocale.sendTo(sender, "COMMANDS.INTERNAL.ERROR-COMMAND", args[0], commandCompute.get(0).getCommandString(label).trim()); 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 @Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { 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 @Override
@ -155,14 +166,16 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
} }
private boolean isConfirmType(CommandSender sender, CommandType commandType) { private boolean isConfirmType(CommandSender sender, CommandType commandType) {
return commandType == CommandType.ALL || (sender instanceof Player && commandType == CommandType.PLAYER); return commandType == CommandType.ALL
|| (sender instanceof Player && commandType == CommandType.PLAYER)
|| (sender instanceof ConsoleCommandSender && commandType == CommandType.CONSOLE);
} }
private void helpCommand(CommandSender sender, String label) { private void helpCommand(CommandSender sender, String label) {
sender.sendMessage(getEmptyLine()); sender.sendMessage(getEmptyLine());
sender.sendMessage(getCommandTitle()); sender.sendMessage(getCommandTitle());
sender.sendMessage(getEmptyLine()); 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()); sender.sendMessage(getEmptyLine());
} }
@ -178,4 +191,8 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor,
} catch (Exception ignored) { } 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; 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 me.skymc.taboolib.commands.internal.type.CommandType;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
/** /**
@ -23,23 +25,16 @@ public abstract class BaseSubCommand implements ISubCommand {
return false; return false;
} }
public String getPermission() {
return null;
}
public boolean isParameterConform(String[] args) { public boolean isParameterConform(String[] args) {
return IntStream.range(0, getArguments().length).noneMatch(i -> getArguments()[i].isRequired() && (args == null || args.length <= i)); return IntStream.range(0, getArguments().length).noneMatch(i -> getArguments()[i].isRequired() && (args == null || args.length <= i));
} }
public String getCommandString(String label) { public String getCommandString(String label) {
StringBuilder stringBuilder = new StringBuilder(); String stringBuilder = Arrays.stream(getArguments()).map(parameter -> parameter.toString() + " ").collect(Collectors.joining());
stringBuilder.append(" §f/"); return TLocale.asString("COMMANDS.INTERNAL.COMMAND-HELP", label, getLabel(), stringBuilder.trim(), getDescription());
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();
} }
} }

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; package me.skymc.taboolib.commands.internal.type;
import com.ilummc.tlib.resources.TLocale;
import java.util.Objects; import java.util.Objects;
/** /**
@ -30,7 +32,7 @@ public class CommandArgument {
@Override @Override
public String toString() { 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 @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 * @Author sky
* @Since 2018-05-09 22:38 * @Since 2018-05-09 22:38
*/ */
@Target(ElementType.METHOD) @Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface CommandRegister { public @interface CommandRegister {

View File

@ -6,6 +6,10 @@ import me.skymc.taboolib.commands.internal.BaseMainCommand;
import me.skymc.taboolib.commands.internal.BaseSubCommand; import me.skymc.taboolib.commands.internal.BaseSubCommand;
import me.skymc.taboolib.commands.internal.ISubCommand; import me.skymc.taboolib.commands.internal.ISubCommand;
import me.skymc.taboolib.commands.internal.type.CommandArgument; import me.skymc.taboolib.commands.internal.type.CommandArgument;
import me.skymc.taboolib.commands.internal.type.CommandRegister;
import me.skymc.taboolib.plugin.PluginLoadState;
import me.skymc.taboolib.plugin.PluginLoadStateType;
import me.skymc.taboolib.plugin.PluginUnloadState;
import me.skymc.taboolib.plugin.PluginUtils; import me.skymc.taboolib.plugin.PluginUtils;
import me.skymc.taboolib.string.ArrayUtils; import me.skymc.taboolib.string.ArrayUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -13,7 +17,6 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -24,12 +27,9 @@ import java.util.stream.Collectors;
*/ */
public class TabooLibPluginMainCommand extends BaseMainCommand { public class TabooLibPluginMainCommand extends BaseMainCommand {
public TabooLibPluginMainCommand() { @Override
listCommand(); public String getCommandTitle() {
infoCommand(); return TLocale.asString("COMMANDS.TPLUGIN.COMMAND-TITLE");
loadCommand();
unloadCommand();
reloadCommand();
} }
@Override @Override
@ -43,17 +43,8 @@ public class TabooLibPluginMainCommand extends BaseMainCommand {
} }
} }
private boolean isPluginCommand(String label) { @CommandRegister(priority = 1)
return "info".equalsIgnoreCase(label) || "load".equalsIgnoreCase(label) || "unload".equalsIgnoreCase(label) || "reload".equalsIgnoreCase(label); BaseSubCommand load = new BaseSubCommand() {
}
@Override
public String getCommandTitle() {
return TLocale.asString("COMMANDS.TPLUGIN.COMMAND-TITLE");
}
void loadCommand() {
registerSubCommand(new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -74,24 +65,36 @@ public class TabooLibPluginMainCommand extends BaseMainCommand {
public void onCommand(CommandSender sender, Command command, String label, String[] args) { public void onCommand(CommandSender sender, Command command, String label, String[] args) {
String name = ArrayUtils.arrayJoin(args, 0); String name = ArrayUtils.arrayJoin(args, 0);
if (PluginUtils.getPluginByName(name) != null) { if (PluginUtils.getPluginByName(name) != null) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name); TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name, name + " already loaded!");
} else { } else {
switch (PluginUtils.load(name)) { PluginLoadState loadState;
case "loaded": { try {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-SUCCESS", name); loadState = PluginUtils.load(name);
} catch (Exception e) {
loadState = new PluginLoadState(PluginLoadStateType.INVALID_PLUGIN, e.toString());
}
switch (loadState.getStateType()) {
case INVALID_DESCRIPTION: {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-DESCRIPTION");
break; break;
} }
default: { case INVALID_PLUGIN: {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-FAIL", name); TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name, loadState.getMessage());
break;
}
case FILE_NOT_FOUND: {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.FILE-NOT-FOUND", name);
break;
}
default:
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-SUCCESS", name);
} }
} }
} }
} };
});
}
void unloadCommand() { @CommandRegister(priority = 2)
registerSubCommand(new BaseSubCommand() { BaseSubCommand unload = new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -117,22 +120,23 @@ public class TabooLibPluginMainCommand extends BaseMainCommand {
} else if (PluginUtils.isIgnored(plugin)) { } else if (PluginUtils.isIgnored(plugin)) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN-IGNORED", name); TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN-IGNORED", name);
} else { } else {
switch (PluginUtils.unload(plugin)) { PluginUnloadState unloadState;
case "unloaded": { try {
unloadState = PluginUtils.unload(plugin);
} catch (Exception e) {
unloadState = new PluginUnloadState(true, e.toString());
}
if (unloadState.isFailed()) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-FAIL", name, unloadState.getMessage());
} else {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-SUCCESS", name); TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-SUCCESS", name);
break;
}
default: {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-FAIL", name);
} }
} }
} }
} };
});
}
void reloadCommand() { @CommandRegister(priority = 3)
registerSubCommand(new BaseSubCommand() { BaseSubCommand reload = new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -162,11 +166,10 @@ public class TabooLibPluginMainCommand extends BaseMainCommand {
PluginUtils.reload(plugin); PluginUtils.reload(plugin);
} }
} }
}); };
}
void infoCommand() { @CommandRegister(priority = 4)
registerSubCommand(new BaseSubCommand() { BaseSubCommand info = new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -200,17 +203,16 @@ public class TabooLibPluginMainCommand extends BaseMainCommand {
String.valueOf(plugin.getDescription().getMain()), String.valueOf(plugin.getDescription().getMain()),
String.valueOf(plugin.getDescription().getVersion()), String.valueOf(plugin.getDescription().getVersion()),
String.valueOf(plugin.getDescription().getWebsite()), String.valueOf(plugin.getDescription().getWebsite()),
String.valueOf(plugin.getDescription().getCommands().keySet())); String.valueOf(plugin.getDescription().getCommands() == null ? "" : plugin.getDescription().getCommands().keySet()));
} catch (Exception ignored) { } catch (Exception e) {
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name); TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-DESCRIPTION", name, e.getMessage());
} }
} }
} }
}); };
}
void listCommand() { @CommandRegister(priority = 5)
registerSubCommand(new BaseSubCommand() { BaseSubCommand list = new BaseSubCommand() {
@Override @Override
public String getLabel() { public String getLabel() {
@ -229,9 +231,18 @@ public class TabooLibPluginMainCommand extends BaseMainCommand {
@Override @Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) { 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()); List<String> pluginList = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(PluginUtils::getFormattedName).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)); 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);
} }
} }

View File

@ -13,7 +13,7 @@ public class CycleInfoCommand extends SubCommand {
public CycleInfoCommand(CommandSender sender, String[] args) { public CycleInfoCommand(CommandSender sender, String[] args) {
super(sender, args); super(sender, args);
if (args.length < 3) { if (args.length < 2) {
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
return; return;
} }

View File

@ -16,7 +16,7 @@ public class CycleResetCommand extends SubCommand {
public CycleResetCommand(CommandSender sender, String[] args) { public CycleResetCommand(CommandSender sender, String[] args) {
super(sender, args); super(sender, args);
if (args.length < 3) { if (args.length < 2) {
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
return; return;
} }

View File

@ -15,7 +15,7 @@ public class CycleUpdateCommand extends SubCommand {
public CycleUpdateCommand(CommandSender sender, String[] args) { public CycleUpdateCommand(CommandSender sender, String[] args) {
super(sender, args); super(sender, args);
if (args.length < 3) { if (args.length < 2) {
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
return; return;
} }

View File

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

View File

@ -11,7 +11,7 @@ public class ShellLoadCommand extends SubCommand {
public ShellLoadCommand(CommandSender sender, String[] args) { public ShellLoadCommand(CommandSender sender, String[] args) {
super(sender, args); super(sender, args);
if (args.length < 3) { if (args.length < 2) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME");
return; return;
} }

View File

@ -11,7 +11,7 @@ public class ShellUnloadCommand extends SubCommand {
public ShellUnloadCommand(CommandSender sender, String[] args) { public ShellUnloadCommand(CommandSender sender, String[] args) {
super(sender, args); super(sender, args);
if (args.length < 3) { if (args.length < 2) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME");
return; return;
} }

View File

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

View File

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

View File

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

View File

@ -1,14 +1,20 @@
package me.skymc.taboolib.fileutils; package me.skymc.taboolib.fileutils;
import ch.njol.util.Closeable; import ch.njol.util.Closeable;
import com.ilummc.tlib.util.IO;
import javafx.print.PageLayout;
import me.skymc.taboolib.Main;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.bukkit.plugin.Plugin;
import java.io.*; import java.io.*;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.Objects; import java.util.Objects;
import java.util.logging.Level;
public class FileUtils { public class FileUtils {
@ -43,6 +49,35 @@ public class FileUtils {
} }
} }
public static InputStream getResource(String filename) {
return getResource(Main.getInst(), filename);
}
public static InputStream getResource(Plugin plugin, String filename) {
try {
URL url = plugin.getClass().getClassLoader().getResource(filename);
if (url == null) {
return null;
} else {
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
}
} catch (IOException ignored) {
return null;
}
}
public static void inputStreamToFile(InputStream inputStream, File file) {
try {
String text = new String(IO.readFully(inputStream), Charset.forName("utf-8"));
FileWriter fileWriter = new FileWriter(FileUtils.createNewFile(file));
fileWriter.write(text);
fileWriter.close();
} catch (IOException ignored) {
}
}
/** /**
* 检测文件并创建 * 检测文件并创建
* *
@ -84,7 +119,7 @@ public class FileUtils {
* *
* @param file 文件夹 * @param file 文件夹
*/ */
public void deleteAllFile(File file) { public static void deleteAllFile(File file) {
if (!file.exists()) { if (!file.exists()) {
return; return;
} }
@ -104,7 +139,7 @@ public class FileUtils {
* @param file1 文件1 * @param file1 文件1
* @param file2 文件2 * @param file2 文件2
*/ */
public void copyAllFile(String file1, String file2) { public static void copyAllFile(String file1, String file2) {
File _file1 = new File(file1); File _file1 = new File(file1);
File _file2 = new File(file2); File _file2 = new File(file2);
if (!_file2.exists()) { if (!_file2.exists()) {
@ -133,7 +168,7 @@ public class FileUtils {
* @param file1 文件1 * @param file1 文件1
* @param file2 文件2 * @param file2 文件2
*/ */
public void fileChannelCopy(File file1, File file2) { public static void fileChannelCopy(File file1, File file2) {
FileInputStream fileIn = null; FileInputStream fileIn = null;
FileOutputStream fileOut = null; FileOutputStream fileOut = null;
FileChannel channelIn = null; FileChannel channelIn = null;

View File

@ -402,7 +402,7 @@ public class ItemUtils {
return section.getItemStack("bukkit"); return section.getItemStack("bukkit");
} }
// 材质 // 材质
ItemStack item = new ItemStack(asMaterial(section.get("material").toString())); ItemStack item = new ItemStack(asMaterial(section.getString("material")));
// 数量 // 数量
item.setAmount(section.contains("amount") ? section.getInt("amount") : 1); item.setAmount(section.contains("amount") ? section.getInt("amount") : 1);
// 耐久 // 耐久

View File

@ -0,0 +1,192 @@
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.EventPriority;
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 (priority = EventPriority.MONITOR)
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,137 @@
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.EventPriority;
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,88 @@
package me.skymc.taboolib.itagapi;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.text.MessageFormat;
import java.util.Objects;
import java.util.UUID;
/**
* @Author sky
* @Since 2018-05-21 15:07
*/
public class TagPlayerData {
private final UUID uuid;
private final String nameOrigin;
private String nameDisplay;
private String prefix;
private String suffix;
public TagPlayerData(Player player) {
this.uuid = player.getUniqueId();
this.nameOrigin = player.getName();
this.nameDisplay = player.getName();
this.prefix = "";
this.suffix = "";
}
public String getTeamHash() {
return Main.getInst().getConfig().getBoolean("TABLIST-SORT") ? String.valueOf(Objects.hash(prefix)) : nameOrigin;
}
public TagPlayerData reset() {
this.nameDisplay = getNameOrigin();
this.prefix = "";
this.suffix = "";
return this;
}
@Override
public String toString() {
return Strings.replaceWithOrder("TagPlayerData'{'uuid={0}, nameOrigin=''{1}'', nameDisplay=''{2}'', prefix=''{3}'', suffix=''{4}'''}'", uuid, nameOrigin, nameDisplay, prefix, suffix);
}
// *********************************
//
// Getter and Setter
//
// *********************************
public UUID getUUID() {
return uuid;
}
public String getNameOrigin() {
return nameOrigin;
}
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

@ -0,0 +1,133 @@
package me.skymc.taboolib.json.tellraw;
import com.ilummc.tlib.bungee.api.chat.*;
import com.ilummc.tlib.bungee.chat.ComponentSerializer;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.methods.ReflectionUtils;
import me.skymc.taboolib.nms.NMSUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.string.ArrayUtils;
import me.skymc.taboolib.string.VariableFormatter;
import org.bukkit.command.CommandSender;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @Author sky
* @Since 2018-05-26 14:42json
*/
public class TellrawJson {
private BaseComponent[] components = TextComponent.fromLegacyText("");
private final Class<?> craftItemStackClazz = NMSUtils.getOBCClass("inventory.CraftItemStack");
private final Class<?> nmsItemStackClazz = NMSUtils.getNMSClass("ItemStack");
private final Class<?> nbtTagCompoundClazz = NMSUtils.getNMSClass("NBTTagCompound");
private final String INVALID_ITEM = "{id:stone,tag:{display:{Name:§c* Invalid ItemStack *}}}";
TellrawJson() {
}
public static TellrawJson create() {
return new TellrawJson();
}
public String toRawMessage() {
return ComponentSerializer.toString(components);
}
public String toLegacyText() {
return TextComponent.toLegacyText(components);
}
public TellrawJson newLine() {
return append("\n");
}
public TellrawJson append(String text) {
Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> this.components = ArrayUtils.arrayAppend(this.components, component));
return this;
}
public TellrawJson hoverText(String text) {
getLatestComponent().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(text).create()));
return this;
}
public TellrawJson hoverItem(ItemStack itemStack) {
getLatestComponent().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, new ComponentBuilder(getItemComponent(itemStack)).create()));
return this;
}
public TellrawJson clickCommand(String command) {
getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command));
return this;
}
public TellrawJson clickSuggest(String command) {
getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, command));
return this;
}
public TellrawJson clickOpenURL(String url) {
getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
return this;
}
public TellrawJson clickChangePage(int page) {
getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, String.valueOf(page)));
return this;
}
public void send(CommandSender sender) {
TLocale.Tellraw.send(sender, toRawMessage());
}
public String getItemComponent(ItemStack itemStack) {
try {
Method asNMSCopyMethod = ReflectionUtils.getMethod(craftItemStackClazz, "asNMSCopy", ItemStack.class);
Method saveNmsItemStackMethod = ReflectionUtils.getMethod(nmsItemStackClazz, "save", nbtTagCompoundClazz);
Object nmsNbtTagCompoundObj = nbtTagCompoundClazz.newInstance();
Object nmsItemStackObj = asNMSCopyMethod.invoke(null, itemStack);
return saveNmsItemStackMethod.invoke(nmsItemStackObj, nmsNbtTagCompoundObj).toString();
} catch (Throwable t) {
TLogger.getGlobalLogger().error("failed to serialize itemstack to nms item: " + t.toString());
return INVALID_ITEM;
}
}
// *********************************
//
// Private Methods
//
// *********************************
private BaseComponent getLatestComponent() {
return components[components.length - 1];
}
private void setLatestComponent(BaseComponent component) {
components[components.length - 1] = component;
}
// *********************************
//
// Getter and Setter
//
// *********************************
public BaseComponent[] getComponents() {
return components;
}
public void setComponents(BaseComponent[] components) {
this.components = components;
}
}

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib.jsonformatter; package me.skymc.taboolib.jsonformatter;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.json.JSONArray; import me.skymc.taboolib.json.JSONArray;
import me.skymc.taboolib.json.JSONObject; import me.skymc.taboolib.json.JSONObject;
import me.skymc.taboolib.jsonformatter.click.ClickEvent; import me.skymc.taboolib.jsonformatter.click.ClickEvent;
@ -15,17 +16,14 @@ import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/**
* @author Unknown
*/
@Deprecated
public class JSONFormatter { public class JSONFormatter {
public static void sendRawMessage(Player player, String message) { public static void sendRawMessage(Player player, String message) {
try { TLocale.Tellraw.send(player, message);
Object entityplayer = NMSUtils.getHandle(player);
Object ppco = ppc.get(entityplayer);
Object packet = ppocc.newInstance(message);
sp.invoke(ppco, packet);
} catch (Exception e) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + message);
}
} }
private JSONArray ja = new JSONArray(); private JSONArray ja = new JSONArray();

View File

@ -3,6 +3,7 @@ package me.skymc.taboolib.jsonformatter.hover;
import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.json.JSONObject; import me.skymc.taboolib.json.JSONObject;
import me.skymc.taboolib.json.tellraw.TellrawJson;
import me.skymc.taboolib.nms.item.DabItemUtils; import me.skymc.taboolib.nms.item.DabItemUtils;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -27,14 +28,20 @@ public class ShowItemEvent extends HoverEvent{
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public ShowItemEvent(ItemStack is) { public ShowItemEvent(ItemStack is) {
if (TabooLib.getVerint() > 10700) {
try {
object.put("action", "show_item");
object.put("value", TellrawJson.create().getItemComponent(is));
} catch (Exception ignored) {
}
}
try { try {
object.put("action", "show_item"); object.put("action", "show_item");
StringBuilder tag = new StringBuilder(); StringBuilder tag = new StringBuilder();
Object itemTag = getItemTag(is); Object itemTag = getItemTag(is);
if (itemTag != null) { if (itemTag != null) {
tag.append(",tag:").append(itemTag); tag.append(",tag:").append(itemTag);
} } else {
else {
ItemMeta im = is.getItemMeta(); ItemMeta im = is.getItemMeta();
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<>(); List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<>();
Map<Enchantment, Integer> enchants = is.getItemMeta().getEnchants(); Map<Enchantment, Integer> enchants = is.getItemMeta().getEnchants();
@ -61,10 +68,8 @@ public class ShowItemEvent extends HoverEvent{
} }
tag.append("}"); tag.append("}");
} }
object.put("value", "{id:" + (TabooLib.getVerint() > 10700 ? DabItemUtils.getMinecraftName(is) : is.getTypeId()) + ",Count:" + is.getAmount() + tag.toString() + "}"); object.put("value", "{id:" + (TabooLib.getVerint() > 10700 ? DabItemUtils.getMinecraftName(is) : is.getTypeId()) + ",Count:" + is.getAmount() + tag.toString() + "}");
} catch(Exception e) { } catch (Exception ignored) {
e.printStackTrace();
} }
} }

View File

@ -0,0 +1,26 @@
package me.skymc.taboolib.listener;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.taboolib.update.UpdateTask;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class ListenerPlayerJoinAndQuit implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent e) {
if (UpdateTask.isHaveUpdate() && e.getPlayer().hasPermission("taboolib.update.notify")) {
TLocale.Logger.sendTo(e.getPlayer(), "UPDATETASK.VERSION-OUTDATED", String.valueOf(TabooLib.getPluginVersion()), String.valueOf(UpdateTask.getNewVersion()));
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent e) {
DataUtils.saveOnline(e.getPlayer().getName());
}
}

View File

@ -1,15 +0,0 @@
package me.skymc.taboolib.listener;
import me.skymc.taboolib.playerdata.DataUtils;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
public class ListenerPlayerQuit implements Listener{
@EventHandler (priority = EventPriority.MONITOR)
public void quit(PlayerQuitEvent e) {
DataUtils.saveOnline(e.getPlayer().getName());
}
}

View File

@ -10,11 +10,6 @@ import java.util.Arrays;
*/ */
public class SQLColumn { public class SQLColumn {
public static void main(String[] args) {
SQLColumn column2 = new SQLColumn(SQLColumnType.INT, "player_title", "");
System.out.println(column2.convertToCommand());
}
/** /**
* 类型 * 类型
*/ */

View File

@ -20,8 +20,10 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
/**
* @author Unknown
*/
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
@Deprecated
public class NMSUtil18 { public class NMSUtil18 {
protected static boolean failed = false; protected static boolean failed = false;
@ -313,7 +315,7 @@ public class NMSUtil18 {
class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class); class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class);
class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class); class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class);
class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE); 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_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack);
class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack); class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack);
class_ItemStack_createStackMethod = class_ItemStack.getMethod("createStack", class_NBTTagCompound); class_ItemStack_createStackMethod = class_ItemStack.getMethod("createStack", class_NBTTagCompound);
@ -526,7 +528,7 @@ public class NMSUtil18 {
return NMSUtil18.class.getClassLoader().loadClass(className); return NMSUtil18.class.getClassLoader().loadClass(className);
} }
public static Object getHandle(org.bukkit.inventory.ItemStack stack) { public static Object getHandle(ItemStack stack) {
Object handle = null; Object handle = null;
try { try {
handle = class_CraftItemStack_getHandleField.get(stack); handle = class_CraftItemStack_getHandleField.get(stack);
@ -536,7 +538,7 @@ public class NMSUtil18 {
return handle; return handle;
} }
public static Object getHandle(org.bukkit.World world) { public static Object getHandle(World world) {
if (world == null) { if (world == null) {
return null; return null;
} }
@ -549,7 +551,7 @@ public class NMSUtil18 {
return handle; return handle;
} }
public static Object getHandle(org.bukkit.entity.Entity entity) { public static Object getHandle(Entity entity) {
if (entity == null) { if (entity == null) {
return null; return null;
} }
@ -575,7 +577,7 @@ public class NMSUtil18 {
return handle; return handle;
} }
public static boolean isDone(org.bukkit.Chunk chunk) { public static boolean isDone(Chunk chunk) {
Object chunkHandle = getHandle(chunk); Object chunkHandle = getHandle(chunk);
boolean done = false; boolean done = false;
try { try {
@ -586,7 +588,7 @@ public class NMSUtil18 {
return done; return done;
} }
public static Object getHandle(org.bukkit.Chunk chunk) { public static Object getHandle(Chunk chunk) {
Object handle = null; Object handle = null;
try { try {
handle = class_CraftChunk_getHandleMethod.invoke(chunk); handle = class_CraftChunk_getHandleMethod.invoke(chunk);
@ -596,7 +598,7 @@ public class NMSUtil18 {
return handle; return handle;
} }
public static Object getHandle(org.bukkit.entity.Player player) { public static Object getHandle(Player player) {
Object handle = null; Object handle = null;
try { try {
handle = class_CraftPlayer_getHandleMethod.invoke(player); handle = class_CraftPlayer_getHandleMethod.invoke(player);
@ -652,17 +654,17 @@ public class NMSUtil18 {
return dir; return dir;
} }
public static org.bukkit.entity.Entity getBukkitEntity(Object entity) { public static Entity getBukkitEntity(Object entity) {
if (entity == null) { if (entity == null) {
return null; return null;
} }
try { try {
Method getMethod = entity.getClass().getMethod("getBukkitEntity"); Method getMethod = entity.getClass().getMethod("getBukkitEntity");
Object bukkitEntity = getMethod.invoke(entity); Object bukkitEntity = getMethod.invoke(entity);
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) { if (!(bukkitEntity instanceof Entity)) {
return null; return null;
} }
return (org.bukkit.entity.Entity) bukkitEntity; return (Entity) bukkitEntity;
} catch (Throwable ex) { } catch (Throwable ex) {
ex.printStackTrace(); ex.printStackTrace();
} }

View File

@ -22,8 +22,10 @@ import java.lang.reflect.Method;
import java.util.*; import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
/**
* @author Unknown
*/
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
@Deprecated
public class NMSUtil19 { public class NMSUtil19 {
protected static boolean failed = false; protected static boolean failed = false;
@ -40,91 +42,91 @@ public class NMSUtil19 {
protected static int WITHER_SKULL_TYPE = 66; protected static int WITHER_SKULL_TYPE = 66;
protected static int FIREWORK_TYPE = 76; protected static int FIREWORK_TYPE = 76;
protected static Class<?> class_Block; public static Class<?> class_Block;
protected static Class<?> class_ItemStack; public static Class<?> class_ItemStack;
protected static Class<?> class_NBTBase; public static Class<?> class_NBTBase;
protected static Class<?> class_NBTTagCompound; public static Class<?> class_NBTTagCompound;
protected static Class<?> class_NBTTagList; public static Class<?> class_NBTTagList;
protected static Class<?> class_NBTTagByte; public static Class<?> class_NBTTagByte;
protected static Class<?> class_NBTTagDouble; public static Class<?> class_NBTTagDouble;
protected static Class<?> class_NBTTagFloat; public static Class<?> class_NBTTagFloat;
protected static Class<?> class_NBTTagInt; public static Class<?> class_NBTTagInt;
protected static Class<?> class_NBTTagLong; public static Class<?> class_NBTTagLong;
protected static Class<?> class_NBTTagShort; public static Class<?> class_NBTTagShort;
protected static Class<?> class_NBTTagString; public static Class<?> class_NBTTagString;
protected static Class<?> class_CraftTask; public static Class<?> class_CraftTask;
protected static Class<?> class_CraftInventoryCustom; public static Class<?> class_CraftInventoryCustom;
protected static Class<?> class_CraftItemStack; public static Class<?> class_CraftItemStack;
protected static Class<?> class_CraftBlockState; public static Class<?> class_CraftBlockState;
protected static Class<?> class_CraftLivingEntity; public static Class<?> class_CraftLivingEntity;
protected static Class<?> class_CraftWorld; public static Class<?> class_CraftWorld;
protected static Class<?> class_Consumer; public static Class<?> class_Consumer;
protected static Class<?> class_Entity; public static Class<?> class_Entity;
protected static Class<?> class_EntityCreature; public static Class<?> class_EntityCreature;
protected static Class<?> class_EntityLiving; public static Class<?> class_EntityLiving;
protected static Class<?> class_EntityHuman; public static Class<?> class_EntityHuman;
protected static Class<?> class_DataWatcher; public static Class<?> class_DataWatcher;
protected static Class<?> class_DamageSource; public static Class<?> class_DamageSource;
protected static Class<?> class_EntityDamageSource; public static Class<?> class_EntityDamageSource;
protected static Class<?> class_World; public static Class<?> class_World;
protected static Class<?> class_WorldServer; public static Class<?> class_WorldServer;
protected static Class<?> class_Packet; public static Class<?> class_Packet;
protected static Class<Enum> class_EnumSkyBlock; protected static Class<Enum> class_EnumSkyBlock;
protected static Class<?> class_EntityPainting; public static Class<?> class_EntityPainting;
protected static Class<?> class_EntityItemFrame; public static Class<?> class_EntityItemFrame;
protected static Class<?> class_EntityMinecartRideable; public static Class<?> class_EntityMinecartRideable;
protected static Class<?> class_EntityTNTPrimed; public static Class<?> class_EntityTNTPrimed;
protected static Class<?> class_AxisAlignedBB; public static Class<?> class_AxisAlignedBB;
protected static Class<?> class_PathPoint; public static Class<?> class_PathPoint;
protected static Class<?> class_PathEntity; public static Class<?> class_PathEntity;
protected static Class<?> class_EntityFirework; public static Class<?> class_EntityFirework;
protected static Class<?> class_CraftSkull; public static Class<?> class_CraftSkull;
protected static Class<?> class_CraftBanner; public static Class<?> class_CraftBanner;
protected static Class<?> class_CraftMetaSkull; public static Class<?> class_CraftMetaSkull;
protected static Class<?> class_CraftMetaBanner; public static Class<?> class_CraftMetaBanner;
protected static Class<?> class_GameProfile; public static Class<?> class_GameProfile;
protected static Class<?> class_GameProfileProperty; public static Class<?> class_GameProfileProperty;
protected static Class<?> class_BlockPosition; public static Class<?> class_BlockPosition;
protected static Class<?> class_NBTCompressedStreamTools; public static Class<?> class_NBTCompressedStreamTools;
protected static Class<?> class_TileEntity; public static Class<?> class_TileEntity;
protected static Class<?> class_TileEntitySign; public static Class<?> class_TileEntitySign;
protected static Class<?> class_TileEntityContainer; public static Class<?> class_TileEntityContainer;
protected static Class<?> class_ChestLock; public static Class<?> class_ChestLock;
protected static Class<Enum> class_EnumDirection; protected static Class<Enum> class_EnumDirection;
protected static Class<?> class_EntityHorse; public static Class<?> class_EntityHorse;
protected static Class<?> class_EntityWitherSkull; public static Class<?> class_EntityWitherSkull;
protected static Class<?> class_PacketPlayOutAttachEntity; public static Class<?> class_PacketPlayOutAttachEntity;
protected static Class<?> class_PacketPlayOutEntityDestroy; public static Class<?> class_PacketPlayOutEntityDestroy;
protected static Class<?> class_PacketPlayOutSpawnEntity; public static Class<?> class_PacketPlayOutSpawnEntity;
protected static Class<?> class_PacketPlayOutSpawnEntityLiving; public static Class<?> class_PacketPlayOutSpawnEntityLiving;
protected static Class<?> class_PacketPlayOutEntityMetadata; public static Class<?> class_PacketPlayOutEntityMetadata;
protected static Class<?> class_PacketPlayOutEntityStatus; public static Class<?> class_PacketPlayOutEntityStatus;
protected static Class<?> class_PacketPlayOutCustomSoundEffect; public static Class<?> class_PacketPlayOutCustomSoundEffect;
protected static Class<?> class_PacketPlayOutExperience; public static Class<?> class_PacketPlayOutExperience;
protected static Class<?> class_PacketPlayOutAnimation; public static Class<?> class_PacketPlayOutAnimation;
protected static Class<?> class_PacketPlayOutBlockBreakAnimation; public static Class<?> class_PacketPlayOutBlockBreakAnimation;
protected static Enum<?> enum_SoundCategory_PLAYERS; protected static Enum<?> enum_SoundCategory_PLAYERS;
protected static Class<Enum> class_EnumSoundCategory; protected static Class<Enum> class_EnumSoundCategory;
protected static Class<?> class_EntityFallingBlock; public static Class<?> class_EntityFallingBlock;
protected static Class<?> class_EntityArmorStand; public static Class<?> class_EntityArmorStand;
protected static Class<?> class_EntityPlayer; public static Class<?> class_EntityPlayer;
protected static Class<?> class_PlayerConnection; public static Class<?> class_PlayerConnection;
protected static Class<?> class_Chunk; public static Class<?> class_Chunk;
protected static Class<?> class_CraftPlayer; public static Class<?> class_CraftPlayer;
protected static Class<?> class_CraftChunk; public static Class<?> class_CraftChunk;
protected static Class<?> class_CraftEntity; public static Class<?> class_CraftEntity;
protected static Class<?> class_EntityProjectile; public static Class<?> class_EntityProjectile;
protected static Class<?> class_EntityFireball; public static Class<?> class_EntityFireball;
protected static Class<?> class_EntityArrow; public static Class<?> class_EntityArrow;
protected static Class<?> class_CraftArrow; public static Class<?> class_CraftArrow;
protected static Class<?> class_MinecraftServer; public static Class<?> class_MinecraftServer;
protected static Class<?> class_CraftServer; public static Class<?> class_CraftServer;
protected static Class<?> class_DataWatcherObject; public static Class<?> class_DataWatcherObject;
protected static Class<?> class_PacketPlayOutChat; public static Class<?> class_PacketPlayOutChat;
protected static Class<Enum> class_ChatMessageType; protected static Class<Enum> class_ChatMessageType;
protected static Enum<?> enum_ChatMessageType_GAME_INFO; protected static Enum<?> enum_ChatMessageType_GAME_INFO;
protected static Class<?> class_ChatComponentText; public static Class<?> class_ChatComponentText;
protected static Class<?> class_IChatBaseComponent; public static Class<?> class_IChatBaseComponent;
protected static Method class_NBTTagList_addMethod; protected static Method class_NBTTagList_addMethod;
protected static Method class_NBTTagList_getMethod; protected static Method class_NBTTagList_getMethod;
@ -275,8 +277,7 @@ public class NMSUtil19 {
protected static Field class_Entity_moveStrafingField; protected static Field class_Entity_moveStrafingField;
protected static Field class_Entity_moveForwardField; protected static Field class_Entity_moveForwardField;
static static {
{
// Find classes Bukkit hides from us. :-D // Find classes Bukkit hides from us. :-D
// Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach. // Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach.
String className = Bukkit.getServer().getClass().getName(); String className = Bukkit.getServer().getClass().getName();
@ -377,7 +378,7 @@ public class NMSUtil19 {
class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class); class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class);
class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class); class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class);
class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE); 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_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack);
class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack); class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack);
class_World_addEntityMethod = class_World.getMethod("addEntity", class_Entity, CreatureSpawnEvent.SpawnReason.class); class_World_addEntityMethod = class_World.getMethod("addEntity", class_Entity, CreatureSpawnEvent.SpawnReason.class);
@ -771,8 +772,7 @@ public class NMSUtil19 {
Bukkit.getLogger().log(Level.WARNING, "An error occurred, setting arrow lifespan will not work", ex); Bukkit.getLogger().log(Level.WARNING, "An error occurred, setting arrow lifespan will not work", ex);
class_EntityArrow_lifeField = null; class_EntityArrow_lifeField = null;
} }
if (class_EntityArrow_lifeField != null) if (class_EntityArrow_lifeField != null) {
{
class_EntityArrow_lifeField.setAccessible(true); class_EntityArrow_lifeField.setAccessible(true);
} }
@ -874,8 +874,7 @@ public class NMSUtil19 {
// 1.10 and earlier // 1.10 and earlier
legacy = true; legacy = true;
} }
} } catch (Throwable ex) {
catch (Throwable ex) {
failed = true; failed = true;
Bukkit.getLogger().log(Level.SEVERE, "An unexpected error occurred initializing Magic", ex); Bukkit.getLogger().log(Level.SEVERE, "An unexpected error occurred initializing Magic", ex);
} }
@ -912,7 +911,7 @@ public class NMSUtil19 {
} }
public static Class<?> getBukkitClass(String className) { public static Class<?> getBukkitClass(String className) {
Class<?> result = null; Class<?> result;
try { try {
result = fixBukkitClass(className); result = fixBukkitClass(className);
} catch (Exception ex) { } catch (Exception ex) {
@ -922,16 +921,20 @@ public class NMSUtil19 {
return result; return result;
} }
public static Class<?> fixBukkitClass(String className) throws ClassNotFoundException { public static Class<?> fixBukkitClass(String className) {
if (!versionPrefix.isEmpty()) { if (!versionPrefix.isEmpty()) {
className = className.replace("org.bukkit.craftbukkit.", "org.bukkit.craftbukkit." + versionPrefix); className = className.replace("org.bukkit.craftbukkit.", "org.bukkit.craftbukkit." + versionPrefix);
className = className.replace("net.minecraft.server.", "net.minecraft.server." + versionPrefix); className = className.replace("net.minecraft.server.", "net.minecraft.server." + versionPrefix);
} }
try {
return NMSUtils.class.getClassLoader().loadClass(className); return NMSUtils.class.getClassLoader().loadClass(className);
} catch (ClassNotFoundException ignored) {
return null;
}
} }
public static Object getHandle(org.bukkit.Server server) { public static Object getHandle(Server server) {
Object handle = null; Object handle = null;
try { try {
handle = class_CraftServer_getServerMethod.invoke(server); handle = class_CraftServer_getServerMethod.invoke(server);
@ -941,7 +944,7 @@ public class NMSUtil19 {
return handle; return handle;
} }
public static Object getHandle(org.bukkit.inventory.ItemStack stack) { public static Object getHandle(ItemStack stack) {
Object handle = null; Object handle = null;
try { try {
handle = class_CraftItemStack_getHandleField.get(stack); handle = class_CraftItemStack_getHandleField.get(stack);
@ -951,7 +954,7 @@ public class NMSUtil19 {
return handle; return handle;
} }
public static Object getHandle(org.bukkit.World world) { public static Object getHandle(World world) {
if (world == null) { if (world == null) {
return null; return null;
} }
@ -964,7 +967,7 @@ public class NMSUtil19 {
return handle; return handle;
} }
public static Object getHandle(org.bukkit.entity.Entity entity) { public static Object getHandle(Entity entity) {
if (entity == null) { if (entity == null) {
return null; return null;
} }
@ -990,7 +993,7 @@ public class NMSUtil19 {
return handle; return handle;
} }
public static boolean isDone(org.bukkit.Chunk chunk) { public static boolean isDone(Chunk chunk) {
Object chunkHandle = getHandle(chunk); Object chunkHandle = getHandle(chunk);
boolean done = false; boolean done = false;
try { try {
@ -1001,7 +1004,7 @@ public class NMSUtil19 {
return done; return done;
} }
public static Object getHandle(org.bukkit.Chunk chunk) { public static Object getHandle(Chunk chunk) {
Object handle = null; Object handle = null;
try { try {
handle = class_CraftChunk_getHandleMethod.invoke(chunk); handle = class_CraftChunk_getHandleMethod.invoke(chunk);
@ -1011,7 +1014,7 @@ public class NMSUtil19 {
return handle; return handle;
} }
public static Object getHandle(org.bukkit.entity.Player player) { public static Object getHandle(Player player) {
Object handle = null; Object handle = null;
try { try {
handle = class_CraftPlayer_getHandleMethod.invoke(player); handle = class_CraftPlayer_getHandleMethod.invoke(player);
@ -1046,8 +1049,7 @@ public class NMSUtil19 {
sendPacketMethod.invoke(connection, packet); sendPacketMethod.invoke(connection, packet);
} }
public static int getFacing(BlockFace direction) public static int getFacing(BlockFace direction) {
{
int dir; int dir;
switch (direction) { switch (direction) {
case SOUTH: case SOUTH:
@ -1068,18 +1070,17 @@ public class NMSUtil19 {
return dir; return dir;
} }
public static org.bukkit.entity.Entity getBukkitEntity(Object entity) public static Entity getBukkitEntity(Object entity) {
{
if (entity == null) { if (entity == null) {
return null; return null;
} }
try { try {
Method getMethod = entity.getClass().getMethod("getBukkitEntity"); Method getMethod = entity.getClass().getMethod("getBukkitEntity");
Object bukkitEntity = getMethod.invoke(entity); Object bukkitEntity = getMethod.invoke(entity);
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) { if (!(bukkitEntity instanceof Entity)) {
return null; return null;
} }
return (org.bukkit.entity.Entity)bukkitEntity; return (Entity) bukkitEntity;
} catch (Throwable ex) { } catch (Throwable ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
@ -1907,8 +1908,7 @@ public class NMSUtil19 {
} }
} }
public static void playCustomSound(Player player, Location location, String sound, float volume, float pitch) public static void playCustomSound(Player player, Location location, String sound, float volume, float pitch) {
{
try { try {
Object packet = class_PacketPlayOutCustomSoundEffect_Constructor.newInstance(sound, enum_SoundCategory_PLAYERS, location.getX(), location.getY(), location.getZ(), volume, pitch); Object packet = class_PacketPlayOutCustomSoundEffect_Constructor.newInstance(sound, enum_SoundCategory_PLAYERS, location.getX(), location.getY(), location.getZ(), volume, pitch);
sendPacket(player, packet); sendPacket(player, packet);
@ -1917,13 +1917,11 @@ public class NMSUtil19 {
} }
} }
public static Map<String, Object> getMap(ConfigurationSection section) public static Map<String, Object> getMap(ConfigurationSection section) {
{
if (section == null) { if (section == null) {
return null; return null;
} }
if (section instanceof MemorySection) if (section instanceof MemorySection) {
{
try { try {
Object mapObject = class_MemorySection_mapField.get(section); Object mapObject = class_MemorySection_mapField.get(section);
if (mapObject instanceof Map) { if (mapObject instanceof Map) {

View File

@ -7,6 +7,9 @@ import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
/**
* @author Unknown
*/
public class NMSUtils { public class NMSUtils {
public static Class<?> c = getOBCClass("block.CraftBlock"); public static Class<?> c = getOBCClass("block.CraftBlock");

View File

@ -8,7 +8,9 @@ import org.bukkit.inventory.ItemStack;
import java.util.HashSet; import java.util.HashSet;
@SuppressWarnings("deprecation") /**
* @author sky
*/
public class PlayerUtils { public class PlayerUtils {
/** /**
@ -19,9 +21,9 @@ public class PlayerUtils {
* @return * @return
*/ */
public static Block getTargetBlock(Player player, int max) { public static Block getTargetBlock(Player player, int max) {
HashSet<Byte> Byte = new HashSet<>(); HashSet<Byte> bytes = new HashSet<>();
Byte.add((byte) 0); bytes.add((byte) 0);
return player.getTargetBlock(Byte, max); return player.getTargetBlock(bytes, max);
} }
/** /**

View File

@ -0,0 +1,24 @@
package me.skymc.taboolib.plugin;
/**
* @Author sky
* @Since 2018-06-01 21:34
*/
public class PluginLoadState {
private final PluginLoadStateType stateType;
private final String message;
public PluginLoadState(PluginLoadStateType stateType, String message) {
this.stateType = stateType;
this.message = message;
}
public PluginLoadStateType getStateType() {
return stateType;
}
public String getMessage() {
return message;
}
}

View File

@ -0,0 +1,34 @@
package me.skymc.taboolib.plugin;
/**
* @Author sky
* @Since 2018-06-01 21:32
*/
public enum PluginLoadStateType {
/**
* 目录不存在
*/
DIRECTORY_NOT_FOUND,
/**
* 插件不存在
*/
FILE_NOT_FOUND,
/**
* 无效的描述
*/
INVALID_DESCRIPTION,
/**
* 无效的插件
*/
INVALID_PLUGIN,
/**
* 载入成功
*/
LOADED
}

View File

@ -0,0 +1,24 @@
package me.skymc.taboolib.plugin;
/**
* @Author sky
* @Since 2018-06-01 21:39
*/
public class PluginUnloadState {
private final boolean failed;
private final String message;
public PluginUnloadState(boolean failed, String message) {
this.failed = failed;
this.message = message;
}
public boolean isFailed() {
return failed;
}
public String getMessage() {
return message;
}
}

View File

@ -1,8 +1,3 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package me.skymc.taboolib.plugin; package me.skymc.taboolib.plugin;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
@ -26,16 +21,33 @@ import java.util.logging.Logger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
/**
* @author PluginMan
*/
public class PluginUtils { public class PluginUtils {
private PluginUtils() { PluginUtils() {
}
public static File getPluginFile(Plugin plugin) {
for (File pluginFile : Objects.requireNonNull(new File("plugins").listFiles())) {
if (pluginFile.getName().endsWith(".jar")) {
try {
PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(pluginFile);
if (desc.getName().equalsIgnoreCase(plugin.getName())) {
return pluginFile;
}
} catch (InvalidDescriptionException ignored) {
}
}
}
return null;
} }
public static void enable(Plugin plugin) { public static void enable(Plugin plugin) {
if (plugin != null && !plugin.isEnabled()) { if (plugin != null && !plugin.isEnabled()) {
Bukkit.getPluginManager().enablePlugin(plugin); Bukkit.getPluginManager().enablePlugin(plugin);
} }
} }
public static void disable(Plugin plugin) { public static void disable(Plugin plugin) {
@ -45,11 +57,11 @@ public class PluginUtils {
} }
public static void enableAll() { public static void enableAll() {
Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> isIgnored(plugin)).forEach(PluginUtils::enable); Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(PluginUtils::isIgnored).forEach(PluginUtils::enable);
} }
public static void disableAll() { public static void disableAll() {
Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> isIgnored(plugin)).forEach(PluginUtils::disable); Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(PluginUtils::isIgnored).forEach(PluginUtils::disable);
} }
public static String getFormattedName(Plugin plugin) { public static String getFormattedName(Plugin plugin) {
@ -58,7 +70,7 @@ public class PluginUtils {
public static String getFormattedName(Plugin plugin, boolean includeVersions) { public static String getFormattedName(Plugin plugin, boolean includeVersions) {
ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED; ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED;
String pluginName = color + plugin.getName(); String pluginName = color + plugin.getName() + ChatColor.RESET;
if (includeVersions) { if (includeVersions) {
pluginName = pluginName + " (" + plugin.getDescription().getVersion() + ")"; pluginName = pluginName + " (" + plugin.getDescription().getVersion() + ")";
} }
@ -89,9 +101,8 @@ public class PluginUtils {
Map commands = plugin.getDescription().getCommands(); Map commands = plugin.getDescription().getCommands();
if (commands != null) { if (commands != null) {
for (Object o : commands.entrySet()) { for (Object o : commands.entrySet()) {
Entry thisEntry = (Entry) o; if (o != null) {
if (thisEntry != null) { parsedCommands.add((String) ((Entry) o).getKey());
parsedCommands.add((String) thisEntry.getKey());
} }
} }
} }
@ -158,37 +169,28 @@ public class PluginUtils {
return plugin.equals(Main.getInst()); return plugin.equals(Main.getInst());
} }
private static String load(Plugin plugin) { private static PluginLoadState load(Plugin plugin) {
return load(plugin.getName()); return load(plugin.getName());
} }
/** public static PluginLoadState load(String name) {
* 返回内容
*
* plugin-directory 插件目录不存在
* cannot-find 插件不存在
* invalid-description 无效的描述
* invalid-plugin 无效的插件
* loaded 载入成功
*/
public static String load(String name) {
Plugin target; Plugin target;
File pluginDir = new File("plugins"); File pluginDir = new File("plugins");
if (!pluginDir.isDirectory()) { if (!pluginDir.isDirectory()) {
return "plugin-directory"; return new PluginLoadState(PluginLoadStateType.DIRECTORY_NOT_FOUND, "null");
} else { } else {
File pluginFile = new File(pluginDir, name + ".jar"); File pluginFile = new File(pluginDir, name + ".jar");
if (!pluginFile.isFile()) { if (!pluginFile.exists()) {
for (File f : Objects.requireNonNull(pluginDir.listFiles())) { for (File plugin : Objects.requireNonNull(pluginDir.listFiles())) {
if (f.getName().endsWith(".jar")) { if (plugin.getName().endsWith(".jar")) {
try { try {
PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(f); PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(plugin);
if (desc.getName().equalsIgnoreCase(name)) { if (desc.getName().equalsIgnoreCase(name)) {
pluginFile = f; pluginFile = plugin;
break; break;
} }
} catch (InvalidDescriptionException var11) { } catch (InvalidDescriptionException ignored) {
return "cannot-find"; return new PluginLoadState(PluginLoadStateType.FILE_NOT_FOUND, "null");
} }
} }
} }
@ -196,15 +198,15 @@ public class PluginUtils {
try { try {
target = Bukkit.getPluginManager().loadPlugin(pluginFile); target = Bukkit.getPluginManager().loadPlugin(pluginFile);
} catch (InvalidDescriptionException var9) { } catch (InvalidDescriptionException e) {
return "invalid-description"; return new PluginLoadState(PluginLoadStateType.INVALID_DESCRIPTION, e.toString());
} catch (InvalidPluginException var10) { } catch (InvalidPluginException e) {
return "invalid-plugin"; return new PluginLoadState(PluginLoadStateType.INVALID_PLUGIN, e.toString());
} }
target.onLoad(); target.onLoad();
Bukkit.getPluginManager().enablePlugin(target); Bukkit.getPluginManager().enablePlugin(target);
return "loaded"; return new PluginLoadState(PluginLoadStateType.LOADED, "null");
} }
} }
@ -213,20 +215,13 @@ public class PluginUtils {
unload(plugin); unload(plugin);
load(plugin); load(plugin);
} }
} }
public static void reloadAll() { public static void reloadAll() {
Arrays.stream(Bukkit.getPluginManager().getPlugins(), 0, Bukkit.getPluginManager().getPlugins().length).filter(PluginUtils::isIgnored).forEach(PluginUtils::reload); Arrays.stream(Bukkit.getPluginManager().getPlugins(), 0, Bukkit.getPluginManager().getPlugins().length).filter(PluginUtils::isIgnored).forEach(PluginUtils::reload);
} }
/** public static PluginUnloadState unload(Plugin plugin) {
* 返回内容
*
* failed 卸载失败
* unloaded 卸载成功
*/
public static String unload(Plugin plugin) {
String name = plugin.getName(); String name = plugin.getName();
PluginManager pluginManager = Bukkit.getPluginManager(); PluginManager pluginManager = Bukkit.getPluginManager();
SimpleCommandMap commandMap = null; SimpleCommandMap commandMap = null;
@ -236,7 +231,6 @@ public class PluginUtils {
Map<Event, SortedSet<RegisteredListener>> listeners = null; Map<Event, SortedSet<RegisteredListener>> listeners = null;
if (pluginManager != null) { if (pluginManager != null) {
pluginManager.disablePlugin(plugin); pluginManager.disablePlugin(plugin);
try { try {
Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins"); Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins");
pluginsField.setAccessible(true); pluginsField.setAccessible(true);
@ -259,8 +253,8 @@ public class PluginUtils {
Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands"); Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true); knownCommandsField.setAccessible(true);
commands = (Map) knownCommandsField.get(commandMap); commands = (Map) knownCommandsField.get(commandMap);
} catch (NoSuchFieldException | IllegalAccessException var15) { } catch (NoSuchFieldException | IllegalAccessException e) {
return "failed"; return new PluginUnloadState(true, e.toString());
} }
} }
@ -276,10 +270,8 @@ public class PluginUtils {
Iterator it; Iterator it;
if (listeners != null) { if (listeners != null) {
it = listeners.values().iterator(); it = listeners.values().iterator();
while (it.hasNext()) { while (it.hasNext()) {
SortedSet<RegisteredListener> set = (SortedSet) it.next(); SortedSet<RegisteredListener> set = (SortedSet) it.next();
while (it.hasNext()) { while (it.hasNext()) {
RegisteredListener value = (RegisteredListener) it.next(); RegisteredListener value = (RegisteredListener) it.next();
if (value.getPlugin() == plugin) { if (value.getPlugin() == plugin) {
@ -291,7 +283,6 @@ public class PluginUtils {
if (commandMap != null) { if (commandMap != null) {
it = commands.entrySet().iterator(); it = commands.entrySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Entry<String, Command> entry = (Entry) it.next(); Entry<String, Command> entry = (Entry) it.next();
if (entry.getValue() instanceof PluginCommand) { if (entry.getValue() instanceof PluginCommand) {
@ -312,7 +303,7 @@ public class PluginUtils {
Logger.getLogger(PluginUtils.class.getName()).log(Level.SEVERE, null, var13); Logger.getLogger(PluginUtils.class.getName()).log(Level.SEVERE, null, var13);
} }
} }
return "unloaded"; return new PluginUnloadState(false, "null");
} }
private static String consolidateStrings(String[] args, int start) { private static String consolidateStrings(String[] args, int start) {

View File

@ -1,5 +1,10 @@
package me.skymc.taboolib.string; package me.skymc.taboolib.string;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -12,12 +17,61 @@ import java.util.stream.IntStream;
*/ */
public class ArrayUtils { public class ArrayUtils {
public static String arrayJoin(String[] args, int start) {
return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim();
}
@SafeVarargs
public static <T> List<T> asList(T... args) { public static <T> List<T> asList(T... args) {
List<T> list = new ArrayList<>(); List<T> list = new ArrayList<>();
Collections.addAll(list, args); Collections.addAll(list, args);
return list; return list;
} }
public static <T> T[] arrayAppend(T[] array, T obj) {
T[] arrayNew = arrayExpand(array, 1);
arrayNew[array.length] = obj;
return arrayNew;
}
public static <T> T[] arrayAddFirst(T[] array, T obj) {
T[] arrayNew = arrayExpandAtFirst(array, 1);
arrayNew[0] = obj;
return arrayNew;
}
@SuppressWarnings("SuspiciousSystemArraycopy")
public static <T> T arrayExpand(T oldArray, int expand) {
int length = Array.getLength(oldArray);
Object newArray = Array.newInstance(oldArray.getClass().getComponentType(), length + expand);
System.arraycopy(oldArray, 0, newArray, 0, length);
return (T) newArray;
}
@SuppressWarnings("SuspiciousSystemArraycopy")
public static <T> T arrayExpandAtFirst(T oldArray, int expand) {
int length = Array.getLength(oldArray);
Object newArray = Array.newInstance(oldArray.getClass().getComponentType(), length + expand);
System.arraycopy(oldArray, 0, newArray, expand, length);
return (T) newArray;
}
public static <T> T cloneAsByte(T obj) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(obj);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
return (T) objectInputStream.readObject();
}
// *********************************
//
// Deprecated
//
// *********************************
@Deprecated
public static String[] addFirst(String[] args, String... value) { public static String[] addFirst(String[] args, String... value) {
if (args.length < 1) { if (args.length < 1) {
return value; return value;
@ -29,6 +83,7 @@ public class ArrayUtils {
return list.toArray(new String[0]); return list.toArray(new String[0]);
} }
@Deprecated
public static String[] removeFirst(String[] args) { public static String[] removeFirst(String[] args) {
if (args.length <= 1) { if (args.length <= 1) {
return new String[0]; return new String[0];
@ -37,8 +92,4 @@ public class ArrayUtils {
list.remove(0); list.remove(0);
return list.toArray(new String[0]); return list.toArray(new String[0]);
} }
public static String arrayJoin(String[] args, int start) {
return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim();
}
} }

View File

@ -0,0 +1,113 @@
package me.skymc.taboolib.string;
import com.ilummc.tlib.util.Strings;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Author sky
* @Since 2018-05-27 11:33
*/
public class VariableFormatter {
private Pattern pattern;
private String text;
private String textOrigin;
private List<Variable> variableList = new ArrayList<>();
public VariableFormatter(String text) {
this(text, "<([^<>]+)>");
}
public VariableFormatter(String text, String regex) {
this(text, Pattern.compile(regex));
}
public VariableFormatter(String text, Pattern pattern) {
this.text = text;
this.textOrigin = text;
this.pattern = pattern;
}
public VariableFormatter reset() {
text = textOrigin;
variableList.clear();
return this;
}
public VariableFormatter find() {
reset();
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String group = matcher.group();
String[] textOther = text.split(group);
String textLeft = text.indexOf(group) > 0 ? textOther[0] : null;
String textRight = textOther.length >= 2 ? text.substring(text.indexOf(group) + group.length()) : null;
if (textLeft != null) {
variableList.add(new Variable(textLeft, false));
}
variableList.add(new Variable(group.substring(1, group.length() - 1), true));
if (textRight != null && !pattern.matcher(textRight).find()) {
variableList.add(new Variable(textRight, false));
} else {
text = String.valueOf(textRight);
}
}
if (variableList.size() == 0) {
variableList.add(new Variable(text, false));
}
return this;
}
@Override
public String toString() {
return Strings.replaceWithOrder("VariableFormatter'{'pattern={0}, text=''{1}'', textOrigin=''{2}'', variableList={3}'}'", pattern, text, textOrigin, variableList);
}
// *********************************
//
// Getter and Setter
//
// *********************************
public String getText() {
return text;
}
public List<Variable> getVariableList() {
return variableList;
}
// *********************************
//
// Public classes
//
// *********************************
public static class Variable {
private final String text;
private final boolean variable;
public Variable(String text, boolean variable) {
this.text = text;
this.variable = variable;
}
public String getText() {
return text;
}
public boolean isVariable() {
return variable;
}
@Override
public String toString() {
return Strings.replaceWithOrder("Variable'{'text=''{0}'', variable={1}'}'", text, variable);
}
}
}

View File

@ -1,5 +1,9 @@
package me.skymc.taboolib.string.language2.value; package me.skymc.taboolib.string.language2.value;
import com.ilummc.tlib.bungee.api.chat.BaseComponent;
import com.ilummc.tlib.bungee.api.chat.ClickEvent;
import com.ilummc.tlib.bungee.api.chat.HoverEvent;
import com.ilummc.tlib.bungee.api.chat.TextComponent;
import me.skymc.taboolib.bookformatter.BookFormatter; import me.skymc.taboolib.bookformatter.BookFormatter;
import me.skymc.taboolib.bookformatter.action.ClickAction; import me.skymc.taboolib.bookformatter.action.ClickAction;
import me.skymc.taboolib.bookformatter.action.HoverAction; import me.skymc.taboolib.bookformatter.action.HoverAction;
@ -8,6 +12,7 @@ import me.skymc.taboolib.bookformatter.builder.PageBuilder;
import me.skymc.taboolib.bookformatter.builder.TextBuilder; import me.skymc.taboolib.bookformatter.builder.TextBuilder;
import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.other.NumberUtils; import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.string.VariableFormatter;
import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Format;
import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Line;
import me.skymc.taboolib.string.language2.Language2Value; import me.skymc.taboolib.string.language2.Language2Value;
@ -21,7 +26,6 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
@ -52,17 +56,15 @@ public class Language2Book implements Language2Line {
// 变量 // 变量
this.player = player; this.player = player;
this.value = format.getLanguage2Value(); this.value = format.getLanguage2Value();
this.book = BookFormatter.writtenBook();
// 获取书本设置 // 设置
formatOptions(list); formatOptions(list);
// 书本
book = BookFormatter.writtenBook();
// 内容 // 内容
PageBuilder page = new PageBuilder(); PageBuilder page = new PageBuilder();
// 遍历内容 // 遍历内容
for (String line : list) { for (String line : list) {
// 翻页 // 翻页
if ("[page]".equals(line)) { if (line.equals("[page]")) {
book.addPages(page.build()); book.addPages(page.build());
page = new PageBuilder(); page = new PageBuilder();
} }
@ -70,57 +72,50 @@ public class Language2Book implements Language2Line {
else if (line.startsWith("@option")) { else if (line.startsWith("@option")) {
break; break;
} else { } else {
Matcher matcher = pattern.matcher(line); for (VariableFormatter.Variable variable : new VariableFormatter(line, pattern).find().getVariableList()) {
boolean find = false; if (variable.isVariable()) {
while (matcher.find()) { String node = variable.getText().substring(1);
find = true; if (!options.containsKey(node)) {
String optionName = matcher.group(1);
String optionFullName = "<@" + matcher.group(1) + ">";
// 判断设置是否存在
if (!options.containsKey(optionName)) {
page.add("§4[<ERROR-50: " + format.getLanguage2Value().getLanguageKey() + ">]"); page.add("§4[<ERROR-50: " + format.getLanguage2Value().getLanguageKey() + ">]");
} else { } else {
String[] line_split = line.split(optionFullName); TextBuilder builder = options.get(node);
try { BaseComponent component = new TextComponent(builder.getText());
// 单独一行 if (builder.getHover() != null) {
if (line_split.length == 0) { component.setHoverEvent(new HoverEvent(builder.getHover().action(), builder.getHover().value()));
page.add(options.get(optionName).build()).endLine();
} else {
// 前段
page.add(line_split[0]);
// 变量
page.add(options.get(optionName).build());
// 后段
if (line_split.length >= 2) {
// 获取文本
StringBuilder sb = new StringBuilder();
for (int i = 1; i < line_split.length; i++) {
sb.append(line_split[i]).append(optionFullName);
} }
// 更改文本 if (builder.getClick() != null) {
line = sb.substring(0, sb.length() - optionFullName.length()); component.setClickEvent(new ClickEvent(builder.getClick().action(), builder.getClick().value()));
// 如果后段还有变量 }
if (!pattern.matcher(line).find()) { page.add(component);
page.add(line_split[1]).endLine();
} }
} else { } else {
page.endLine(); page.add(variable.getText());
} }
} }
} catch (Exception e) { page.newLine();
page.add("§4[<ERROR-51: " + format.getLanguage2Value().getLanguageKey() + ">]");
}
}
}
if (!find) {
page.add(line).endLine();
}
} }
} }
// 结尾 // 结尾
book.addPages(page.build()); book.addPages(page.build());
} }
@Override
public void send(Player player) {
BookFormatter.forceOpen(player, book.build());
}
@Override
public void console() {
Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[<ERROR-40: " + value.getLanguageKey() + ">]");
}
// *********************************
//
// Getter and Setter
//
// *********************************
public static Pattern getPattern() { public static Pattern getPattern() {
return pattern; return pattern;
} }
@ -141,6 +136,46 @@ public class Language2Book implements Language2Line {
return book; return book;
} }
// *********************************
//
// Private Methods
//
// *********************************
private List<List<String>> getBookPages(List<String> source) {
List<List<String>> list = new ArrayList<>();
for (String line : removeOption(source)) {
if (line.equalsIgnoreCase("[page]")) {
list.add(new ArrayList<>());
} else {
getLatestList(list).add(line);
}
}
return list;
}
public List<String> getLatestList(List<List<String>> list) {
if (list.size() == 0) {
List<String> newList = new ArrayList<>();
list.add(newList);
return newList;
} else {
return list.get(list.size() - 1);
}
}
public List<String> removeOption(List<String> source) {
List<String> list = new ArrayList<>();
for (String line : source) {
if (!line.contains("@option")) {
list.add(line);
} else {
return list;
}
}
return list;
}
private void formatOptions(List<String> list) { private void formatOptions(List<String> list) {
// 获取书本设置 // 获取书本设置
HashMap<String, List<String>> _options = getOptions(list); HashMap<String, List<String>> _options = getOptions(list);
@ -204,14 +239,4 @@ public class Language2Book implements Language2Line {
options_source.put(optionName, option); options_source.put(optionName, option);
return options_source; return options_source;
} }
@Override
public void send(Player player) {
BookFormatter.forceOpen(player, book.build());
}
@Override
public void console() {
Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[<ERROR-40: " + value.getLanguageKey() + ">]");
}
} }

View File

@ -1,90 +1,41 @@
package me.skymc.taboolib.team; 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.google.common.base.Preconditions;
import com.ilummc.tlib.bungee.api.ChatColor;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.events.itag.AsyncPlayerReceiveNameTagEvent; import me.skymc.taboolib.itagapi.TagDataHandler;
import me.skymc.taboolib.events.itag.PlayerReceiveNameTagEvent;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; 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.Set;
import java.util.stream.IntStream;
/** /**
* @Author sky * @Author sky
* @Since 2018-05-09 21:03 * @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}; /**
* 该工具于 2018年5月23日02:31:14 失效
private static boolean loaded = false; * 新工具类: {@link TagDataHandler}
private static HashMap<Integer, Player> entityIdMap = new HashMap<>(); */
private static HashMap<UUID, String> playerData = new HashMap<>();
TagAPI() { TagAPI() {
} }
public static void inst() { 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) { 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) { public static void setPlayerDisplayName(Player player, String name) {
String nameColored = ChatColor.translateAlternateColorCodes('&', name); TagDataHandler.getHandler().setDisplay(player, name);
player.setDisplayName(nameColored);
player.setPlayerListName(nameColored);
playerData.put(player.getUniqueId(), nameColored);
Bukkit.getScheduler().runTask(Main.getInst(), () -> refreshPlayer(player));
} }
public static void removePlayerDisplayName(Player player) { public static void removePlayerDisplayName(Player player) {
player.setDisplayName(null); TagDataHandler.getHandler().setDisplay(player, player.getName());
player.setPlayerListName(null);
playerData.remove(player.getUniqueId());
Bukkit.getScheduler().runTask(Main.getInst(), () -> refreshPlayer(player));
} }
public static void refreshPlayer(Player player) { public static void refreshPlayer(Player player) {
@ -112,50 +63,4 @@ public class TagAPI implements Listener {
forWhom.forEach(playerFor -> refreshPlayer(player, playerFor)); 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 com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.itagapi.TagDataHandler;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -18,16 +19,16 @@ import java.util.UUID;
* @author sky * @author sky
* @since 2018-03-17 21:43:49 * @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 static TagManager inst;
private HashMap<UUID, PlayerData> playerData = new HashMap<>();
private TagManager() {
Bukkit.getPluginManager().registerEvents(this, Main.getInst());
}
public static TagManager getInst() { public static TagManager getInst() {
synchronized (TagManager.class) { synchronized (TagManager.class) {
if (inst == null) { if (inst == null) {
@ -38,146 +39,37 @@ public class TagManager implements Listener {
} }
public HashMap<UUID, PlayerData> getPlayerData() { public HashMap<UUID, PlayerData> getPlayerData() {
return playerData; return new HashMap<>(0);
} }
/**
* 设置玩家前缀
*
* @param player 名称
* @param prefix 前缀
*/
public void setPrefix(Player player, String prefix) { public void setPrefix(Player player, String prefix) {
getPlayerData(player).setPrefix(prefix); TagDataHandler.getHandler().setPrefix(player, prefix);
uploadData(player);
} }
/**
* 设置玩家后缀
*
* @param player 玩家
* @param suffix 后缀
*/
public void setSuffix(Player player, String suffix) { public void setSuffix(Player player, String suffix) {
getPlayerData(player).setSuffix(suffix); TagDataHandler.getHandler().setSuffix(player, suffix);
uploadData(player);
} }
/**
* 获取玩家前缀
*
* @param player 玩家
* @return String
*/
public String getPrefix(Player player) { public String getPrefix(Player player) {
return getPlayerData(player).getPrefix(); return TagDataHandler.getHandler().getPrefix(player);
} }
/**
* 获取玩家后缀
*
* @param player 玩家
* @return String
*/
public String getSuffix(Player player) { public String getSuffix(Player player) {
return getPlayerData(player).getSuffix(); return TagDataHandler.getHandler().getSuffix(player);
} }
/**
* 获取玩家数据
*
* @param player 玩家
* @return {@link PlayerData}
*/
public PlayerData getPlayerData(Player player) { 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) { public void unloadData(Player targetPlayer) {
PlayerData data = getPlayerData(targetPlayer); TagDataHandler.getHandler().resetVariable(targetPlayer);
for (Player player : Bukkit.getOnlinePlayers()) {
Scoreboard scoreboard = getScoreboard(player);
Team team = scoreboard.getTeam(data.getName());
if (team != null) {
team.unregister();
}
}
data.reset();
} }
/**
* 将该玩家的数据向服务器所有玩家更新
*
* @param targetPlayer 玩家
*/
public void uploadData(Player 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) { 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 { 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

@ -1,11 +1,13 @@
package me.skymc.taboolib.update; package me.skymc.taboolib.update;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.fileutils.FileUtils; import me.skymc.taboolib.fileutils.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
/** /**
@ -14,11 +16,17 @@ import org.bukkit.scheduler.BukkitRunnable;
*/ */
public class UpdateTask { public class UpdateTask {
private static final String API = "https://internal.github.com/repos/Bkm016/TabooLib/releases/latest"; private static boolean haveUpdate = false;
private static double newVersion = 0;
public static boolean isHaveUpdate() {
return haveUpdate;
}
public static double getNewVersion() {
return newVersion;
}
/**
* 检测更新
*/
public UpdateTask() { public UpdateTask() {
new BukkitRunnable() { new BukkitRunnable() {
@ -27,14 +35,31 @@ public class UpdateTask {
if (!Main.getInst().getConfig().getBoolean("UPDATE-CHECK")) { if (!Main.getInst().getConfig().getBoolean("UPDATE-CHECK")) {
return; return;
} }
String value = FileUtils.getStringFromURL(API, "{}");
JsonObject json = new JsonParser().parse(value).getAsJsonObject(); String value = FileUtils.getStringFromURL("https://api.github.com/repos/Bkm016/TabooLib/tags", null);
if (json.entrySet().size() > 0) { if (value == null) {
double newVersion = Double.parseDouble(json.get("tag_name").getAsString()); TLocale.Logger.error("UPDATETASK.VERSION-FAIL");
return;
}
JsonElement json = new JsonParser().parse(value);
if (json.isJsonArray()) {
JsonObject latestObject = json.getAsJsonArray().get(0).getAsJsonObject();
newVersion = latestObject.get("name").getAsDouble();
if (TabooLib.getPluginVersion() >= newVersion) { if (TabooLib.getPluginVersion() >= newVersion) {
TLocale.Logger.info("UPDATETASK.VERSION-LATEST"); TLocale.Logger.info("UPDATETASK.VERSION-LATEST");
} else { } else {
haveUpdate = true;
TLocale.Logger.info("UPDATETASK.VERSION-OUTDATED", String.valueOf(TabooLib.getPluginVersion()), String.valueOf(newVersion)); TLocale.Logger.info("UPDATETASK.VERSION-OUTDATED", String.valueOf(TabooLib.getPluginVersion()), String.valueOf(newVersion));
new BukkitRunnable() {
@Override
public void run() {
if (Main.getInst().getConfig().getBoolean("UPDATE-DOWNLOAD", false)) {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "taboolib updatePlugin");
}
}
}.runTask(Main.getInst());
} }
} }
} }

View File

@ -17,9 +17,8 @@ DATAURL:
# 启用后将收到来自其他插件的调试信息 # 启用后将收到来自其他插件的调试信息
DEBUG: false DEBUG: false
# 是否启用离线模式 # 网络连接测试地址
# 离线模式下将不会下载依赖 TEST-URL: 'aliyun.com'
OFFLINE-MODE: false
# 下载依赖时启用的线程数 # 下载依赖时启用的线程数
DOWNLOAD-POOL-SIZE: 4 DOWNLOAD-POOL-SIZE: 4
@ -35,9 +34,16 @@ LOCALE:
# 如果需要开启仍然可以在语言文件中加入 papi: true # 如果需要开启仍然可以在语言文件中加入 papi: true
USE_PAPI: false USE_PAPI: false
# 玩家列表TAB是否根据前缀排序
# 启用后将会导致部分通过计分板获取玩家数据的插件出错BedwarsRel、SkyWars
TABLIST-SORT: false
# 是否启用更新检测 # 是否启用更新检测
UPDATE-CHECK: true UPDATE-CHECK: true
# 是否启用自动更新
UPDATE-DOWNLOAD: false
# 是否在关闭服务器时清理玩家数据 # 是否在关闭服务器时清理玩家数据
# 该配置将在启用数据库储存时失效 # 该配置将在启用数据库储存时失效
DELETE-DATA: false DELETE-DATA: false

View File

@ -1,9 +1,18 @@
TLIB: TLIB:
INJECTION-SUCCESS: '注入成功' INJECTION-SUCCESS: '注入成功'
INJECTION-FAILED: '注入失败' INJECTION-FAILED: '注入失败'
LOAD-FAIL-OFFLINE:
- '**********************************************'
- '** TabooLib-{0} 无法在您的服务器上使用'
- '**'
- '** 您的服务器尚未连接互联网导致本插件无法正常载入'
- '** 请使用离线版本或是手动下载依赖库文件'
- '**'
- '** 详情查阅: https://github.com/Bkm016/TabooLib'
- '**********************************************'
DEPENDENCY: DEPENDENCY:
OFFLINE-DEPENDENCY-WARN: '已启用离线模式, 将不会下载第三方依赖库' DOWNLOAD-OFFLINE: '已启用离线模式, 将不会下载第三方依赖库'
DOWNLOAD-CONNECTED: ' 正在下载 {0} 大小 {1}' DOWNLOAD-CONNECTED: ' 正在下载 {0} 大小 {1}'
DOWNLOAD-PROGRESS: ' 下载速度 {0} 进度 {1}' DOWNLOAD-PROGRESS: ' 下载速度 {0} 进度 {1}'
DOWNLOAD-SUCCESS: ' 下载 {0} 完成' DOWNLOAD-SUCCESS: ' 下载 {0} 完成'
@ -48,6 +57,10 @@ NOTIFY:
LOCALE: LOCALE:
TITLE-SEND-TO-NON-PLAYER: '该语言类型只能发送给玩家:{0}' TITLE-SEND-TO-NON-PLAYER: '该语言类型只能发送给玩家:{0}'
PLUGIN-NOT-FOUND: '无效的语言文件发送形式: &4{0}' PLUGIN-NOT-FOUND: '无效的语言文件发送形式: &4{0}'
BOOK-ARGUMENTS-IDENTIFICATION-FAILED: 'TlocaleBook 的变量识别失败: {0}'
BAR-COLOR-IDENTIFICATION-FAILED: 'TLocaleBossBar 的颜色识别失败: {0}'
BAR-STYLE-IDENTIFICATION-FAILED: 'TLocaleBossBar 的类型识别失败: {0}'
BAR-PLUGIN-NOT-FOUND: 'TLocaleBossBar 的依赖插件 BossBarAPI 不存在'
MISC: MISC:
FIELD-COPY-FAILED: '拷贝 {0} 对象失败' FIELD-COPY-FAILED: '拷贝 {0} 对象失败'
@ -103,7 +116,8 @@ ANVIL-CONTAINER:
- '&7随后点击右侧输出物品' - '&7随后点击右侧输出物品'
UPDATETASK: UPDATETASK:
VERSION-LATEST: '插件已是最新版, 无需更新!' VERSION-FAIL: '&4更新记录获取失败, 请检查网络连接!'
VERSION-LATEST: '&7插件已是最新版, 无需更新!'
VERSION-OUTDATED: VERSION-OUTDATED:
- '&8####################################################' - '&8####################################################'
- '&7 检测到有新的版本更新!' - '&7 检测到有新的版本更新!'
@ -143,7 +157,7 @@ COMMANDS:
ONLY-PLAYER: '&8[&3&lTabooLib&8] &4控制台无法这么做' ONLY-PLAYER: '&8[&3&lTabooLib&8] &4控制台无法这么做'
ONLY-STORAGE-SQL: '&8[&3&lTabooLib&8] &4只有启用数据库储存时才能这么做' ONLY-STORAGE-SQL: '&8[&3&lTabooLib&8] &4只有启用数据库储存时才能这么做'
INTERNAL: INTERNAL:
ONLY-PLAYER: '&8[&3&lTabooLib&8] &7指令 &f{0} &7只能由 &f{1} &7执行' TYPE-ERROR: '&8[&3&lTabooLib&8] &7指令 &f{0} &7只能由 &f{1} &7执行'
TYPE-PLAYER: 玩家 TYPE-PLAYER: 玩家
TYPE-CONSOLE: 控制台 TYPE-CONSOLE: 控制台
ERROR-USAGE: ERROR-USAGE:
@ -155,6 +169,9 @@ COMMANDS:
- '&8[&3&lTabooLib&8] &7你可能想要:' - '&8[&3&lTabooLib&8] &7你可能想要:'
- '&8[&3&lTabooLib&8] &7{1}' - '&8[&3&lTabooLib&8] &7{1}'
COMMAND-REGISTER: '&7自动为插件 &f{0} &7的命令 &f{1} &7注册 &f{2} &7条子命令' 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: PARAMETER:
UNKNOWN: '&8[&3&lTabooLib&8] &4指令错误' UNKNOWN: '&8[&3&lTabooLib&8] &4指令错误'
INSUFFICIENT: '&8[&3&lTabooLib&8] &4参数不足' INSUFFICIENT: '&8[&3&lTabooLib&8] &4参数不足'
@ -213,6 +230,13 @@ COMMANDS:
IMPORTING-START: '&8[&3&lTabooLib&8] &7开始导入 &f{0} &7项玩家数据' IMPORTING-START: '&8[&3&lTabooLib&8] &7开始导入 &f{0} &7项玩家数据'
IMPORTING-PROGRESS: '&8[&3&lTabooLib&8] &7导入玩家数据: &f{0} &7进度: &f{1}/{2}' IMPORTING-PROGRESS: '&8[&3&lTabooLib&8] &7导入玩家数据: &f{0} &7进度: &f{1}/{2}'
SUCCESS: '&8[&3&lTabooLib&8] &7导入完成' SUCCESS: '&8[&3&lTabooLib&8] &7导入完成'
UPDATEPLUGIN:
DESCRIPTION: '&4更新插件 &8(谨防非正规途径的插件获取方式)'
UPDATE-NOT-FOUND: '&8[&3&lTabooLib&8] &7插件已是最新版, 无需更新!'
UPDATE-NOT-SUPPORT: '&8[&3&lTabooLib&8] &4您的服务器不支持在线更新!'
FILE-NOT-FOUND: '&8[&3&lTabooLib&8] &4尚未寻找到插件文件'
UPDATE-START: '&8[&3&lTabooLib&8] &7开始下载:&f {0}'
UPDATE-SUCCESS: '&8[&3&lTabooLib&8] &7最新版下载完成, 重启服务器自动更新!'
JAVASHELL: JAVASHELL:
DESCRIPTION: DESCRIPTION:
LOAD: '载入脚本' LOAD: '载入脚本'
@ -453,6 +477,7 @@ COMMANDS:
ARGUMENTS: ARGUMENTS:
0: '名称' 0: '名称'
INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在' INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在'
INVALID-DESCRIPTION: '&8[&3&lTabooLib&8] &4获取插件 &c{0} &4信息失败: &c{1}'
INFO-PLUGIN: INFO-PLUGIN:
- '&8[&3&lTabooLib&8] &7插件名称: &f{0}' - '&8[&3&lTabooLib&8] &7插件名称: &f{0}'
- '&8[&3&lTabooLib&8] &7描述: &f{1}' - '&8[&3&lTabooLib&8] &7描述: &f{1}'
@ -467,9 +492,10 @@ COMMANDS:
DESCRIPTION: '载入插件' DESCRIPTION: '载入插件'
ARGUMENTS: ARGUMENTS:
0: '名称' 0: '名称'
INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4已经载入' INVALID-DESCRIPTION: '&8[&3&lTabooLib&8] &4插件目录不存在'
INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4载入失败: &c{1}'
FILE-NOT-FOUND: '&8[&3&lTabooLib&8] &4插件 &c{0} &4文件不存在'
LOAD-SUCCESS: '&8[&3&lTabooLib&8] &7插件已载入' LOAD-SUCCESS: '&8[&3&lTabooLib&8] &7插件已载入'
LOAD-FAIL: '&8[&3&lTabooLib&8] &7插件载入失败'
UNLOAD: UNLOAD:
DESCRIPTION: '卸载插件' DESCRIPTION: '卸载插件'
ARGUMENTS: ARGUMENTS:
@ -477,7 +503,7 @@ COMMANDS:
INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在' INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在'
INVALID-PLUGIN-IGNORED: '&8[&3&lTabooLib&8] &4插件 &c{0} &4无法操作' INVALID-PLUGIN-IGNORED: '&8[&3&lTabooLib&8] &4插件 &c{0} &4无法操作'
UNLOAD-SUCCESS: '&8[&3&lTabooLib&8] &7插件已卸载' UNLOAD-SUCCESS: '&8[&3&lTabooLib&8] &7插件已卸载'
UNLOAD-FAIL: '&8[&3&lTabooLib&8] &7插件卸载失败' UNLOAD-FAIL: '&8[&3&lTabooLib&8] &4插件 &c{0} &e卸载失败: &c{1}'
RELOAD: RELOAD:
DESCRIPTION: '重载插件' DESCRIPTION: '重载插件'
ARGUMENTS: ARGUMENTS:

View File

@ -25,4 +25,4 @@ commands:
aliases: [tlm] aliases: [tlm]
depend: [Vault] depend: [Vault]
softdepend: [PlaceholderAPI, Skript, TabooCode, MassiveLag] softdepend: [PlaceholderAPI, Skript, MassiveLag]