This commit is contained in:
坏黑 2018-04-26 18:21:06 +08:00
parent 4f16196170
commit 381d96c5b1
9 changed files with 1 additions and 705 deletions

View File

@ -1,40 +0,0 @@
package com.ilummc.tlib.compat;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public abstract class PlaceholderApiHook {
private static PlaceholderApiHook impl;
public static void init() {
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null)
impl = new PlaceholderImpl();
else impl = new AbstractImpl();
}
public static String replace(CommandSender sender, String text) {
return sender instanceof Player ? impl.replace(((Player) sender), text) : text;
}
abstract String replace(Player player, String text);
private static class PlaceholderImpl extends PlaceholderApiHook {
@Override
String replace(Player player, String text) {
return PlaceholderAPI.setPlaceholders(player, text);
}
}
private static class AbstractImpl extends PlaceholderApiHook {
@Override
String replace(Player player, String text) {
return text;
}
}
}

View File

@ -1,168 +0,0 @@
package com.ilummc.tlib.inject;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.annotations.*;
import com.ilummc.tlib.dependency.TDependency;
import com.ilummc.tlib.resources.LocaleLoader;
import com.ilummc.tlib.util.Ref;
import com.ilummc.tlib.util.TLogger;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.lang.reflect.Field;
public class DependencyInjector {
public static void inject(Plugin plugin, Object o) {
injectDependencies(plugin, o);
injectLogger(plugin, o);
injectConfig(plugin, o);
injectPluginInstance(plugin, o);
LocaleLoader.load(plugin, true);
}
static void injectOnEnable(Plugin plugin) {
inject(plugin, plugin);
}
static void onDisable(Plugin plugin) {
eject(plugin, plugin);
}
public static void eject(Plugin plugin, Object o) {
try {
ejectConfig(plugin, o);
} catch (Throwable ignored) {
}
}
private static void ejectConfig(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
Config config;
if ((config = field.getType().getAnnotation(Config.class)) != null && config.saveOnExit()) {
try {
field.setAccessible(true);
TConfigInjector.saveConfig(plugin, field.get(o));
TLib.getTLib().getLogger().info("插件 " + plugin + " 的配置 " + config.name() + " 已保存");
} catch (Exception e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置 " + config.name() + " 保存失败");
e.printStackTrace();
}
}
}
}
private static void injectConfig(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
try {
Config config;
if ((config = field.getType().getAnnotation(Config.class)) != null) {
field.setAccessible(true);
Object obj = TConfigInjector.loadConfig(plugin, field.getType());
if (obj != null) {
TLib.getTLib().getLogger().info("插件 " + plugin.getName() + "" + config.name() + " 配置文件成功加载");
field.set(o, obj);
if (config.listenChanges()) {
TLib.getTLib().getLogger().info("开始监听插件 " + plugin.getName() + "" + config.name() + " 配置文件");
TLib.getTLib().getConfigWatcher().addOnListen(
new File(plugin.getDataFolder(), config.name()),
obj,
object -> {
try {
Object newObj = TConfigInjector.loadConfig(plugin, object.getClass());
for (Field f : newObj.getClass().getDeclaredFields()) {
f.setAccessible(true);
f.set(obj, f.get(newObj));
}
TLib.getTLib().getLogger().info("插件 " + plugin.getName() + "" + config.name() + " 配置文件成功重载");
} catch (Exception ignored) {
TLib.getTLib().getLogger().warn("插件 " + plugin.getName() + "" + config.name() + " 配置文件重载时发生错误");
}
}
);
}
}
}
} catch (Exception ignored) {
}
}
}
private static void injectLogger(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
try {
Logger logger;
if ((logger = field.getAnnotation(Logger.class)) != null) {
field.getType().asSubclass(TLogger.class);
TLogger tLogger = new TLogger(logger.value(), plugin, logger.level());
if (!field.isAccessible())
field.setAccessible(true);
field.set(o, tLogger);
}
} catch (Exception ignored2) {
}
}
}
private static void injectPluginInstance(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
try {
PluginInstance instance;
if ((instance = field.getAnnotation(PluginInstance.class)) != null) {
if (!field.isAccessible())
field.setAccessible(true);
field.getType().asSubclass(JavaPlugin.class);
Plugin pl;
if ((pl = Bukkit.getPluginManager().getPlugin(instance.value())) == null) {
if (!TDependency.requestPlugin(instance.value())) {
TLib.getTLib().getLogger().warn(plugin.getName() + " 所需的依赖插件 " + instance.value() + " 自动加载失败");
return;
} else {
pl = Bukkit.getPluginManager().getPlugin(instance.value());
}
}
if (pl != null)
field.set(o, pl);
}
} catch (Exception ignored) {
}
}
}
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};
}
}
if (dependencies.length != 0) {
TLib.getTLib().getLogger().info("正在加载 " + plugin.getName() + " 插件所需的依赖");
for (Dependency dependency : dependencies) {
if (dependency.type() == Dependency.Type.PLUGIN) {
if (TDependency.requestPlugin(dependency.plugin())) {
TLib.getTLib().getLogger().info(" " + plugin.getName() + " 请求的插件 " + dependency.plugin() + " 加载成功。");
} else {
TLib.getTLib().getLogger().warn(" " + plugin.getName() + " 请求的插件 " + dependency.plugin() + " 加载失败。");
}
}
if (dependency.type() == Dependency.Type.LIBRARY) {
if (TDependency.requestLib(dependency.maven(), dependency.mavenRepo(), dependency.url())) {
TLib.getTLib().getLogger().info(" " + plugin.getName() + " 请求的库文件 " + String.join(":", dependency.maven()) + " 加载成功。");
} else {
TLib.getTLib().getLogger().warn(" " + plugin.getName() + " 请求的库文件 " + String.join(":", dependency.maven()) + " 加载失败。");
}
}
}
TLib.getTLib().getLogger().info("依赖加载完成");
}
}
}

