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://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://github.com/bkm016/TabooLib/releases) 根据您服务器的网络状态下载**在线**或**离线**版本
离线版为 **offline** 结尾的 **jar** 文件
如果你的服务器是 **1.7.10** 版本,在 [这里](https://pcd.ac.cn/2018/05/19/71/) 修复因 **SpecialSource** 版本过低导致插件无法载入的问题
## 添加 TabooLib 为库
### Maven

View File

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

View File

@ -13,6 +13,7 @@ import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.IO;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.fileutils.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
@ -49,7 +50,7 @@ public class TLib {
libsFolder.mkdirs();
}
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.loadFromString(yamlText);
} catch (IOException | InvalidConfigurationException ignored) {
@ -71,13 +72,14 @@ public class TLib {
TLocaleLoader.init();
PlaceholderHook.init();
TLocaleLoader.load(Main.getInst(), false);
TDependencyInjector.inject(Main.getInst(), tLib);
}
public static void initPost() {
TDependencyInjector.inject(Main.getInst(), TLib.getTLib());
try {
Pool.init();
} catch (Throwable ignored) {
}
}
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 java.lang.reflect.Type;
import java.util.Arrays;
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) {
if (Main.getInst().getConfig().getBoolean("OFFLINE-MODE")) {
TLocale.Logger.warn("DEPENDENCY.OFFLINE-DEPENDENCY-WARN");
if (Main.isOfflineVersion()) {
TLocale.Logger.warn("DEPENDENCY.DOWNLOAD-OFFLINE");
return false;
}
AtomicBoolean failed = new AtomicBoolean(false);
@ -84,4 +84,4 @@ public class TDependency {
private static int getDownloadPoolSize() {
return Main.getInst().getConfig().getInt("DOWNLOAD-POOL-SIZE", 4);
}
}
}

View File

@ -13,9 +13,23 @@ import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
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) {
TLocaleLoader.load(plugin, true);
injectDependencies(plugin, o);
@ -135,17 +149,7 @@ public class TDependencyInjector {
}
private static void injectDependencies(Plugin plugin, 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};
}
}
Dependency[] dependencies = getDependencies(o);
if (dependencies.length != 0) {
TLocale.Logger.info("DEPENDENCY.LOADING-START", plugin.getName());
for (Dependency dependency : dependencies) {
@ -167,5 +171,4 @@ public class TDependencyInjector {
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.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.util.Ref;
import com.ilummc.tlib.util.Strings;
import me.clip.placeholderapi.PlaceholderAPI;
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.command.CommandSender;
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.List;
import java.util.stream.Collectors;
/**
* @author IzzelAliz
*/
public class 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.TabooLib;
import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.fileutils.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
@ -29,8 +30,10 @@ public class TLocaleLoader {
public static void init() {
ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT");
ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON");
ConfigurationSerialization.registerClass(TLocaleBook.class, "BOOK");
ConfigurationSerialization.registerClass(TLocaleSound.class, "SOUND");
ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE");
ConfigurationSerialization.registerClass(TLocaleBossBar.class, "BAR");
ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION");
}
@ -140,7 +143,7 @@ public class TLocaleLoader {
}
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 {
String yamlText = new String(IO.readFully(localeInputSteam), Charset.forName("utf-8"));
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.TLocaleSerialize;
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.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import javax.annotation.concurrent.ThreadSafe;
import java.util.*;
@ -21,6 +23,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ThreadSafe
@SerializableAs("JSON")
public class TLocaleJson extends TLocaleSerialize {
@ -72,11 +75,11 @@ public class TLocaleJson extends TLocaleSerialize {
// 可能有很多个 BaseComponent于是为每个 component 单独设置各种事件
BaseComponent[] component = TextComponent.fromLegacyText(text);
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))));
} 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))));
} 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())));
}
});
@ -101,7 +104,7 @@ public class TLocaleJson extends TLocaleSerialize {
private static List<String> getTextList(Object textObj) {
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) {
return Lists.newArrayList(TLocale.Translate.setColored((String) textObj));
} else {
@ -125,11 +128,11 @@ public class TLocaleJson extends TLocaleSerialize {
}
private void sendRawMessage(CommandSender sender, BaseComponent[] components) {
if (sender instanceof Player) {
JSONFormatter.sendRawMessage((Player) sender, ComponentSerializer.toString(components));
} else {
sender.sendMessage(TextComponent.toLegacyText(components));
}
TLocale.Tellraw.send(sender, ComponentSerializer.toString(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) {
@ -140,10 +143,6 @@ public class TLocaleJson extends TLocaleSerialize {
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) {
if (component.getClickEvent() != null) {
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);
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 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
*
@ -28,15 +36,13 @@ public class Strings {
return stringBuilder.toString();
}
// *********************************
//
// Deprecated
//
// *********************************
public static String replaceWithOrder(String template, String... 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;
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 me.skymc.taboolib.anvil.AnvilContainerAPI;
import me.skymc.taboolib.bstats.Metrics;
import me.skymc.taboolib.commands.TabooLibMainCommand;
import me.skymc.taboolib.commands.internal.BaseMainCommand;
import me.skymc.taboolib.commands.internal.TBaseCommand;
import me.skymc.taboolib.commands.language.Language2Command;
import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand;
import me.skymc.taboolib.commands.plugin.TabooLibPluginMainCommand;
@ -17,17 +18,17 @@ import me.skymc.taboolib.database.PlayerDataManager;
import me.skymc.taboolib.economy.EcoUtils;
import me.skymc.taboolib.entity.EntityUtils;
import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.inventory.speciaitem.SpecialItem;
import me.skymc.taboolib.itagapi.TagDataHandler;
import me.skymc.taboolib.javashell.JavaShell;
import me.skymc.taboolib.listener.*;
import me.skymc.taboolib.message.ChatCatcher;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.mysql.hikari.HikariHandler;
import me.skymc.taboolib.mysql.protect.MySQLConnection;
import me.skymc.taboolib.nms.item.DabItemUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.packet.PacketUtils;
import me.skymc.taboolib.permission.PermissionUtils;
import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.taboolib.sign.SignUtils;
@ -35,8 +36,6 @@ import me.skymc.taboolib.skript.SkriptHandler;
import me.skymc.taboolib.string.StringUtils;
import me.skymc.taboolib.string.language2.Language2;
import me.skymc.taboolib.support.SupportPlaceholder;
import me.skymc.taboolib.team.TagAPI;
import me.skymc.taboolib.team.TagUtils;
import me.skymc.taboolib.timecycle.TimeCycleManager;
import me.skymc.taboolib.update.UpdateTask;
import me.skymc.tlm.TLM;
@ -50,6 +49,8 @@ import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Random;
/**
@ -57,6 +58,14 @@ import java.util.Random;
*/
public class Main extends JavaPlugin implements Listener {
public Main() {
inst = this;
}
public enum StorageType {
LOCAL, SQL
}
private static Plugin inst;
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 StorageType storageType;
private static StorageType storageType = StorageType.LOCAL;
private static boolean disable = false;
@ -75,60 +84,10 @@ public class Main extends JavaPlugin implements Listener {
private static boolean started;
private static boolean isInternetOnline = false;
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
public FileConfiguration getConfig() {
return config;
@ -150,71 +109,31 @@ public class Main extends JavaPlugin implements Listener {
@Override
public void onLoad() {
inst = this;
disable = false;
// 载入配置
saveDefaultConfig();
// 加载依赖
// 载入牛逼玩意儿
TLib.init();
TLib.injectPluginManager();
// 载入目录
// 网络检测
testInternet();
// 创建文件夹
setupDataFolder();
// 注册配置
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;
} else {
// 储存方式
storageType = StorageType.LOCAL;
}
// 创建数据库
setupDatabase();
// 载入离线库文件
setupLibraries();
// 载入牛逼玩意儿
TLib.initPost();
}
@Override
public void onEnable() {
// 注册指令
getCommand("language2").setExecutor(new Language2Command());
getCommand("taboolibrarymodule").setExecutor(new TLMCommands());
getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand());
BaseMainCommand.createCommandExecutor("taboolib", new TabooLibMainCommand());
BaseMainCommand.createCommandExecutor("taboolibplugin", new TabooLibPluginMainCommand());
// 注册命令
registerCommands();
// 注册监听
registerListener();
// 载入经济
EcoUtils.setupEconomy();
// 载入权限
@ -229,6 +148,8 @@ public class Main extends JavaPlugin implements Listener {
JavaShell.javaShellSetup();
// 注册脚本
SkriptHandler.getInst();
// 注册头衔
TagDataHandler.init(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, () -> PlayerDataManager.saveAllCaches(true, false), 20, 20 * 60);
// 文件监控
TLib.getTLib().getConfigWatcher().addListener(new File(getDataFolder(), "config.yml"), null, obj -> {
reloadConfig();
@ -254,12 +176,10 @@ public class Main extends JavaPlugin implements Listener {
@Override
public void run() {
// 载入 PlaceholderAPI 扩展
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
new SupportPlaceholder(getInst(), "taboolib").hook();
}
if (PacketUtils.isProtocolLibEnabled()) {
TagAPI.inst();
}
// 载入 SpecialItem 接口
SpecialItem.getInst().loadItems();
// 载入 TLM 接口
@ -320,20 +240,34 @@ public class Main extends JavaPlugin implements Listener {
// 提示信息
TLocale.Logger.error("NOTIFY.SUCCESS-DISABLE");
// 清理头衔
TagUtils.delete();
// 结束连接
if (connection != null && connection.isConnection()) {
connection.closeConnection();
}
// 卸载牛逼玩意儿
TLib.unload();
// 关闭服务器
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() {
playerDataFolder = new File(getConfig().getString("DATAURL.PLAYER-DATA"));
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() {
getServer().getPluginManager().registerEvents(this, this);
getServer().getPluginManager().registerEvents(new ListenerPlayerCommand(), 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 DataUtils(), 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;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.playerdata.DataUtils;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
@ -37,17 +38,17 @@ public class TabooLib {
}
public static double getPluginVersion() {
try {
return Double.valueOf(Main.getInst().getDescription().getVersion());
} catch (Exception e) {
return 0D;
}
return NumberUtils.getDouble(Main.getInst().getDescription().getVersion());
}
public static String getVersion() {
return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
}
public static int getVersionNumber() {
return getVerint();
}
public static String getServerUID() {
if (!DataUtils.getPluginData("TabooLibrary", null).contains("serverUID")) {
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());
}
@Deprecated
public static int getVerint() {
if (getVersion().startsWith("v1_7")) {
String version = getVersion();
if (version.startsWith("v1_7")) {
return 10700;
} else if (getVersion().startsWith("v1_8")) {
} else if (version.startsWith("v1_8")) {
return 10800;
} else if (getVersion().startsWith("v1_9")) {
} else if (version.startsWith("v1_9")) {
return 10900;
} else if (getVersion().startsWith("v1_10")) {
} else if (version.startsWith("v1_10")) {
return 11000;
} else if (getVersion().startsWith("v1_11")) {
} else if (version.startsWith("v1_11")) {
return 11100;
} else if (getVersion().startsWith("v1_12")) {
} else if (version.startsWith("v1_12")) {
return 11200;
} else if (getVersion().startsWith("v1_13")) {
} else if (version.startsWith("v1_13")) {
return 11300;
}
return 0;

View File

@ -1,8 +1,10 @@
package me.skymc.taboolib.bookformatter;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
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.logger.TLogger;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@ -12,6 +14,7 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -31,11 +34,13 @@ public final class BookReflection {
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;
//only version >= 1.9
// only version >= 1.9
private static final Object[] hands;
//Older versions
@ -115,18 +120,22 @@ public final class BookReflection {
* @param meta the book meta to change
* @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 {
List<Object> pages = (List<Object>) craftMetaBookField.get(meta);
pages.clear();
for (BaseComponent[] c : components) {
final String json = ComponentSerializer.toString(c);
//System.out.println("page:" + json); //Debug
pages.add(chatSerializerA.invoke(null, json));
}
pages = (List<Object>) craftMetaBookField.get(meta);
} catch (Exception e) {
throw new UnsupportedVersionException(e);
TLogger.getGlobalLogger().error("Error while executing reflections, failed to get bookmeta (version: " + BookReflection.version + ")");
return;
}
pages.clear();
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();
}
}
}
@ -136,17 +145,21 @@ public final class BookReflection {
* @param meta the book meta to change
* @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 {
List<Object> 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));
}
pages = (List<Object>) craftMetaBookField.get(meta);
} 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;
import net.md_5.bungee.api.chat.ClickEvent;
import com.ilummc.tlib.bungee.api.chat.ClickEvent;
/**
* @author sky
@ -86,12 +86,12 @@ public interface ClickAction {
@Override
public ClickEvent.Action action() {
return null;
return action;
}
@Override
public String value() {
return null;
return value;
}
}
}

View File

@ -1,10 +1,10 @@
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.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.entity.Entity;
import org.bukkit.inventory.ItemStack;
@ -157,12 +157,12 @@ public interface HoverAction {
@Override
public HoverEvent.Action action() {
return null;
return action;
}
@Override
public BaseComponent[] value() {
return new BaseComponent[0];
return value;
}
}
}

View File

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

View File

@ -1,11 +1,8 @@
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.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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,20 @@
package me.skymc.taboolib.fileutils;
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.bukkit.plugin.Plugin;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.logging.Level;
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 文件夹
*/
public void deleteAllFile(File file) {
public static void deleteAllFile(File file) {
if (!file.exists()) {
return;
}
@ -104,7 +139,7 @@ public class FileUtils {
* @param file1 文件1
* @param file2 文件2
*/
public void copyAllFile(String file1, String file2) {
public static void copyAllFile(String file1, String file2) {
File _file1 = new File(file1);
File _file2 = new File(file2);
if (!_file2.exists()) {
@ -133,7 +168,7 @@ public class FileUtils {
* @param file1 文件1
* @param file2 文件2
*/
public void fileChannelCopy(File file1, File file2) {
public static void fileChannelCopy(File file1, File file2) {
FileInputStream fileIn = null;
FileOutputStream fileOut = null;
FileChannel channelIn = null;

View File

@ -402,7 +402,7 @@ public class ItemUtils {
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);
// 耐久

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;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.json.JSONArray;
import me.skymc.taboolib.json.JSONObject;
import me.skymc.taboolib.jsonformatter.click.ClickEvent;
@ -15,17 +16,14 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* @author Unknown
*/
@Deprecated
public class JSONFormatter {
public static void sendRawMessage(Player player, String message) {
try {
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);
}
TLocale.Tellraw.send(player, message);
}
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.inventory.ItemUtils;
import me.skymc.taboolib.json.JSONObject;
import me.skymc.taboolib.json.tellraw.TellrawJson;
import me.skymc.taboolib.nms.item.DabItemUtils;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
@ -13,64 +14,68 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class ShowItemEvent extends HoverEvent{
private JSONObject object = new JSONObject();
public Object getItemTag(ItemStack item) {
try {
return DabItemUtils.getInstance().getTag(DabItemUtils.getInstance().getNMSCopy(item));
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("deprecation")
public ShowItemEvent(ItemStack is){
try{
object.put("action", "show_item");
StringBuilder tag = new StringBuilder();
Object itemTag = getItemTag(is);
if (itemTag != null) {
public class ShowItemEvent extends HoverEvent {
private JSONObject object = new JSONObject();
public Object getItemTag(ItemStack item) {
try {
return DabItemUtils.getInstance().getTag(DabItemUtils.getInstance().getNMSCopy(item));
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("deprecation")
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 {
object.put("action", "show_item");
StringBuilder tag = new StringBuilder();
Object itemTag = getItemTag(is);
if (itemTag != null) {
tag.append(",tag:").append(itemTag);
}
else {
ItemMeta im = is.getItemMeta();
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<>();
Map<Enchantment, Integer> enchants = is.getItemMeta().getEnchants();
} else {
ItemMeta im = is.getItemMeta();
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<>();
Map<Enchantment, Integer> enchants = is.getItemMeta().getEnchants();
tag.append(",tag:{display:{Name:").append(enchants.size() > 0 ? "§b§o" : "§f").append(ItemUtils.getCustomName(is));
if (lore.size() > 0) {
tag.append(",Lore:[");
for (String s : lore){
if (lore.size() > 0) {
tag.append(",Lore:[");
for (String s : lore) {
tag.append("\"").append(s).append("\",");
}
tag.delete(tag.length() - 1, tag.length());
tag.append("]");
}
tag.append("}");
if (enchants.size() > 0) {
if(tag.length() > 6) {
tag.append(",");
}
tag.append("ench:[");
for (Entry<Enchantment, Integer> e : enchants.entrySet()) {
}
tag.delete(tag.length() - 1, tag.length());
tag.append("]");
}
tag.append("}");
if (enchants.size() > 0) {
if (tag.length() > 6) {
tag.append(",");
}
tag.append("ench:[");
for (Entry<Enchantment, Integer> e : enchants.entrySet()) {
tag.append("{id:").append(e.getKey().getId()).append(",lvl:").append(e.getValue()).append("},");
}
tag.delete(tag.length() - 1, tag.length());
tag.append("]");
}
tag.append("}");
}
object.put("value", "{id:" + (TabooLib.getVerint() > 10700 ? DabItemUtils.getMinecraftName(is) : is.getTypeId()) + ",Count:" + is.getAmount() + tag.toString() + "}");
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public JSONObject getEvent(){
return object;
}
}
tag.delete(tag.length() - 1, tag.length());
tag.append("]");
}
tag.append("}");
}
object.put("value", "{id:" + (TabooLib.getVerint() > 10700 ? DabItemUtils.getMinecraftName(is) : is.getTypeId()) + ",Count:" + is.getAmount() + tag.toString() + "}");
} catch (Exception ignored) {
}
}
@Override
public JSONObject getEvent() {
return object;
}
}

View File

@ -14,29 +14,29 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent;
public class ListenerPlayerCommand implements Listener {
@EventHandler
public void cmd(ServerCommandEvent e) {
if ("savefile".equals(e.getCommand())) {
if (TabooLib.getVerint() > 10700) {
e.setCancelled(true);
}
@EventHandler
public void cmd(ServerCommandEvent e) {
if ("savefile".equals(e.getCommand())) {
if (TabooLib.getVerint() > 10700) {
e.setCancelled(true);
}
Bukkit.getScheduler().runTask(Main.getInst(), DataUtils::saveAllCaches);
Bukkit.getScheduler().runTask(Main.getInst(), () -> PlayerDataManager.saveAllCaches(true, false));
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void cmd(PlayerCommandPreprocessEvent e) {
if ("/unbreakable".equals(e.getMessage()) && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) {
e.setCancelled(true);
NBTItem nbti = new NBTItem(e.getPlayer().getItemInHand());
nbti.setInteger("Unbreakable", 1);
e.getPlayer().setItemInHand(nbti.getItem());
MsgUtils.send(e.getPlayer(), "Success!");
}
}
Bukkit.getScheduler().runTask(Main.getInst(), () -> PlayerDataManager.saveAllCaches(true, false));
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void cmd(PlayerCommandPreprocessEvent e) {
if ("/unbreakable".equals(e.getMessage()) && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) {
e.setCancelled(true);
NBTItem nbti = new NBTItem(e.getPlayer().getItemInHand());
nbti.setInteger("Unbreakable", 1);
e.getPlayer().setItemInHand(nbti.getItem());
MsgUtils.send(e.getPlayer(), "Success!");
}
}
}

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

View File

@ -22,17 +22,19 @@ import java.lang.reflect.Method;
import java.util.*;
import java.util.logging.Level;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Deprecated
/**
* @author Unknown
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class NMSUtil19 {
protected static boolean failed = false;
protected static boolean legacy = false;
protected static String versionPrefix = "";
protected final static int NBT_TYPE_COMPOUND = 10;
protected final static int NBT_TYPE_INT_ARRAY= 11;
protected final static int NBT_TYPE_INT_ARRAY = 11;
protected final static int NBT_TYPE_DOUBLE = 6;
protected final static int NBT_TYPE_FLOAT = 5;
protected final static int NBT_TYPE_STRING = 8;
@ -40,91 +42,91 @@ public class NMSUtil19 {
protected static int WITHER_SKULL_TYPE = 66;
protected static int FIREWORK_TYPE = 76;
protected static Class<?> class_Block;
protected static Class<?> class_ItemStack;
protected static Class<?> class_NBTBase;
protected static Class<?> class_NBTTagCompound;
protected static Class<?> class_NBTTagList;
protected static Class<?> class_NBTTagByte;
protected static Class<?> class_NBTTagDouble;
protected static Class<?> class_NBTTagFloat;
protected static Class<?> class_NBTTagInt;
protected static Class<?> class_NBTTagLong;
protected static Class<?> class_NBTTagShort;
protected static Class<?> class_NBTTagString;
protected static Class<?> class_CraftTask;
protected static Class<?> class_CraftInventoryCustom;
protected static Class<?> class_CraftItemStack;
protected static Class<?> class_CraftBlockState;
protected static Class<?> class_CraftLivingEntity;
protected static Class<?> class_CraftWorld;
protected static Class<?> class_Consumer;
protected static Class<?> class_Entity;
protected static Class<?> class_EntityCreature;
protected static Class<?> class_EntityLiving;
protected static Class<?> class_EntityHuman;
protected static Class<?> class_DataWatcher;
protected static Class<?> class_DamageSource;
protected static Class<?> class_EntityDamageSource;
protected static Class<?> class_World;
protected static Class<?> class_WorldServer;
protected static Class<?> class_Packet;
public static Class<?> class_Block;
public static Class<?> class_ItemStack;
public static Class<?> class_NBTBase;
public static Class<?> class_NBTTagCompound;
public static Class<?> class_NBTTagList;
public static Class<?> class_NBTTagByte;
public static Class<?> class_NBTTagDouble;
public static Class<?> class_NBTTagFloat;
public static Class<?> class_NBTTagInt;
public static Class<?> class_NBTTagLong;
public static Class<?> class_NBTTagShort;
public static Class<?> class_NBTTagString;
public static Class<?> class_CraftTask;
public static Class<?> class_CraftInventoryCustom;
public static Class<?> class_CraftItemStack;
public static Class<?> class_CraftBlockState;
public static Class<?> class_CraftLivingEntity;
public static Class<?> class_CraftWorld;
public static Class<?> class_Consumer;
public static Class<?> class_Entity;
public static Class<?> class_EntityCreature;
public static Class<?> class_EntityLiving;
public static Class<?> class_EntityHuman;
public static Class<?> class_DataWatcher;
public static Class<?> class_DamageSource;
public static Class<?> class_EntityDamageSource;
public static Class<?> class_World;
public static Class<?> class_WorldServer;
public static Class<?> class_Packet;
protected static Class<Enum> class_EnumSkyBlock;
protected static Class<?> class_EntityPainting;
protected static Class<?> class_EntityItemFrame;
protected static Class<?> class_EntityMinecartRideable;
protected static Class<?> class_EntityTNTPrimed;
protected static Class<?> class_AxisAlignedBB;
protected static Class<?> class_PathPoint;
protected static Class<?> class_PathEntity;
protected static Class<?> class_EntityFirework;
protected static Class<?> class_CraftSkull;
protected static Class<?> class_CraftBanner;
protected static Class<?> class_CraftMetaSkull;
protected static Class<?> class_CraftMetaBanner;
protected static Class<?> class_GameProfile;
protected static Class<?> class_GameProfileProperty;
protected static Class<?> class_BlockPosition;
protected static Class<?> class_NBTCompressedStreamTools;
protected static Class<?> class_TileEntity;
protected static Class<?> class_TileEntitySign;
protected static Class<?> class_TileEntityContainer;
protected static Class<?> class_ChestLock;
public static Class<?> class_EntityPainting;
public static Class<?> class_EntityItemFrame;
public static Class<?> class_EntityMinecartRideable;
public static Class<?> class_EntityTNTPrimed;
public static Class<?> class_AxisAlignedBB;
public static Class<?> class_PathPoint;
public static Class<?> class_PathEntity;
public static Class<?> class_EntityFirework;
public static Class<?> class_CraftSkull;
public static Class<?> class_CraftBanner;
public static Class<?> class_CraftMetaSkull;
public static Class<?> class_CraftMetaBanner;
public static Class<?> class_GameProfile;
public static Class<?> class_GameProfileProperty;
public static Class<?> class_BlockPosition;
public static Class<?> class_NBTCompressedStreamTools;
public static Class<?> class_TileEntity;
public static Class<?> class_TileEntitySign;
public static Class<?> class_TileEntityContainer;
public static Class<?> class_ChestLock;
protected static Class<Enum> class_EnumDirection;
protected static Class<?> class_EntityHorse;
protected static Class<?> class_EntityWitherSkull;
protected static Class<?> class_PacketPlayOutAttachEntity;
protected static Class<?> class_PacketPlayOutEntityDestroy;
protected static Class<?> class_PacketPlayOutSpawnEntity;
protected static Class<?> class_PacketPlayOutSpawnEntityLiving;
protected static Class<?> class_PacketPlayOutEntityMetadata;
protected static Class<?> class_PacketPlayOutEntityStatus;
protected static Class<?> class_PacketPlayOutCustomSoundEffect;
protected static Class<?> class_PacketPlayOutExperience;
protected static Class<?> class_PacketPlayOutAnimation;
protected static Class<?> class_PacketPlayOutBlockBreakAnimation;
public static Class<?> class_EntityHorse;
public static Class<?> class_EntityWitherSkull;
public static Class<?> class_PacketPlayOutAttachEntity;
public static Class<?> class_PacketPlayOutEntityDestroy;
public static Class<?> class_PacketPlayOutSpawnEntity;
public static Class<?> class_PacketPlayOutSpawnEntityLiving;
public static Class<?> class_PacketPlayOutEntityMetadata;
public static Class<?> class_PacketPlayOutEntityStatus;
public static Class<?> class_PacketPlayOutCustomSoundEffect;
public static Class<?> class_PacketPlayOutExperience;
public static Class<?> class_PacketPlayOutAnimation;
public static Class<?> class_PacketPlayOutBlockBreakAnimation;
protected static Enum<?> enum_SoundCategory_PLAYERS;
protected static Class<Enum> class_EnumSoundCategory;
protected static Class<?> class_EntityFallingBlock;
protected static Class<?> class_EntityArmorStand;
protected static Class<?> class_EntityPlayer;
protected static Class<?> class_PlayerConnection;
protected static Class<?> class_Chunk;
protected static Class<?> class_CraftPlayer;
protected static Class<?> class_CraftChunk;
protected static Class<?> class_CraftEntity;
protected static Class<?> class_EntityProjectile;
protected static Class<?> class_EntityFireball;
protected static Class<?> class_EntityArrow;
protected static Class<?> class_CraftArrow;
protected static Class<?> class_MinecraftServer;
protected static Class<?> class_CraftServer;
protected static Class<?> class_DataWatcherObject;
protected static Class<?> class_PacketPlayOutChat;
public static Class<?> class_EntityFallingBlock;
public static Class<?> class_EntityArmorStand;
public static Class<?> class_EntityPlayer;
public static Class<?> class_PlayerConnection;
public static Class<?> class_Chunk;
public static Class<?> class_CraftPlayer;
public static Class<?> class_CraftChunk;
public static Class<?> class_CraftEntity;
public static Class<?> class_EntityProjectile;
public static Class<?> class_EntityFireball;
public static Class<?> class_EntityArrow;
public static Class<?> class_CraftArrow;
public static Class<?> class_MinecraftServer;
public static Class<?> class_CraftServer;
public static Class<?> class_DataWatcherObject;
public static Class<?> class_PacketPlayOutChat;
protected static Class<Enum> class_ChatMessageType;
protected static Enum<?> enum_ChatMessageType_GAME_INFO;
protected static Class<?> class_ChatComponentText;
protected static Class<?> class_IChatBaseComponent;
public static Class<?> class_ChatComponentText;
public static Class<?> class_IChatBaseComponent;
protected static Method class_NBTTagList_addMethod;
protected static Method class_NBTTagList_getMethod;
@ -275,8 +277,7 @@ public class NMSUtil19 {
protected static Field class_Entity_moveStrafingField;
protected static Field class_Entity_moveForwardField;
static
{
static {
// Find classes Bukkit hides from us. :-D
// Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach.
String className = Bukkit.getServer().getClass().getName();
@ -312,8 +313,8 @@ public class NMSUtil19 {
class_Packet = fixBukkitClass("net.minecraft.server.Packet");
class_World = fixBukkitClass("net.minecraft.server.World");
class_WorldServer = fixBukkitClass("net.minecraft.server.WorldServer");
class_EnumSkyBlock = (Class<Enum>)fixBukkitClass("net.minecraft.server.EnumSkyBlock");
class_EnumSoundCategory = (Class<Enum>)fixBukkitClass("net.minecraft.server.SoundCategory");
class_EnumSkyBlock = (Class<Enum>) fixBukkitClass("net.minecraft.server.EnumSkyBlock");
class_EnumSoundCategory = (Class<Enum>) fixBukkitClass("net.minecraft.server.SoundCategory");
enum_SoundCategory_PLAYERS = Enum.valueOf(class_EnumSoundCategory, "PLAYERS");
class_EntityPainting = fixBukkitClass("net.minecraft.server.EntityPainting");
class_EntityCreature = fixBukkitClass("net.minecraft.server.EntityCreature");
@ -377,7 +378,7 @@ public class NMSUtil19 {
class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class);
class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class);
class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE);
class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", org.bukkit.inventory.ItemStack.class);
class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", ItemStack.class);
class_CraftItemStack_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack);
class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack);
class_World_addEntityMethod = class_World.getMethod("addEntity", class_Entity, CreatureSpawnEvent.SpawnReason.class);
@ -394,7 +395,7 @@ public class NMSUtil19 {
class_EntityPlayer_setResourcePackMethod = class_EntityPlayer.getMethod("setResourcePack", String.class, String.class);
class_CraftServer_getServerMethod = class_CraftServer.getMethod("getServer");
class_MinecraftServer_getResourcePackMethod = class_MinecraftServer.getMethod("getResourcePack");
class_CraftInventoryCustom_constructor = class_CraftInventoryCustom.getConstructor(InventoryHolder.class, Integer.TYPE, String.class);
class_EntityFireworkConstructor = class_EntityFirework.getConstructor(class_World, Double.TYPE, Double.TYPE, Double.TYPE, class_ItemStack);
class_PacketSpawnEntityConstructor = class_PacketPlayOutSpawnEntity.getConstructor(class_Entity, Integer.TYPE);
@ -478,10 +479,10 @@ public class NMSUtil19 {
class_Chunk_doneField.setAccessible(true);
class_CraftItemStack_getHandleField = class_CraftItemStack.getDeclaredField("handle");
class_CraftItemStack_getHandleField.setAccessible(true);
class_MemorySection_mapField = MemorySection.class.getDeclaredField("map");
class_MemorySection_mapField.setAccessible(true);
class_TileEntityContainer = fixBukkitClass("net.minecraft.server.TileEntityContainer");
class_ChestLock = fixBukkitClass("net.minecraft.server.ChestLock");
class_Entity_getBoundingBox = class_Entity.getMethod("getBoundingBox");
@ -508,7 +509,7 @@ public class NMSUtil19 {
class_CraftBanner_setPatternsMethod = class_CraftBanner.getMethod("setPatterns", List.class);
class_CraftBanner_setBaseColorMethod = class_CraftBanner.getMethod("setBaseColor", DyeColor.class);
class_EnumDirection = (Class<Enum>)fixBukkitClass("net.minecraft.server.EnumDirection");
class_EnumDirection = (Class<Enum>) fixBukkitClass("net.minecraft.server.EnumDirection");
class_BlockPosition_Constructor = class_BlockPosition.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE);
class_EntityPaintingConstructor = class_EntityPainting.getConstructor(class_World, class_BlockPosition, class_EnumDirection);
class_EntityItemFrameConstructor = class_EntityItemFrame.getConstructor(class_World, class_BlockPosition, class_EnumDirection);
@ -603,7 +604,7 @@ public class NMSUtil19 {
class_ChatComponentText_constructor = class_ChatComponentText.getConstructor(String.class);
// 1.12 specific
class_ChatMessageType = (Class<Enum>)fixBukkitClass("net.minecraft.server.ChatMessageType");
class_ChatMessageType = (Class<Enum>) fixBukkitClass("net.minecraft.server.ChatMessageType");
enum_ChatMessageType_GAME_INFO = Enum.valueOf(class_ChatMessageType, "GAME_INFO");
class_PacketPlayOutChat_constructor = class_PacketPlayOutChat.getConstructor(class_IChatBaseComponent, class_ChatMessageType);
@ -771,8 +772,7 @@ public class NMSUtil19 {
Bukkit.getLogger().log(Level.WARNING, "An error occurred, setting arrow lifespan will not work", ex);
class_EntityArrow_lifeField = null;
}
if (class_EntityArrow_lifeField != null)
{
if (class_EntityArrow_lifeField != null) {
class_EntityArrow_lifeField.setAccessible(true);
}
@ -874,8 +874,7 @@ public class NMSUtil19 {
// 1.10 and earlier
legacy = true;
}
}
catch (Throwable ex) {
} catch (Throwable ex) {
failed = true;
Bukkit.getLogger().log(Level.SEVERE, "An unexpected error occurred initializing Magic", ex);
}
@ -884,7 +883,7 @@ public class NMSUtil19 {
public static boolean getFailed() {
return failed;
}
public static boolean isLegacy() {
return legacy;
}
@ -912,7 +911,7 @@ public class NMSUtil19 {
}
public static Class<?> getBukkitClass(String className) {
Class<?> result = null;
Class<?> result;
try {
result = fixBukkitClass(className);
} catch (Exception ex) {
@ -922,16 +921,20 @@ public class NMSUtil19 {
return result;
}
public static Class<?> fixBukkitClass(String className) throws ClassNotFoundException {
public static Class<?> fixBukkitClass(String className) {
if (!versionPrefix.isEmpty()) {
className = className.replace("org.bukkit.craftbukkit.", "org.bukkit.craftbukkit." + versionPrefix);
className = className.replace("net.minecraft.server.", "net.minecraft.server." + versionPrefix);
}
return NMSUtils.class.getClassLoader().loadClass(className);
try {
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;
try {
handle = class_CraftServer_getServerMethod.invoke(server);
@ -941,7 +944,7 @@ public class NMSUtil19 {
return handle;
}
public static Object getHandle(org.bukkit.inventory.ItemStack stack) {
public static Object getHandle(ItemStack stack) {
Object handle = null;
try {
handle = class_CraftItemStack_getHandleField.get(stack);
@ -951,7 +954,7 @@ public class NMSUtil19 {
return handle;
}
public static Object getHandle(org.bukkit.World world) {
public static Object getHandle(World world) {
if (world == null) {
return null;
}
@ -964,7 +967,7 @@ public class NMSUtil19 {
return handle;
}
public static Object getHandle(org.bukkit.entity.Entity entity) {
public static Object getHandle(Entity entity) {
if (entity == null) {
return null;
}
@ -990,18 +993,18 @@ public class NMSUtil19 {
return handle;
}
public static boolean isDone(org.bukkit.Chunk chunk) {
public static boolean isDone(Chunk chunk) {
Object chunkHandle = getHandle(chunk);
boolean done = false;
try {
done = (Boolean)class_Chunk_doneField.get(chunkHandle);
done = (Boolean) class_Chunk_doneField.get(chunkHandle);
} catch (Throwable ex) {
ex.printStackTrace();
}
return done;
}
public static Object getHandle(org.bukkit.Chunk chunk) {
public static Object getHandle(Chunk chunk) {
Object handle = null;
try {
handle = class_CraftChunk_getHandleMethod.invoke(chunk);
@ -1011,7 +1014,7 @@ public class NMSUtil19 {
return handle;
}
public static Object getHandle(org.bukkit.entity.Player player) {
public static Object getHandle(Player player) {
Object handle = null;
try {
handle = class_CraftPlayer_getHandleMethod.invoke(player);
@ -1021,11 +1024,11 @@ public class NMSUtil19 {
return handle;
}
protected static void sendPacket(Server server, Location source, Collection<? extends Player> players, Object packet) throws Exception {
protected static void sendPacket(Server server, Location source, Collection<? extends Player> players, Object packet) throws Exception {
players = ((players != null && players.size() > 0) ? players : server.getOnlinePlayers());
int viewDistance = Bukkit.getServer().getViewDistance() * 16;
int viewDistanceSquared = viewDistance * viewDistance;
int viewDistanceSquared = viewDistance * viewDistance;
World sourceWorld = source.getWorld();
for (Player player : players) {
Location location = player.getLocation();
@ -1045,41 +1048,39 @@ public class NMSUtil19 {
Method sendPacketMethod = connection.getClass().getMethod("sendPacket", class_Packet);
sendPacketMethod.invoke(connection, packet);
}
public static int getFacing(BlockFace direction)
{
public static int getFacing(BlockFace direction) {
int dir;
switch (direction) {
case SOUTH:
default:
dir = 0;
break;
case WEST:
dir = 1;
break;
case NORTH:
dir = 2;
break;
case EAST:
dir = 3;
break;
case SOUTH:
default:
dir = 0;
break;
case WEST:
dir = 1;
break;
case NORTH:
dir = 2;
break;
case EAST:
dir = 3;
break;
}
return dir;
}
public static org.bukkit.entity.Entity getBukkitEntity(Object entity)
{
public static Entity getBukkitEntity(Object entity) {
if (entity == null) {
return null;
}
try {
Method getMethod = entity.getClass().getMethod("getBukkitEntity");
Object bukkitEntity = getMethod.invoke(entity);
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) {
if (!(bukkitEntity instanceof Entity)) {
return null;
}
return (org.bukkit.entity.Entity)bukkitEntity;
return (Entity) bukkitEntity;
} catch (Throwable ex) {
ex.printStackTrace();
}
@ -1197,7 +1198,7 @@ public class NMSUtil19 {
}
Boolean result = false;
try {
result = (Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag);
result = (Boolean) class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
@ -1267,7 +1268,7 @@ public class NMSUtil19 {
}
String meta = null;
try {
meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag);
meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
@ -1280,7 +1281,7 @@ public class NMSUtil19 {
}
String meta = null;
try {
meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag);
meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
@ -1293,7 +1294,7 @@ public class NMSUtil19 {
}
Byte meta = null;
try {
meta = (Byte)class_NBTTagCompound_getByteMethod.invoke(node, tag);
meta = (Byte) class_NBTTagCompound_getByteMethod.invoke(node, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
@ -1306,7 +1307,7 @@ public class NMSUtil19 {
}
Integer meta = null;
try {
meta = (Integer)class_NBTTagCompound_getIntMethod.invoke(node, tag);
meta = (Integer) class_NBTTagCompound_getIntMethod.invoke(node, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
@ -1319,7 +1320,7 @@ public class NMSUtil19 {
}
Boolean meta = null;
try {
meta = (Boolean)class_NBTTagCompound_getBooleanMethod.invoke(node, tag);
meta = (Boolean) class_NBTTagCompound_getBooleanMethod.invoke(node, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
@ -1327,7 +1328,7 @@ public class NMSUtil19 {
}
public static void setMeta(Object node, String tag, String value) {
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
if (node == null || !class_NBTTagCompound.isInstance(node)) {
return;
}
try {
@ -1342,7 +1343,7 @@ public class NMSUtil19 {
}
public static void setMetaLong(Object node, String tag, long value) {
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
if (node == null || !class_NBTTagCompound.isInstance(node)) {
return;
}
try {
@ -1353,7 +1354,7 @@ public class NMSUtil19 {
}
public static void setMetaBoolean(Object node, String tag, boolean value) {
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
if (node == null || !class_NBTTagCompound.isInstance(node)) {
return;
}
try {
@ -1364,7 +1365,7 @@ public class NMSUtil19 {
}
public static void setMetaDouble(Object node, String tag, double value) {
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
if (node == null || !class_NBTTagCompound.isInstance(node)) {
return;
}
try {
@ -1375,7 +1376,7 @@ public class NMSUtil19 {
}
public static void setMetaInt(Object node, String tag, int value) {
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
if (node == null || !class_NBTTagCompound.isInstance(node)) {
return;
}
try {
@ -1386,7 +1387,7 @@ public class NMSUtil19 {
}
public static void removeMeta(Object node, String tag) {
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
if (node == null || !class_NBTTagCompound.isInstance(node)) {
return;
}
try {
@ -1453,7 +1454,7 @@ public class NMSUtil19 {
ex.printStackTrace();
return false;
}
return true;
}
@ -1471,7 +1472,7 @@ public class NMSUtil19 {
if (tagObject == null) {
return null;
}
meta = (String)class_NBTTagCompound_getStringMethod.invoke(tagObject, tag);
meta = (String) class_NBTTagCompound_getStringMethod.invoke(tagObject, tag);
} catch (Throwable ex) {
ex.printStackTrace();
}
@ -1578,7 +1579,7 @@ public class NMSUtil19 {
} catch (Throwable ignored) {
}
return unbreakableFlag != null && unbreakableFlag;
}
@ -1646,7 +1647,7 @@ public class NMSUtil19 {
Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks);
Field cancelledField = explosion.getClass().getDeclaredField("wasCanceled");
result = (Boolean)cancelledField.get(explosion);
result = (Boolean) cancelledField.get(explosion);
} catch (Throwable ex) {
ex.printStackTrace();
result = false;
@ -1665,7 +1666,7 @@ public class NMSUtil19 {
public static void makeUnplaceable(ItemStack itemStack) {
setMeta(itemStack, "unplaceable", "true");
}
public static void removeUnplaceable(ItemStack itemStack) {
removeMeta(itemStack, "unplaceable");
}
@ -1743,7 +1744,7 @@ public class NMSUtil19 {
} else {
nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag);
}
item = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, nmsStack);
item = (ItemStack) class_CraftItemStack_mirrorMethod.invoke(null, nmsStack);
} catch (Exception ex) {
ex.printStackTrace();
}
@ -1753,7 +1754,7 @@ public class NMSUtil19 {
public static ItemStack[] getItems(Object rootTag, String tagName) {
try {
Object itemList = class_NBTTagCompound_getListMethod.invoke(rootTag, tagName, NBT_TYPE_COMPOUND);
Integer size = (Integer)class_NBTTagList_sizeMethod.invoke(itemList);
Integer size = (Integer) class_NBTTagList_sizeMethod.invoke(itemList);
ItemStack[] items = new ItemStack[size];
for (int i = 0; i < size; i++) {
try {
@ -1823,10 +1824,10 @@ public class NMSUtil19 {
class_TileEntity_saveMethod.invoke(tileEntity, entityData);
Object itemList = class_NBTTagCompound_getListMethod.invoke(entityData, "Items", NBT_TYPE_COMPOUND);
if (itemList != null) {
List items = (List)class_NBTTagList_list.get(itemList);
List items = (List) class_NBTTagList_list.get(itemList);
items.clear();
}
class_NBTTagCompound_removeMethod.invoke(entityData,"Item");
class_NBTTagCompound_removeMethod.invoke(entityData, "Item");
class_TileEntity_loadMethod.invoke(tileEntity, entityData);
class_TileEntity_updateMethod.invoke(tileEntity);
}
@ -1871,9 +1872,9 @@ public class NMSUtil19 {
}
try {
Object posList = class_NBTTagCompound_getListMethod.invoke(entityData, tag, NBT_TYPE_DOUBLE);
Double x = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 0);
Double y = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 1);
Double z = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 2);
Double x = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 0);
Double y = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 1);
Double z = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 2);
if (x != null && y != null && z != null) {
return new Vector(x, y, z);
}
@ -1886,7 +1887,7 @@ public class NMSUtil19 {
public static Entity getEntity(World world, UUID uuid) {
try {
Object worldHandle = getHandle(world);
final Map<UUID, Entity> entityMap = (Map<UUID, Entity>)class_WorldServer_entitiesByUUIDField.get(worldHandle);
final Map<UUID, Entity> entityMap = (Map<UUID, Entity>) class_WorldServer_entitiesByUUIDField.get(worldHandle);
if (entityMap != null) {
Object nmsEntity = entityMap.get(uuid);
if (nmsEntity != null) {
@ -1906,9 +1907,8 @@ public class NMSUtil19 {
ex.printStackTrace();
}
}
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 {
Object packet = class_PacketPlayOutCustomSoundEffect_Constructor.newInstance(sound, enum_SoundCategory_PLAYERS, location.getX(), location.getY(), location.getZ(), volume, pitch);
sendPacket(player, packet);
@ -1917,17 +1917,15 @@ public class NMSUtil19 {
}
}
public static Map<String, Object> getMap(ConfigurationSection section)
{
public static Map<String, Object> getMap(ConfigurationSection section) {
if (section == null) {
return null;
}
if (section instanceof MemorySection)
{
if (section instanceof MemorySection) {
try {
Object mapObject = class_MemorySection_mapField.get(section);
if (mapObject instanceof Map) {
return (Map<String, Object>)mapObject;
return (Map<String, Object>) mapObject;
}
} catch (Exception ex) {
ex.printStackTrace();
@ -1940,7 +1938,7 @@ public class NMSUtil19 {
for (String key : keys) {
map.put(key, section.get(key));
}
return map;
}
@ -1956,7 +1954,7 @@ public class NMSUtil19 {
if (handle == null) {
return false;
}
return (Boolean)class_ItemStack_isEmptyMethod.invoke(handle);
return (Boolean) class_ItemStack_isEmptyMethod.invoke(handle);
} catch (Throwable ex) {
ex.printStackTrace();
}

View File

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

View File

@ -8,54 +8,56 @@ import org.bukkit.inventory.ItemStack;
import java.util.HashSet;
@SuppressWarnings("deprecation")
/**
* @author sky
*/
public class PlayerUtils {
/**
* 获取目标方块
*
* @param player 玩家
* @param max 最大视野
* @return
*/
public static Block getTargetBlock(Player player, int max) {
HashSet<Byte> Byte = new HashSet<>();
Byte.add((byte) 0);
return player.getTargetBlock(Byte, max);
}
/**
* 重写数据
*
* @param player 玩家
* @param scoreboard 是否清理计分板
*/
public static void resetData(Player player, boolean scoreboard) {
if (player.isDead()) {
player.spigot().respawn();
}
player.closeInventory();
player.setGameMode(GameMode.SURVIVAL);
player.getInventory().setArmorContents(new ItemStack[4]);
player.getInventory().setContents(new ItemStack[0]);
player.setAllowFlight(false);
player.setFlying(false);
player.setExp(0.0F);
player.setLevel(0);
player.setSneaking(false);
player.setSprinting(false);
player.setFoodLevel(20);
player.setSaturation(10.0F);
player.setExhaustion(0.0F);
player.setMaxHealth(20.0D);
player.setHealth(20.0D);
player.setFireTicks(0);
player.setItemOnCursor(null);
player.getActivePotionEffects().clear();
player.getEnderChest().clear();
player.updateInventory();
if (scoreboard) {
player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
}
/**
* 获取目标方块
*
* @param player 玩家
* @param max 最大视野
* @return
*/
public static Block getTargetBlock(Player player, int max) {
HashSet<Byte> bytes = new HashSet<>();
bytes.add((byte) 0);
return player.getTargetBlock(bytes, max);
}
/**
* 重写数据
*
* @param player 玩家
* @param scoreboard 是否清理计分板
*/
public static void resetData(Player player, boolean scoreboard) {
if (player.isDead()) {
player.spigot().respawn();
}
player.closeInventory();
player.setGameMode(GameMode.SURVIVAL);
player.getInventory().setArmorContents(new ItemStack[4]);
player.getInventory().setContents(new ItemStack[0]);
player.setAllowFlight(false);
player.setFlying(false);
player.setExp(0.0F);
player.setLevel(0);
player.setSneaking(false);
player.setSprinting(false);
player.setFoodLevel(20);
player.setSaturation(10.0F);
player.setExhaustion(0.0F);
player.setMaxHealth(20.0D);
player.setHealth(20.0D);
player.setFireTicks(0);
player.setItemOnCursor(null);
player.getActivePotionEffects().clear();
player.getEnderChest().clear();
player.updateInventory();
if (scoreboard) {
player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
}
}

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

View File

@ -1,5 +1,10 @@
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.Collections;
import java.util.List;
@ -11,34 +16,80 @@ import java.util.stream.IntStream;
* @since 2018-04-16
*/
public class ArrayUtils {
public static <T> List<T> asList(T... args) {
List<T> list = new ArrayList<>();
Collections.addAll(list, args);
return list;
}
public static String[] addFirst(String[] args, String... value) {
if (args.length < 1) {
return value;
}
List<String> list = asList(args);
for (int i = value.length - 1 ; i >= 0 ; i--) {
list.add(0, value[i]);
}
return list.toArray(new String[0]);
}
public static String[] removeFirst(String[] args) {
if (args.length <= 1) {
return new String[0];
}
List<String> list = asList(args);
list.remove(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();
}
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) {
List<T> list = new ArrayList<>();
Collections.addAll(list, args);
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) {
if (args.length < 1) {
return value;
}
List<String> list = asList(args);
for (int i = value.length - 1; i >= 0; i--) {
list.add(0, value[i]);
}
return list.toArray(new String[0]);
}
@Deprecated
public static String[] removeFirst(String[] args) {
if (args.length <= 1) {
return new String[0];
}
List<String> list = asList(args);
list.remove(0);
return list.toArray(new String[0]);
}
}

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;
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.action.ClickAction;
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.inventory.ItemUtils;
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.Language2Line;
import me.skymc.taboolib.string.language2.Language2Value;
@ -21,7 +26,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
@ -52,17 +56,15 @@ public class Language2Book implements Language2Line {
// 变量
this.player = player;
this.value = format.getLanguage2Value();
// 获取书本设置
this.book = BookFormatter.writtenBook();
// 设置
formatOptions(list);
// 书本
book = BookFormatter.writtenBook();
// 内容
PageBuilder page = new PageBuilder();
// 遍历内容
for (String line : list) {
// 翻页
if ("[page]".equals(line)) {
if (line.equals("[page]")) {
book.addPages(page.build());
page = new PageBuilder();
}
@ -70,57 +72,50 @@ public class Language2Book implements Language2Line {
else if (line.startsWith("@option")) {
break;
} else {
Matcher matcher = pattern.matcher(line);
boolean find = false;
while (matcher.find()) {
find = true;
String optionName = matcher.group(1);
String optionFullName = "<@" + matcher.group(1) + ">";
// 判断设置是否存在
if (!options.containsKey(optionName)) {
page.add("§4[<ERROR-50: " + format.getLanguage2Value().getLanguageKey() + ">]");
} else {
String[] line_split = line.split(optionFullName);
try {
// 单独一行
if (line_split.length == 0) {
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);
}
// 更改文本
line = sb.substring(0, sb.length() - optionFullName.length());
// 如果后段还有变量
if (!pattern.matcher(line).find()) {
page.add(line_split[1]).endLine();
}
} else {
page.endLine();
}
for (VariableFormatter.Variable variable : new VariableFormatter(line, pattern).find().getVariableList()) {
if (variable.isVariable()) {
String node = variable.getText().substring(1);
if (!options.containsKey(node)) {
page.add("§4[<ERROR-50: " + format.getLanguage2Value().getLanguageKey() + ">]");
} else {
TextBuilder builder = options.get(node);
BaseComponent component = new TextComponent(builder.getText());
if (builder.getHover() != null) {
component.setHoverEvent(new HoverEvent(builder.getHover().action(), builder.getHover().value()));
}
} catch (Exception e) {
page.add("§4[<ERROR-51: " + format.getLanguage2Value().getLanguageKey() + ">]");
if (builder.getClick() != null) {
component.setClickEvent(new ClickEvent(builder.getClick().action(), builder.getClick().value()));
}
page.add(component);
}
} else {
page.add(variable.getText());
}
}
if (!find) {
page.add(line).endLine();
}
page.newLine();
}
}
// 结尾
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() {
return pattern;
}
@ -141,6 +136,46 @@ public class Language2Book implements Language2Line {
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) {
// 获取书本设置
HashMap<String, List<String>> _options = getOptions(list);
@ -204,14 +239,4 @@ public class Language2Book implements Language2Line {
options_source.put(optionName, option);
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;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.EnumWrappers;
import com.comphenix.protocol.wrappers.PlayerInfoData;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.google.common.base.Preconditions;
import com.ilummc.tlib.bungee.api.ChatColor;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.events.itag.AsyncPlayerReceiveNameTagEvent;
import me.skymc.taboolib.events.itag.PlayerReceiveNameTagEvent;
import me.skymc.taboolib.itagapi.TagDataHandler;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.*;
import java.util.stream.IntStream;
import java.util.Set;
/**
* @Author sky
* @Since 2018-05-09 21:03
*/
public class TagAPI implements Listener {
@Deprecated
public class TagAPI {
private static final int[] uuidSplit = new int[]{0, 8, 12, 16, 20, 32};
private static boolean loaded = false;
private static HashMap<Integer, Player> entityIdMap = new HashMap<>();
private static HashMap<UUID, String> playerData = new HashMap<>();
/**
* 该工具于 2018年5月23日02:31:14 失效
* 新工具类: {@link TagDataHandler}
*/
TagAPI() {
}
public static void inst() {
assert !loaded : "TagAPI is already instanced!";
loaded = true;
Bukkit.getServer().getOnlinePlayers().forEach(player -> entityIdMap.put(player.getEntityId(), player));
Bukkit.getPluginManager().registerEvents(new TagAPI(), Main.getInst());
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(Main.getInst(), PacketType.Play.Server.PLAYER_INFO) {
@Override
public void onPacketSending(PacketEvent event) {
if (event.getPacket().getPlayerInfoAction().read(0) != EnumWrappers.PlayerInfoAction.ADD_PLAYER) {
return;
}
List<PlayerInfoData> newPlayerInfo = new ArrayList<>();
for (PlayerInfoData playerInfo : event.getPacket().getPlayerInfoDataLists().read(0)) {
Player player;
if (playerInfo == null || playerInfo.getProfile() == null || (player = Bukkit.getServer().getPlayer(playerInfo.getProfile().getUUID())) == null) {
// Unknown Player
newPlayerInfo.add(playerInfo);
continue;
}
newPlayerInfo.add(new PlayerInfoData(getSentName(player.getEntityId(), playerInfo.getProfile(), event.getPlayer()), playerInfo.getPing(), playerInfo.getGameMode(), playerInfo.getDisplayName()));
}
event.getPacket().getPlayerInfoDataLists().write(0, newPlayerInfo);
}
});
}
public static String getPlayerDisplayName(Player player) {
return playerData.getOrDefault(player.getUniqueId(), player.getName());
return TagDataHandler.getHandler().getDisplay(player);
}
public static void setPlayerDisplayName(Player player, String name) {
String nameColored = ChatColor.translateAlternateColorCodes('&', name);
player.setDisplayName(nameColored);
player.setPlayerListName(nameColored);
playerData.put(player.getUniqueId(), nameColored);
Bukkit.getScheduler().runTask(Main.getInst(), () -> refreshPlayer(player));
TagDataHandler.getHandler().setDisplay(player, name);
}
public static void removePlayerDisplayName(Player player) {
player.setDisplayName(null);
player.setPlayerListName(null);
playerData.remove(player.getUniqueId());
Bukkit.getScheduler().runTask(Main.getInst(), () -> refreshPlayer(player));
TagDataHandler.getHandler().setDisplay(player, player.getName());
}
public static void refreshPlayer(Player player) {
@ -112,50 +63,4 @@ public class TagAPI implements Listener {
forWhom.forEach(playerFor -> refreshPlayer(player, playerFor));
}
private static WrappedGameProfile getSentName(int sentEntityId, WrappedGameProfile sent, Player destinationPlayer) {
Preconditions.checkState(Bukkit.getServer().isPrimaryThread(), "Can only process events on main thread.");
Player namedPlayer = entityIdMap.get(sentEntityId);
if (namedPlayer == null) {
// They probably were dead when we reloaded
return sent;
}
PlayerReceiveNameTagEvent oldEvent = new PlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, sent.getName());
Bukkit.getServer().getPluginManager().callEvent(oldEvent);
StringBuilder builtUUID = new StringBuilder();
if (!sent.getId().contains("-")) {
IntStream.range(0, uuidSplit.length - 1).forEach(i -> builtUUID.append(sent.getId(), uuidSplit[i], uuidSplit[i + 1]).append("-"));
} else {
builtUUID.append(sent.getId());
}
AsyncPlayerReceiveNameTagEvent newEvent = new AsyncPlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, getPlayerDisplayName(namedPlayer), UUID.fromString(builtUUID.toString()));
Bukkit.getServer().getPluginManager().callEvent(newEvent);
updatePlayerTag(namedPlayer, newEvent);
return new WrappedGameProfile(newEvent.getUUID(), newEvent.getTag().substring(0, Math.min(newEvent.getTag().length(), 16)));
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
entityIdMap.put(event.getPlayer().getEntityId(), event.getPlayer());
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
entityIdMap.remove(event.getPlayer().getEntityId());
}
private static void updatePlayerTag(Player namedPlayer, AsyncPlayerReceiveNameTagEvent newEvent) {
TagManager.PlayerData playerData = TagManager.getInst().getPlayerData(namedPlayer);
if (playerData.isEmpty()) {
return;
}
TagManager.getInst().unloadData(namedPlayer);
playerData.setName(newEvent.getTag());
TagManager.getInst().uploadData(namedPlayer);
}
}

View File

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

View File

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

View File

@ -1,11 +1,13 @@
package me.skymc.taboolib.update;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.fileutils.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
/**
@ -14,11 +16,17 @@ import org.bukkit.scheduler.BukkitRunnable;
*/
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() {
new BukkitRunnable() {
@ -27,14 +35,31 @@ public class UpdateTask {
if (!Main.getInst().getConfig().getBoolean("UPDATE-CHECK")) {
return;
}
String value = FileUtils.getStringFromURL(API, "{}");
JsonObject json = new JsonParser().parse(value).getAsJsonObject();
if (json.entrySet().size() > 0) {
double newVersion = Double.parseDouble(json.get("tag_name").getAsString());
String value = FileUtils.getStringFromURL("https://api.github.com/repos/Bkm016/TabooLib/tags", null);
if (value == null) {
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) {
TLocale.Logger.info("UPDATETASK.VERSION-LATEST");
} else {
haveUpdate = true;
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
# 是否启用离线模式
# 离线模式下将不会下载依赖
OFFLINE-MODE: false
# 网络连接测试地址
TEST-URL: 'aliyun.com'
# 下载依赖时启用的线程数
DOWNLOAD-POOL-SIZE: 4
@ -34,10 +33,17 @@ LOCALE:
# 关闭可提升性能
# 如果需要开启仍然可以在语言文件中加入 papi: true
USE_PAPI: false
# 玩家列表TAB是否根据前缀排序
# 启用后将会导致部分通过计分板获取玩家数据的插件出错BedwarsRel、SkyWars
TABLIST-SORT: false
# 是否启用更新检测
UPDATE-CHECK: true
# 是否启用自动更新
UPDATE-DOWNLOAD: false
# 是否在关闭服务器时清理玩家数据
# 该配置将在启用数据库储存时失效
DELETE-DATA: false

View File

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

View File

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