View File

@ -1,174 +0,0 @@
package com.ilummc.tlib.inject;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.permissions.Permissible;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.*;
import java.io.File;
import java.util.Set;
public class TLibPluginManager implements PluginManager {
private final PluginManager instance;
private final Main main = (Main) Main.getInst();
public TLibPluginManager() {
instance = Bukkit.getPluginManager();
}
@Override
public void registerInterface(Class<? extends PluginLoader> aClass) throws IllegalArgumentException {
instance.registerInterface(aClass);
}
@Override
public Plugin getPlugin(String s) {
return instance.getPlugin(s);
}
@Override
public Plugin[] getPlugins() {
return instance.getPlugins();
}
@Override
public boolean isPluginEnabled(String s) {
return instance.isPluginEnabled(s);
}
@Override
public boolean isPluginEnabled(Plugin plugin) {
return instance.isPluginEnabled(plugin);
}
@Override
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
return instance.loadPlugin(file);
}
@Override
public Plugin[] loadPlugins(File file) {
return instance.loadPlugins(file);
}
@Override
public void disablePlugins() {
for (Plugin plugin : getPlugins()) {
if (plugin != main) disablePlugin(plugin);
}
disablePlugin(main);
}
@Override
public void clearPlugins() {
instance.clearPlugins();
}
@Override
public void callEvent(Event event) throws IllegalStateException {
instance.callEvent(event);
}
@Override
public void registerEvents(Listener listener, Plugin plugin) {
instance.registerEvents(listener, plugin);
}
@Override
public void registerEvent(Class<? extends Event> aClass, Listener listener, EventPriority eventPriority, EventExecutor eventExecutor, Plugin plugin) {
instance.registerEvent(aClass, listener, eventPriority, eventExecutor, plugin);
}
@Override
public void registerEvent(Class<? extends Event> aClass, Listener listener, EventPriority eventPriority, EventExecutor eventExecutor, Plugin plugin, boolean b) {
instance.registerEvent(aClass, listener, eventPriority, eventExecutor, plugin, b);
}
@Override
public void enablePlugin(Plugin plugin) {
DependencyInjector.injectOnEnable(plugin);
instance.enablePlugin(plugin);
}
@Override
public void disablePlugin(Plugin plugin) {
DependencyInjector.onDisable(plugin);
instance.disablePlugin(plugin);
}
@Override
public Permission getPermission(String s) {
return instance.getPermission(s);
}
@Override
public void addPermission(Permission permission) {
instance.addPermission(permission);
}
@Override
public void removePermission(Permission permission) {
instance.removePermission(permission);
}
@Override
public void removePermission(String s) {
instance.removePermission(s);
}
@Override
public Set<Permission> getDefaultPermissions(boolean b) {
return instance.getDefaultPermissions(b);
}
@Override
public void recalculatePermissionDefaults(Permission permission) {
instance.recalculatePermissionDefaults(permission);
}
@Override
public void subscribeToPermission(String s, Permissible permissible) {
instance.subscribeToPermission(s, permissible);
}
@Override
public void unsubscribeFromPermission(String s, Permissible permissible) {
instance.unsubscribeFromPermission(s, permissible);
}
@Override
public Set<Permissible> getPermissionSubscriptions(String s) {
return instance.getPermissionSubscriptions(s);
}
@Override
public void subscribeToDefaultPerms(boolean b, Permissible permissible) {
instance.subscribeToDefaultPerms(b, permissible);
}
@Override
public void unsubscribeFromDefaultPerms(boolean b, Permissible permissible) {
instance.unsubscribeFromDefaultPerms(b, permissible);
}
@Override
public Set<Permissible> getDefaultPermSubscriptions(boolean b) {
return instance.getDefaultPermSubscriptions(b);
}
@Override
public Set<Permission> getPermissions() {
return instance.getPermissions();
}
@Override
public boolean useTimings() {
return instance.useTimings();
}
}

View File

@ -1,65 +0,0 @@
package com.ilummc.tlib.resources;
import com.google.common.collect.ImmutableList;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import javax.annotation.concurrent.ThreadSafe;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
@ThreadSafe
class LocaleInstance {
private static final Function<Object, Sendable> TO_SENDABLE = o -> {
if (o instanceof Sendable) return ((Sendable) o);
else if (o instanceof String) return SimpleChatMessage.of(((String) o));
else return SimpleChatMessage.of(String.valueOf(o));
};
LocaleInstance() {
}
private final Map<String, List<Sendable>> map = new ConcurrentHashMap<>();
void sendTo(String path, CommandSender sender) {
map.getOrDefault(path, ImmutableList.of(Sendable.EMPTY)).forEach(sendable -> sendable.sendTo(sender));
}
void sendTo(String path, CommandSender sender, String... args) {
map.getOrDefault(path, ImmutableList.of(Sendable.EMPTY)).forEach(sendable -> sendable.sendTo(sender, args));
System.out.println(map.toString());
}
void load(YamlConfiguration configuration) {
configuration.getKeys(false).forEach(s -> {
Object object = configuration.get(s);
if (object instanceof ConfigurationSection)
loadRecursively(s, (ConfigurationSection) object);
else if (object instanceof Sendable)
map.put(s, Collections.singletonList((Sendable) object));
else if (object instanceof List && !((List) object).isEmpty())
map.put(s, ((List<?>) object).stream().map(TO_SENDABLE).collect(Collectors.toList()));
else map.put(s, Collections.singletonList(SimpleChatMessage.of(String.valueOf(object))));
});
}
private void loadRecursively(String path, ConfigurationSection section) {
section.getKeys(false).forEach(s -> {
Object object = section.get(path + "." + s);
if (object instanceof ConfigurationSection)
loadRecursively(path + "." + s, (ConfigurationSection) object);
else if (object instanceof Sendable)
map.put(path + "." + s, Collections.singletonList((Sendable) object));
else if (object instanceof List && !((List) object).isEmpty())
map.put(path + "." + s, ((List<?>) object).stream().map(TO_SENDABLE).collect(Collectors.toList()));
else map.put(path + "." + s, Collections.singletonList(SimpleChatMessage.of(String.valueOf(object))));
});
}
}

View File

@ -1,76 +0,0 @@
package com.ilummc.tlib.resources;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.inject.TConfigInjector;
import me.skymc.taboolib.Main;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class LocaleLoader {
private static final Map<String, LocaleInstance> map = new HashMap<>();
static void sendTo(Plugin plugin, String path, CommandSender sender, String... args) {
Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args));
}
static void sendTo(Plugin plugin, String path, CommandSender sender) {
Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender));
}
public static void init() {
ConfigurationSerialization.registerClass(SimpleChatMessage.class);
ConfigurationSerialization.registerClass(SimpleChatMessage.class, "Message");
ConfigurationSerialization.registerClass(SimpleChatMessage.class, "MESSAGE");
ConfigurationSerialization.registerClass(SimpleChatMessage.class, "TEXT");
ConfigurationSerialization.registerClass(SimpleChatMessage.class, "Text");
}
public static void load(Plugin plugin, boolean ignoreLoaded) {
try {
if ((!ignoreLoaded || !map.containsKey(plugin.getName())) && plugin == Main.getInst() ||
plugin.getDescription().getDepend().contains("TabooLib") || plugin.getDescription().getSoftDepend().contains("TabooLib")) {
InputStream inputStream = null;
File file = null;
String lang = null;
for (String s : TLib.getTLib().getConfig().getLocale()) {
lang = s;
file = new File(plugin.getDataFolder(), "/lang/" + s + ".yml");
if (file.exists()) {
inputStream = Files.newInputStream(file.toPath(), StandardOpenOption.READ);
break;
} else if ((inputStream = plugin.getClass().getResourceAsStream("/lang/" + s + ".yml")) != null)
break;
}
if (inputStream == null) return;
TLib.getTLib().getLogger().info("尝试加载 " + lang + ".yml 作为语言文件");
YamlConfiguration configuration = YamlConfiguration.loadConfiguration(new InputStreamReader(inputStream, Charset.forName("utf-8")));
LocaleInstance localeInstance = new LocaleInstance();
localeInstance.load(configuration);
map.put(plugin.getName(), localeInstance);
TConfigInjector.fixUnicode(configuration);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
configuration.save(file);
TLib.getTLib().getLogger().info("成功加载 " + lang + " 语言文件");
}
} catch (Exception e) {
TLib.getTLib().getLogger().error("载入语言文件发生异常:" + e.toString());
}
}
}

View File

@ -1,21 +0,0 @@
package com.ilummc.tlib.resources;
import org.bukkit.command.CommandSender;
public interface Sendable {
Sendable EMPTY = new Sendable() {
@Override
public void sendTo(CommandSender sender) {
}
@Override
public void sendTo(CommandSender sender, String... args) {
}
};
void sendTo(CommandSender sender);
void sendTo(CommandSender sender, String... args);
}

View File

@ -1,95 +0,0 @@
package com.ilummc.tlib.resources;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.compat.PlaceholderApiHook;
import com.ilummc.tlib.util.Strings;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import javax.annotation.concurrent.Immutable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
@Immutable
@SerializableAs("TEXT")
@SuppressWarnings("unchecked")
public class SimpleChatMessage implements Sendable, ConfigurationSerializable {
private final Object text;
private final boolean usePlaceholder;
private SimpleChatMessage(Object text, boolean usePlaceholder) {
this.usePlaceholder = usePlaceholder;
if (text instanceof String)
this.text = text;
else if (text instanceof List)
this.text = ImmutableList.copyOf(((List) text));
else
throw new IllegalArgumentException("Param 'text' can only be an instance of String or String[] or List<String>");
}
@Override
public void sendTo(CommandSender sender) {
if (text instanceof String)
sender.sendMessage(replaceMsg(sender, (String) text));
else if (text instanceof List)
((List) text).forEach(s -> sender.sendMessage(replaceMsg(sender, String.valueOf(s))));
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (text instanceof String)
sender.sendMessage(replaceMsg(sender, Strings.replaceWithOrder((String) text, args)));
else if (text instanceof List)
((List) text).forEach(s -> sender.sendMessage(replaceMsg(sender, Strings.replaceWithOrder(String.valueOf(s), args))));
}
private String replaceMsg(CommandSender sender, String s) {
return usePlaceholder ? PlaceholderApiHook.replace(sender, s) : s;
}
@Override
public String toString() {
if (text instanceof String[]) return Arrays.toString((String[]) text);
else return text.toString();
}
@Override
public Map<String, Object> serialize() {
if (usePlaceholder) return Maps.newHashMap(ImmutableMap.of("text", text, "papi", true));
return Maps.newHashMap(ImmutableMap.of("text", text));
}
public static SimpleChatMessage valueOf(Map<String, Object> map) {
if (map.containsKey("text")) {
Object object = map.get("text");
Object objPapi = map.getOrDefault("papi", TLib.getTLib().getConfig().isEnablePapiByDefault());
boolean papi = objPapi instanceof Boolean ? (boolean) objPapi : objPapi instanceof String && objPapi.equals("true");
if (object instanceof List)
return new SimpleChatMessage(((List<String>) object).stream()
.map(s -> ChatColor.translateAlternateColorCodes('&', s))
.collect(Collectors.toList()), papi);
else if (object instanceof String[])
return new SimpleChatMessage(Arrays.stream(((String[]) object))
.map(s -> ChatColor.translateAlternateColorCodes('&', s))
.collect(Collectors.toList()), papi);
else
return new SimpleChatMessage(ChatColor.translateAlternateColorCodes('&', Objects.toString(object)), papi);
}
return new SimpleChatMessage("§cError chat message loaded.", TLib.getTLib().getConfig().isEnablePapiByDefault());
}
public static SimpleChatMessage of(String s) {
return new SimpleChatMessage(ChatColor.translateAlternateColorCodes('&', s), TLib.getTLib().getConfig().isEnablePapiByDefault());
}
}

View File

@ -38,7 +38,7 @@ public class TLocaleLoader {
}
static String asString(Plugin plugin, String path) {
return Optional.ofNullable(map.get(plugin.getName())).get().asString(path);
return map.get(plugin.getName()).asString(path);
}
public static void init() {

View File

@ -1,65 +0,0 @@
package com.ilummc.tlib.util;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.Plugin;
import lombok.Getter;
import lombok.Setter;
public class TLogger {
public static final int VERBOSE = 0, FINEST = 1, FINE = 2, INFO = 3, WARN = 4, ERROR = 5, FATAL = 6;
@Getter
private final String pattern;
@Getter
private Plugin plugin;
@Getter
@Setter
private int level;
public TLogger(String pattern, Plugin plugin, int level) {
this.pattern = pattern;
this.plugin = plugin;
this.level = level;
}
public void verbose(String msg) {
if (level <= VERBOSE)
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§f全部", ChatColor.translateAlternateColorCodes('&', msg)));
}
public void finest(String msg) {
if (level <= FINEST)
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§e良好", ChatColor.translateAlternateColorCodes('&', msg)));
}
public void fine(String msg) {
if (level <= FINE)
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§a正常", ChatColor.translateAlternateColorCodes('&', msg)));
}
public void info(String msg) {
if (level <= INFO)
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§b信息", ChatColor.translateAlternateColorCodes('&', msg)));
}
public void warn(String msg) {
if (level <= WARN)
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§6警告", "§6" + ChatColor.translateAlternateColorCodes('&', msg)));
}
public void error(String msg) {
if (level <= ERROR)
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§c错误", "§c" + ChatColor.translateAlternateColorCodes('&', msg)));
}
public void fatal(String msg) {
if (level <= FATAL)
Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§4致命错误", "§4" + ChatColor.translateAlternateColorCodes('&', msg)));
}
}