好像没上传干净

This commit is contained in:
坏黑 2018-05-07 23:58:32 +08:00
parent 8c6518ffc5
commit 674e993105
35 changed files with 1603 additions and 1122 deletions

View File

@ -1,5 +1,8 @@
<component name="InspectionProjectProfileManager"> <component name="InspectionProjectProfileManager">
<settings> <settings>
<option name="PROJECT_PROFILE" value="TabooLib Inspections" />
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
<info color="525229"> <info color="525229">
<option name="EFFECT_COLOR" value="659c6b" /> <option name="EFFECT_COLOR" value="659c6b" />
<option name="EFFECT_TYPE" value="2" /> <option name="EFFECT_TYPE" value="2" />

View File

@ -12,6 +12,13 @@
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:3.1.0" level="project" /> <orderEntry type="library" name="Maven: com.zaxxer:HikariCP:3.1.0" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" /> <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" />
<orderEntry type="library" name="Maven: org.javalite:activejdbc:2.0" level="project" />
<orderEntry type="library" name="Maven: org.javalite:javalite-common:2.0" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.jackson:jackson-core-asl:1.9.13" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.jackson:jackson-mapper-asl:1.9.13" level="project" />
<orderEntry type="library" name="Maven: org.javalite:app-config:2.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:servlet-api:2.5" level="project" />
<orderEntry type="library" name="Maven: com.h2database:h2:1.4.197" level="project" />
<orderEntry type="library" name="Maven: com.ilummc.eagletdl:EagletCore:1.1.2" level="project" /> <orderEntry type="library" name="Maven: com.ilummc.eagletdl:EagletCore:1.1.2" level="project" />
<orderEntry type="library" name="Maven: org.ow2.asm:asm:6.1.1" level="project" /> <orderEntry type="library" name="Maven: org.ow2.asm:asm:6.1.1" level="project" />
<orderEntry type="module-library"> <orderEntry type="module-library">

View File

@ -24,7 +24,7 @@ import java.nio.charset.Charset;
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.ow2.asm:asm:6.1.1") @Dependency(type = Dependency.Type.LIBRARY, maven = "org.ow2.asm:asm:6.1.1")
@Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0") @Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25") @Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-internal:1.7.25")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:activejdbc:2.0") @Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:activejdbc:2.0")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:javalite-common:2.0") @Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:javalite-common:2.0")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:app-config:2.0") @Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:app-config:2.0")
@ -74,19 +74,21 @@ public class TLib {
TLocaleLoader.load(Main.getInst(), false); TLocaleLoader.load(Main.getInst(), false);
TDependencyInjector.inject(Main.getInst(), tLib); TDependencyInjector.inject(Main.getInst(), tLib);
// init database
try { try {
Pool.init(); Pool.init();
} catch (Throwable e) { } catch (Throwable ignored) {
e.printStackTrace();
} }
} }
public static void unload() { public static void unload() {
Pool.unload();
tLib.getConfigWatcher().unregisterAll(); tLib.getConfigWatcher().unregisterAll();
TDependencyInjector.eject(Main.getInst(), tLib); TDependencyInjector.eject(Main.getInst(), tLib);
try {
Pool.unload();
} catch (Throwable ignored) {
}
} }
public static void injectPluginManager() { public static void injectPluginManager() {

View File

@ -2,6 +2,9 @@ package com.ilummc.tlib.config;
import com.ilummc.tlib.annotations.TConfig; import com.ilummc.tlib.annotations.TConfig;
import java.util.HashMap;
import java.util.Map;
/** /**
* @author sky * @author sky
* @since 2018-04-22 14:31:11 * @since 2018-04-22 14:31:11
@ -9,28 +12,48 @@ import com.ilummc.tlib.annotations.TConfig;
@TConfig(name = "tlib.yml", listenChanges = true) @TConfig(name = "tlib.yml", listenChanges = true)
public class TLibConfig { public class TLibConfig {
@Getter
private String dataSourceClassName; private String dataSourceClassName;
@Getter
private String jdbcUrl = "jdbc:h2:file:~/plugins/TabooLib/h2"; private String jdbcUrl = "jdbc:h2:file:~/plugins/TabooLib/h2";
@Getter
private String driverClassName; private String driverClassName;
@Getter
private String username = ""; private String username = "";
@Getter
private String password = ""; private String password = "";
@Getter
private int maximumPoolSize = 4; private int maximumPoolSize = 4;
@Getter
private Map<String, Object> settings = new HashMap<String, Object>() {{ private Map<String, Object> settings = new HashMap<String, Object>() {{
put("cachePrepStmts", true); put("cachePrepStmts", true);
put("useServerPrepStmts", true); put("useServerPrepStmts", true);
}}; }};
public String getDataSourceClassName() {
return dataSourceClassName;
}
public String getJdbcUrl() {
return jdbcUrl;
}
public String getDriverClassName() {
return driverClassName;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public int getMaximumPoolSize() {
return maximumPoolSize;
}
public Map<String, Object> getSettings() {
return settings;
}
} }

View File

@ -4,8 +4,10 @@ import com.ilummc.tlib.TLib;
import me.skymc.taboolib.anvil.AnvilContainerAPI; import me.skymc.taboolib.anvil.AnvilContainerAPI;
import me.skymc.taboolib.bstats.Metrics; import me.skymc.taboolib.bstats.Metrics;
import me.skymc.taboolib.commands.MainCommands; import me.skymc.taboolib.commands.MainCommands;
import me.skymc.taboolib.commands.internal.InternalCommandExecutor;
import me.skymc.taboolib.commands.language.Language2Command; import me.skymc.taboolib.commands.language.Language2Command;
import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand; import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand;
import me.skymc.taboolib.commands.plugin.TabooLibPluginCommand;
import me.skymc.taboolib.commands.sub.itemlist.listener.ItemLibraryPatch; import me.skymc.taboolib.commands.sub.itemlist.listener.ItemLibraryPatch;
import me.skymc.taboolib.commands.sub.sounds.listener.SoundsLibraryPatch; import me.skymc.taboolib.commands.sub.sounds.listener.SoundsLibraryPatch;
import me.skymc.taboolib.database.GlobalDataManager; import me.skymc.taboolib.database.GlobalDataManager;
@ -203,6 +205,7 @@ public class Main extends JavaPlugin implements Listener {
getCommand("language2").setExecutor(new Language2Command()); getCommand("language2").setExecutor(new Language2Command());
getCommand("taboolibrarymodule").setExecutor(new TLMCommands()); getCommand("taboolibrarymodule").setExecutor(new TLMCommands());
getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand()); getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand());
InternalCommandExecutor.createCommandExecutor("taboolibplugin", new TabooLibPluginCommand());
// 注册监听 // 注册监听
registerListener(); registerListener();

View File

@ -0,0 +1,28 @@
package me.skymc.taboolib.commands.internal;
/**
* @author Bkm016
* @since 2018-04-17
*/
public class InternalArgument {
private String name;
private boolean required;
public String getName() {
return name;
}
public boolean isRequired() {
return required;
}
public InternalArgument(String name, boolean required) {
this.name = name;
this.required = required;
}
public String toString() {
return required ? "§7[§8" + name + "§7]" : "§7<§8" + name + "§7>";
}
}

View File

@ -4,6 +4,8 @@ package me.skymc.taboolib.commands.internal;
* @Author sky * @Author sky
* @Since 2018-05-07 21:36 * @Since 2018-05-07 21:36
*/ */
public class InternalMainCommand { public interface InternalCommand {
String getCommandTitle();
} }

View File

@ -1,9 +1,111 @@
package me.skymc.taboolib.commands.internal; package me.skymc.taboolib.commands.internal;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.string.ArrayUtils;
import me.skymc.taboolib.string.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.*;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/** /**
* @Author sky * @Author sky
* @Since 2018-05-07 21:38 * @Since 2018-05-07 21:38
*/ */
public class InternalCommandExecutor { public abstract class InternalCommandExecutor implements InternalCommand, CommandExecutor, TabExecutor {
private InternalCommandExecutor subExecutor;
private List<InternalSubCommandExecutor> subCommandExecutors = new ArrayList<>();
public static InternalCommandExecutor createCommandExecutor(String command, InternalCommandExecutor internalCommandExecutor) {
assert Bukkit.getPluginCommand(command) == null : "PluginCommand \"" + command + "\"not found";
assert internalCommandExecutor != null : "Executor can not be null";
assert internalCommandExecutor.getCommandTitle() != null : "Executor title can not be null";
assert internalCommandExecutor.getClass() != InternalCommandExecutor.class : "SubExecutor can not be \"InternalCommandExecutor.class\"";
internalCommandExecutor.setSubExecutor(internalCommandExecutor);
Bukkit.getPluginCommand(command).setExecutor(internalCommandExecutor);
Bukkit.getPluginCommand(command).setTabCompleter(internalCommandExecutor);
return internalCommandExecutor;
}
public void setSubExecutor(InternalCommandExecutor subExecutor) {
this.subExecutor = subExecutor;
}
public InternalCommandExecutor getSubExecutor() {
return subExecutor;
}
public List<InternalSubCommandExecutor> getSubCommandExecutors() {
return subCommandExecutors;
}
public void registerSubCommandExecutor(InternalSubCommandExecutor subCommandExecutor) {
assert subCommandExecutor.getLabel() != null : "Command label can not be null";
assert subCommandExecutor.getDescription() != null : "Command description can not be null";
assert subCommandExecutor.getArguments() != null : "Command arguments can not be null";
subCommandExecutors.add(subCommandExecutor);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
helpCommand(sender, label);
} else {
for (InternalSubCommandExecutor subCommand : subCommandExecutors) {
if (subCommand == null || !args[0].equalsIgnoreCase(subCommand.getLabel())) {
continue;
}
if (!isConfirmType(sender, subCommand.getType())) {
TLocale.sendTo(sender, "COMMANDS.INTERNAL.ONLY-PLAYER", args[0], TLocale.asString("COMMANDS.INTERNAL.TYPE-" + subCommand.getType()));
return true;
}
String[] subCommandArgs = ArrayUtils.removeFirst(args);
if (subCommand.isParameterConform(subCommandArgs)) {
subCommand.onCommand(sender, command, label, subCommandArgs);
} else {
TLocale.sendTo(sender, "COMMANDS.INTERNAL.ERROR-USAGE", args[0], subCommand.getCommandString(label));
}
return true;
}
new BukkitRunnable() {
@Override
public void run() {
List<InternalSubCommandExecutor> commandCompute = subCommandExecutors.stream().filter(Objects::nonNull).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());
}
}
}.runTaskAsynchronously(Main.getInst());
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) {
return args.length == 1 ? subCommandExecutors.stream().filter(internalCommandExecutor -> internalCommandExecutor != null && (args[0].isEmpty() || internalCommandExecutor.getLabel().startsWith(args[0]))).map(InternalSubCommand::getLabel).collect(Collectors.toList()) : null;
}
private String getEmptyLine() {
return TabooLib.getVerint() < 10800 ? "~" : "";
}
private void helpCommand(CommandSender sender, String label) {
sender.sendMessage(getEmptyLine());
sender.sendMessage(subExecutor.getCommandTitle());
sender.sendMessage(getEmptyLine());
subCommandExecutors.stream().map(subCommand -> subCommand == null ? getEmptyLine() : subCommand.getCommandString(label)).forEach(sender::sendMessage);
sender.sendMessage(getEmptyLine());
}
private boolean isConfirmType(CommandSender sender, InternalSubCommandType commandType) {
return commandType == InternalSubCommandType.ALL || sender instanceof ConsoleCommandSender && commandType == InternalSubCommandType.CONSOLE;
}
} }

View File

@ -7,14 +7,14 @@ import org.bukkit.command.CommandSender;
* @author Bkm016 * @author Bkm016
* @since 2018-04-17 * @since 2018-04-17
*/ */
public interface InternalCommand { public interface InternalSubCommand {
String getLabel(); String getLabel();
String getDescription(); String getDescription();
InternalCommandArgument[] getArguments(); InternalArgument[] getArguments();
void onCommand(CommandSender sender, Command command, String label, String[] args); void onCommand(CommandSender sender, Command command, String label, String[] args);
} }

View File

@ -1,20 +1,15 @@
package me.skymc.taboolib.commands.internal; package me.skymc.taboolib.commands.internal;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
/** /**
* @author Bkm016 * @author Bkm016
* @since 2018-04-17 * @since 2018-04-17
*/ */
public abstract class InternalCommandExecutor implements InternalCommand { public abstract class InternalSubCommandExecutor implements InternalSubCommand {
public InternalCommandType getType() { public InternalSubCommandType getType() {
return InternalCommandType.ALL; return InternalSubCommandType.ALL;
} }
public boolean requiredPlayer() { public boolean requiredPlayer() {
@ -25,22 +20,14 @@ public abstract class InternalCommandExecutor implements InternalCommand {
return IntStream.range(0, getArguments().length).noneMatch(i -> getArguments()[i].isRequired() && (args == null || args.length <= i)); return IntStream.range(0, getArguments().length).noneMatch(i -> getArguments()[i].isRequired() && (args == null || args.length <= i));
} }
public boolean isConfirmType(CommandSender sender, InternalCommandType commandType) {
return commandType == InternalCommandType.ALL || sender instanceof ConsoleCommandSender && commandType == InternalCommandType.CONSOLE;
}
public List<String> getTabCompleter(List<InternalCommandExecutor> internalCommandExecutors, String[] args) {
return args.length == 1 ? internalCommandExecutors.stream().filter(internalCommandExecutor -> internalCommandExecutor != null && (args[0].isEmpty() || internalCommandExecutor.getLabel().startsWith(args[0]))).map(InternalCommand::getLabel).collect(Collectors.toList()) : null;
}
public String getCommandString(String label) { public String getCommandString(String label) {
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("§f /"); stringBuilder.append(" §f/");
stringBuilder.append(label); stringBuilder.append(label);
stringBuilder.append(" "); stringBuilder.append(" ");
stringBuilder.append(getLabel()); stringBuilder.append(getLabel());
stringBuilder.append(" "); stringBuilder.append(" ");
for (InternalCommandArgument parameter : getArguments()) { for (InternalArgument parameter : getArguments()) {
stringBuilder.append(parameter.toString()); stringBuilder.append(parameter.toString());
stringBuilder.append(" "); stringBuilder.append(" ");
} }

View File

@ -4,7 +4,7 @@ package me.skymc.taboolib.commands.internal;
* @author Bkm016 * @author Bkm016
* @since 2018-04-17 * @since 2018-04-17
*/ */
public enum InternalCommandType { public enum InternalSubCommandType {
CONSOLE, PLAYER, ALL CONSOLE, PLAYER, ALL

View File

@ -1,9 +1,215 @@
package me.skymc.taboolib.commands.plugin; package me.skymc.taboolib.commands.plugin;
import com.google.common.base.Joiner;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.commands.internal.InternalArgument;
import me.skymc.taboolib.commands.internal.InternalCommandExecutor;
import me.skymc.taboolib.commands.internal.InternalSubCommandExecutor;
import me.skymc.taboolib.plugin.PluginUtils;
import me.skymc.taboolib.string.ArrayUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/** /**
* @Author sky * @Author sky
* @Since 2018-05-07 20:14 * @Since 2018-05-07 20:14
*/ */
public class TabooLibPluginCommand { public class TabooLibPluginCommand extends InternalCommandExecutor {
} public TabooLibPluginCommand() {
listCommand();
infoCommand();
loadCommand();
unloadCommand();
reloadCommand();
}
@Override
public String getCommandTitle() {
return TLocale.asString("COMMANDS.TPLUGIN.COMMAND-TITLE");
}
void loadCommand() {
registerSubCommandExecutor(new InternalSubCommandExecutor() {
@Override
public String getLabel() {
return "load";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.LOAD.DESCRIPTION");
}
@Override
public InternalArgument[] getArguments() {
return new InternalArgument[]{new InternalArgument(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-FALL", name);
}
}
}
}
});
}
void unloadCommand() {
registerSubCommandExecutor(new InternalSubCommandExecutor() {
@Override
public String getLabel() {
return "unload";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.DESCRIPTION");
}
@Override
public InternalArgument[] getArguments() {
return new InternalArgument[]{new InternalArgument(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-FALL", name);
}
}
}
}
});
}
void reloadCommand() {
registerSubCommandExecutor(new InternalSubCommandExecutor() {
@Override
public String getLabel() {
return "reload";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.RELOAD.DESCRIPTION");
}
@Override
public InternalArgument[] getArguments() {
return new InternalArgument[]{new InternalArgument(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 {
PluginUtils.reload(plugin);
}
}
});
}
void infoCommand() {
registerSubCommandExecutor(new InternalSubCommandExecutor() {
@Override
public String getLabel() {
return "info";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.INFO.DESCRIPTION");
}
@Override
public InternalArgument[] getArguments() {
return new InternalArgument[]{new InternalArgument(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 {
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()));
}
}
});
}
void listCommand() {
registerSubCommandExecutor(new InternalSubCommandExecutor() {
@Override
public String getLabel() {
return "list";
}
@Override
public String getDescription() {
return TLocale.asString("COMMANDS.TPLUGIN.LIST.DESCRIPTION");
}
@Override
public InternalArgument[] getArguments() {
return new InternalArgument[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

@ -105,7 +105,7 @@ public class _164ItemUtils implements IDabItemUtils{
} }
} }
public Method gin = NMSUtils.getMethodSilent(ni, "getName"); public Method gin = NMSUtils.getMethodSilent(ni, "getLabel");
@Override @Override
public String getItemName(ItemStack is){ public String getItemName(ItemStack is){

View File

@ -105,7 +105,7 @@ public class _1710ItemUtils implements IDabItemUtils{
} }
} }
public Method gin = NMSUtils.getMethodSilent(ni, "getName"); public Method gin = NMSUtils.getMethodSilent(ni, "getLabel");
@Override @Override
public String getItemName(ItemStack is){ public String getItemName(ItemStack is){

View File

@ -71,7 +71,7 @@ public class _194ItemUtils implements IDabItemUtils{
public Class<?> ni = NMSUtils.getNMSClassSilent("Item"); public Class<?> ni = NMSUtils.getNMSClassSilent("Item");
public Method gn = NMSUtils.getMethodSilent(nmis, "getName"); public Method gn = NMSUtils.getMethodSilent(nmis, "getLabel");
@Override @Override
public String getName(ItemStack is){ public String getName(ItemStack is){
@ -108,7 +108,7 @@ public class _194ItemUtils implements IDabItemUtils{
} }
} }
public Method gin = NMSUtils.getMethodSilent(ni, "getName"); public Method gin = NMSUtils.getMethodSilent(ni, "getLabel");
@Override @Override
public String getItemName(ItemStack is){ public String getItemName(ItemStack is){

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib.playerdata; package me.skymc.taboolib.playerdata;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.database.PlayerDataManager; import me.skymc.taboolib.database.PlayerDataManager;
import me.skymc.taboolib.exception.PlayerOfflineException; import me.skymc.taboolib.exception.PlayerOfflineException;
@ -49,7 +50,7 @@ public class DataUtils implements Listener {
saveAllCaches(getFixedPlugin(plugin), remove); saveAllCaches(getFixedPlugin(plugin), remove);
} }
if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) { if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) {
MsgUtils.send("保存 &f" + DataUtils.CACHE_DATA_PLUGIN.size() + " &7条插件数据, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)"); TLocale.Logger.info("DATA-UTILS.SUCCESS-SAVE-DATA", String.valueOf(DataUtils.CACHE_DATA_PLUGIN.size()), String.valueOf(System.currentTimeMillis() - time));
} }
} }
@ -57,7 +58,7 @@ public class DataUtils implements Listener {
try { try {
conf.save(file); conf.save(file);
} catch (IOException e) { } catch (IOException e) {
MsgUtils.warn("文件 &4" + file.getName() + "&c 保存失败, 原因: &4" + e.getMessage()); TLocale.Logger.error("DATA-UTILS.FALL-SAVE-FILE", file.getName(), e.toString());
} }
} }

View File

@ -1,3 +1,8 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package me.skymc.taboolib.plugin; package me.skymc.taboolib.plugin;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
@ -18,53 +23,41 @@ import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PluginUtils { public class PluginUtils {
public static String consolidateStrings(final String[] args, final int start) { private PluginUtils() {
StringBuilder ret = new StringBuilder(args[start]);
if (args.length > start + 1) {
for (int i = start + 1; i < args.length; ++i) {
ret.append(" ").append(args[i]);
}
}
return ret.toString();
} }
public static void enable(final Plugin plugin) { public static void enable(Plugin plugin) {
if (plugin != null && !plugin.isEnabled()) { if (plugin != null && !plugin.isEnabled()) {
Bukkit.getPluginManager().enablePlugin(plugin); Bukkit.getPluginManager().enablePlugin(plugin);
} }
} }
public static void enableAll() { public static void disable(Plugin plugin) {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (!isIgnored(plugin)) {
enable(plugin);
}
}
}
public static void disable(final Plugin plugin) {
if (plugin != null && plugin.isEnabled()) { if (plugin != null && plugin.isEnabled()) {
Bukkit.getPluginManager().disablePlugin(plugin); Bukkit.getPluginManager().disablePlugin(plugin);
} }
} }
public static void disableAll() { public static void enableAll() {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> isIgnored(plugin)).forEach(PluginUtils::enable);
if (!isIgnored(plugin)) {
disable(plugin);
}
}
} }
public static String getFormattedName(final Plugin plugin) { public static void disableAll() {
Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> isIgnored(plugin)).forEach(PluginUtils::disable);
}
public static String getFormattedName(Plugin plugin) {
return getFormattedName(plugin, false); return getFormattedName(plugin, false);
} }
public static String getFormattedName(final Plugin plugin, final boolean includeVersions) { public static String getFormattedName(Plugin plugin, boolean includeVersions) {
final ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED; ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED;
String pluginName = color + plugin.getName(); String pluginName = color + plugin.getName();
if (includeVersions) { if (includeVersions) {
pluginName = pluginName + " (" + plugin.getDescription().getVersion() + ")"; pluginName = pluginName + " (" + plugin.getDescription().getVersion() + ")";
@ -72,76 +65,83 @@ public class PluginUtils {
return pluginName; return pluginName;
} }
public static Plugin getPluginByName(final String[] args, final int start) { public static Plugin getPluginByName(String[] args, int start) {
return getPluginByName(consolidateStrings(args, start)); return getPluginByName(consolidateStrings(args, start));
} }
public static Plugin getPluginByName(final String name) { public static Plugin getPluginByName(String name) {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { return Arrays.stream(Bukkit.getPluginManager().getPlugins(), 0, Bukkit.getPluginManager().getPlugins().length).filter(plugin -> name.equalsIgnoreCase(plugin.getName())).findFirst().orElse(null);
if (name.equalsIgnoreCase(plugin.getName())) {
return plugin;
}
}
return null;
} }
public static List<String> getPluginNames(final boolean fullName) { public static List<String> getPluginNames(boolean fullName) {
final List<String> plugins = new ArrayList<>(); List<String> plugins;
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { plugins = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(plugin -> fullName ? plugin.getDescription().getFullName() : plugin.getName()).collect(Collectors.toList());
plugins.add(fullName ? plugin.getDescription().getFullName() : plugin.getName());
}
return plugins; return plugins;
} }
public static String getPluginVersion(final String name) { public static String getPluginVersion(String name) {
final Plugin plugin = getPluginByName(name); Plugin plugin = getPluginByName(name);
if (plugin != null && plugin.getDescription() != null) { return plugin != null && plugin.getDescription() != null ? plugin.getDescription().getVersion() : null;
return plugin.getDescription().getVersion();
}
return null;
} }
public static String getUsages(final Plugin plugin) { public static String getUsages(Plugin plugin) {
final List<String> parsedCommands = new ArrayList<>(); List<String> parsedCommands = new ArrayList();
final Map<String, Map<String, Object>> commands = plugin.getDescription().getCommands(); Map commands = plugin.getDescription().getCommands();
if (commands != null) { if (commands != null) {
for (final Entry<String, Map<String, Object>> thisEntry : commands.entrySet()) { for (Object o : commands.entrySet()) {
Entry thisEntry = (Entry) o;
if (thisEntry != null) { if (thisEntry != null) {
parsedCommands.add(thisEntry.getKey()); parsedCommands.add((String) thisEntry.getKey());
} }
} }
} }
if (parsedCommands.isEmpty()) { return parsedCommands.isEmpty() ? "No commands registered." : Joiner.on(", ").join(parsedCommands);
return "No commands registered.";
}
return Joiner.on(", ").join(parsedCommands);
} }
@SuppressWarnings("unchecked") public static List<String> findByCommand(String command) {
public static List<String> findByCommand(final String command) { List<String> plugins = new ArrayList();
final List<String> plugins = new ArrayList<>();
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { label60:
final Map<String, Map<String, Object>> commands = plugin.getDescription().getCommands(); for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
Map<String, Map<String, Object>> commands = plugin.getDescription().getCommands();
if (commands != null) { if (commands != null) {
for (final Map.Entry<String, Map<String, Object>> commandNext : commands.entrySet()) { Iterator commandIterator = commands.entrySet().iterator();
if (commandNext.getKey().equalsIgnoreCase(command)) {
plugins.add(plugin.getName()); while (true) {
} else { label55:
for (final Map.Entry<String, Object> attributeNext : commandNext.getValue().entrySet()) { while (true) {
if (attributeNext.getKey().equals("aliases")) { if (!commandIterator.hasNext()) {
final Object aliases = attributeNext.getValue(); continue label60;
}
Entry<String, Map<String, Object>> commandNext = (Entry) commandIterator.next();
if (commandNext.getKey().equalsIgnoreCase(command)) {
plugins.add(plugin.getName());
} else {
Iterator attributeIterator = ((Map) commandNext.getValue()).entrySet().iterator();
while (true) while (true) {
Entry attributeNext;
if (!attributeIterator.hasNext()) {
continue label55;
}
attributeNext = (Entry) attributeIterator.next();
while (!attributeNext.getKey().equals("aliases")) {
if (!attributeIterator.hasNext()) {
continue label55;
}
attributeNext = (Entry) attributeIterator.next();
}
Object aliases = attributeNext.getValue();
if (aliases instanceof String) { if (aliases instanceof String) {
if (!((String) aliases).equalsIgnoreCase(command)) { if (((String) aliases).equalsIgnoreCase(command)) {
continue; plugins.add(plugin.getName());
} }
plugins.add(plugin.getName());
} else { } else {
final List<String> array = (List<String>) aliases; ((List<String>) aliases).stream().filter(str -> str.equalsIgnoreCase(command)).map(str -> plugin.getName()).forEach(plugins::add);
for (final String str : array) {
if (str.equalsIgnoreCase(command)) {
plugins.add(plugin.getName());
}
}
} }
} }
} }
@ -152,138 +152,172 @@ public class PluginUtils {
return plugins; return plugins;
} }
public static boolean isIgnored(final Plugin plugin) { public static boolean isIgnored(Plugin plugin) {
return isIgnored(plugin.getName()); return plugin.equals(Main.getInst());
} }
public static boolean isIgnored(final String plugin) { private static String load(Plugin plugin) {
return plugin.equalsIgnoreCase(Main.getInst().getName());
}
private static String load(final Plugin plugin) {
return load(plugin.getName()); return load(plugin.getName());
} }
public static String load(final String name) { /**
* 返回内容
*
* plugin-directory 插件目录不存在
* cannot-find 插件不存在
* invalid-description 无效的描述
* invalid-plugin 无效的插件
* loaded 载入成功
*/
public static String load(String name) {
Plugin target; Plugin target;
final File pluginDir = new File("plugins"); File pluginDir = new File("plugins");
if (!pluginDir.isDirectory()) { if (!pluginDir.isDirectory()) {
return "load.plugin-directory"; return "plugin-directory";
} } else {
File pluginFile = new File(pluginDir, name + ".jar"); File pluginFile = new File(pluginDir, name + ".jar");
if (!pluginFile.isFile()) { if (!pluginFile.isFile()) {
for (final File f : pluginDir.listFiles()) { for (File f : Objects.requireNonNull(pluginDir.listFiles())) {
if (f.getName().endsWith(".jar")) { if (f.getName().endsWith(".jar")) {
try { try {
final PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(f); PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(f);
if (desc.getName().equalsIgnoreCase(name)) { if (desc.getName().equalsIgnoreCase(name)) {
pluginFile = f; pluginFile = f;
break; break;
}
} catch (InvalidDescriptionException var11) {
return "cannot-find";
} }
} catch (InvalidDescriptionException e3) {
return "load.cannot-find";
} }
} }
} }
try {
target = Bukkit.getPluginManager().loadPlugin(pluginFile);
} catch (InvalidDescriptionException var9) {
return "invalid-description";
} catch (InvalidPluginException var10) {
return "invalid-plugin";
}
target.onLoad();
Bukkit.getPluginManager().enablePlugin(target);
return "loaded";
} }
try {
target = Bukkit.getPluginManager().loadPlugin(pluginFile);
} catch (InvalidDescriptionException e) {
return "load.invalid-description";
} catch (InvalidPluginException e2) {
return "load.invalid-plugin";
}
target.onLoad();
Bukkit.getPluginManager().enablePlugin(target);
return "load.loaded";
} }
public static void reload(final Plugin plugin) { public static void reload(Plugin plugin) {
if (plugin != null) { if (plugin != null) {
unload(plugin); unload(plugin);
load(plugin); load(plugin);
} }
} }
public static void reloadAll() { public static void reloadAll() {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { Arrays.stream(Bukkit.getPluginManager().getPlugins(), 0, Bukkit.getPluginManager().getPlugins().length).filter(PluginUtils::isIgnored).forEach(PluginUtils::reload);
if (!isIgnored(plugin)) {
reload(plugin);
}
}
} }
@SuppressWarnings("unchecked") /**
public static String unload(final Plugin plugin) { * 返回内容
final String name = plugin.getName(); *
final PluginManager pluginManager = Bukkit.getPluginManager(); * failed 卸载失败
* unloaded 卸载成功
*/
public static String unload(Plugin plugin) {
String name = plugin.getName();
PluginManager pluginManager = Bukkit.getPluginManager();
SimpleCommandMap commandMap = null; SimpleCommandMap commandMap = null;
List<Plugin> plugins = null; List<Plugin> plugins = null;
Map<String, Plugin> names = null; Map<String, Plugin> names = null;
Map<String, Command> commands = null; Map<String, Command> commands = null;
Map<Event, SortedSet<RegisteredListener>> listeners = null; Map<Event, SortedSet<RegisteredListener>> listeners = null;
boolean reloadlisteners = true;
if (pluginManager != null) { if (pluginManager != null) {
pluginManager.disablePlugin(plugin); pluginManager.disablePlugin(plugin);
try { try {
final Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins"); Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins");
pluginsField.setAccessible(true); pluginsField.setAccessible(true);
plugins = (List<Plugin>) pluginsField.get(pluginManager); plugins = (List) pluginsField.get(pluginManager);
final Field lookupNamesField = Bukkit.getPluginManager().getClass().getDeclaredField("lookupNames"); Field lookupNamesField = Bukkit.getPluginManager().getClass().getDeclaredField("lookupNames");
lookupNamesField.setAccessible(true); lookupNamesField.setAccessible(true);
names = (Map<String, Plugin>) lookupNamesField.get(pluginManager); names = (Map) lookupNamesField.get(pluginManager);
Field commandMapField;
try { try {
final Field listenersField = Bukkit.getPluginManager().getClass().getDeclaredField("listeners"); commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("listeners");
listenersField.setAccessible(true); commandMapField.setAccessible(true);
listeners = (Map<Event, SortedSet<RegisteredListener>>) listenersField.get(pluginManager); listeners = (Map) commandMapField.get(pluginManager);
} catch (Exception e3) { } catch (Exception ignored) {
reloadlisteners = false;
} }
final Field commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap");
commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap");
commandMapField.setAccessible(true); commandMapField.setAccessible(true);
commandMap = (SimpleCommandMap) commandMapField.get(pluginManager); commandMap = (SimpleCommandMap) commandMapField.get(pluginManager);
final Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands"); Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true); knownCommandsField.setAccessible(true);
commands = (Map<String, Command>) knownCommandsField.get(commandMap); commands = (Map) knownCommandsField.get(commandMap);
} catch (NoSuchFieldException | IllegalAccessException e) { } catch (NoSuchFieldException | IllegalAccessException var15) {
return "failed"; return "failed";
} }
} }
pluginManager.disablePlugin(plugin); pluginManager.disablePlugin(plugin);
if (plugins != null && plugins.contains(plugin)) { if (plugins != null && plugins.contains(plugin)) {
plugins.remove(plugin); plugins.remove(plugin);
} }
if (names != null && names.containsKey(name)) { if (names != null && names.containsKey(name)) {
names.remove(name); names.remove(name);
} }
if (listeners != null && reloadlisteners) {
for (final SortedSet<RegisteredListener> set : listeners.values()) { Iterator it;
set.removeIf(value -> value.getPlugin() == plugin); if (listeners != null) {
} it = listeners.values().iterator();
}
if (commandMap != null) { while (it.hasNext()) {
final Iterator<Map.Entry<String, Command>> it2 = commands.entrySet().iterator(); SortedSet<RegisteredListener> set = (SortedSet) it.next();
while (it2.hasNext()) {
final Map.Entry<String, Command> entry = it2.next(); while (it.hasNext()) {
if (entry.getValue() instanceof PluginCommand) { RegisteredListener value = (RegisteredListener) it.next();
final PluginCommand c = (PluginCommand) entry.getValue(); if (value.getPlugin() == plugin) {
if (c.getPlugin() != plugin) { it.remove();
continue;
} }
c.unregister(commandMap);
it2.remove();
} }
} }
} }
final ClassLoader cl = plugin.getClass().getClassLoader();
if (commandMap != null) {
it = commands.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Command> entry = (Entry) it.next();
if (entry.getValue() instanceof PluginCommand) {
PluginCommand c = (PluginCommand) entry.getValue();
if (c.getPlugin() == plugin) {
c.unregister(commandMap);
it.remove();
}
}
}
}
ClassLoader cl = plugin.getClass().getClassLoader();
if (cl instanceof URLClassLoader) { if (cl instanceof URLClassLoader) {
try { try {
((URLClassLoader) cl).close(); ((URLClassLoader) cl).close();
} catch (IOException ex) { } catch (IOException var13) {
Logger.getLogger(PluginUtils.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(PluginUtils.class.getName()).log(Level.SEVERE, null, var13);
} }
} }
System.gc();
return "unloaded"; return "unloaded";
} }
private static String consolidateStrings(String[] args, int start) {
String ret = "";
if (args.length > start + 1) {
ret = IntStream.range(start + 1, args.length).mapToObj(i -> " " + args[i]).collect(Collectors.joining("", args[start], ""));
}
return ret;
}
} }

View File

@ -1,8 +1,10 @@
package me.skymc.taboolib.sign; package me.skymc.taboolib.sign;
import java.lang.reflect.InvocationTargetException; import me.skymc.taboolib.Main;
import java.util.HashMap; import me.skymc.taboolib.location.LocationUtils;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.methods.MethodsUtils;
import me.skymc.taboolib.nms.NMSUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@ -16,134 +18,126 @@ import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
import me.skymc.taboolib.Main; import java.lang.reflect.InvocationTargetException;
import me.skymc.taboolib.location.LocationUtils; import java.util.HashMap;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.methods.MethodsUtils;
import me.skymc.taboolib.nms.NMSUtils;
@Deprecated @Deprecated
public class SignUtils implements Listener { public class SignUtils implements Listener {
public static HashMap<String, Block> signs = new HashMap<>();
public static void openSign(Player p, Block b) {
if (!(b.getType().equals(Material.WALL_SIGN) || b.getType().equals(Material.SIGN_POST))) {
return;
}
b.setMetadata("TabooLib-Sign-Editing", new FixedMetadataValue(Main.getInst(), true));
try {
Object world = b.getWorld().getClass().getMethod("getHandle").invoke(b.getWorld());
Object blockPos = NMSUtils.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(b.getX(), b.getY(), b.getZ());
Object sign = world.getClass().getMethod("getTileEntity", NMSUtils.getNMSClass("BlockPosition")).invoke(world, blockPos);
Object player = p.getClass().getMethod("getHandle").invoke(p);
player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign);
}
catch (Exception e) {
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)");
e.printStackTrace();
}
}
public static void openSign(Player p, String[] lines, String signid) public static HashMap<String, Block> signs = new HashMap<>();
{
if (!MethodsUtils.checkUser(new String(new byte[] { 'm', 'e', '.', 's', 'k', 'y', 'm', 'c' }), new Exception().getStackTrace()[1].getClassName())) public static void openSign(Player p, Block b) {
{
throw new Error("未经允许的方法调用"); if (!(b.getType().equals(Material.WALL_SIGN) || b.getType().equals(Material.SIGN_POST))) {
} return;
}
Block b = LocationUtils.findBlockByLocation(p.getLocation());
if(b == null) { b.setMetadata("TabooLib-Sign-Editing", new FixedMetadataValue(Main.getInst(), true));
try {
Object world = b.getWorld().getClass().getMethod("getHandle").invoke(b.getWorld());
Object blockPos = NMSUtils.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(b.getX(), b.getY(), b.getZ());
Object sign = world.getClass().getMethod("getTileEntity", NMSUtils.getNMSClass("BlockPosition")).invoke(world, blockPos);
Object player = p.getClass().getMethod("getHandle").invoke(p);
player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign);
} catch (Exception e) {
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)");
e.printStackTrace();
}
}
public static void openSign(Player p, String[] lines, String signid) {
if (!MethodsUtils.checkUser(new String(new byte[]{'m', 'e', '.', 's', 'k', 'y', 'm', 'c'}), new Exception().getStackTrace()[1].getClassName())) {
throw new Error("未经允许的方法调用");
}
Block b = LocationUtils.findBlockByLocation(p.getLocation());
if (b == null) {
MsgUtils.send(p, "&4所在位置无法进行该操作 &8(NOT FOUND AIR BY SIGN)"); MsgUtils.send(p, "&4所在位置无法进行该操作 &8(NOT FOUND AIR BY SIGN)");
return; return;
} }
b.setData((byte) 0); b.setData((byte) 0);
b.setType(Material.WALL_SIGN); b.setType(Material.WALL_SIGN);
b.setMetadata("TabooLib-Sign", new FixedMetadataValue(Main.getInst(), true)); b.setMetadata("TabooLib-Sign", new FixedMetadataValue(Main.getInst(), true));
b.setMetadata("TabooLib-Sign-UUID", new FixedMetadataValue(Main.getInst(), signid)); b.setMetadata("TabooLib-Sign-UUID", new FixedMetadataValue(Main.getInst(), signid));
try { try {
Object world = b.getWorld().getClass().getMethod("getHandle").invoke(b.getWorld()); Object world = b.getWorld().getClass().getMethod("getHandle").invoke(b.getWorld());
Object blockPos = NMSUtils.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(b.getX(), b.getY(), b.getZ()); Object blockPos = NMSUtils.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(b.getX(), b.getY(), b.getZ());
Object sign = world.getClass().getMethod("getTileEntity", NMSUtils.getNMSClass("BlockPosition")).invoke(world, blockPos); Object sign = world.getClass().getMethod("getTileEntity", NMSUtils.getNMSClass("BlockPosition")).invoke(world, blockPos);
Object[] _lines = (Object[]) sign.getClass().getField("lines").get(sign); Object[] _lines = (Object[]) sign.getClass().getField("lines").get(sign);
for (int i = 0; i < lines.length ; i++) { for (int i = 0; i < lines.length; i++) {
Object object = NMSUtils.getNMSClass("ChatComponentText").getConstructor(String.class).newInstance(lines[i]); Object object = NMSUtils.getNMSClass("ChatComponentText").getConstructor(String.class).newInstance(lines[i]);
_lines[i] = object; _lines[i] = object;
} }
Object player = p.getClass().getMethod("getHandle").invoke(p); Object player = p.getClass().getMethod("getHandle").invoke(p);
Bukkit.getScheduler().runTaskLater(Main.getInst(), () -> { Bukkit.getScheduler().runTaskLater(Main.getInst(), () -> {
if (p.isOnline()) { if (p.isOnline()) {
try { try {
player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign); player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign);
signs.put(p.getName(), b); signs.put(p.getName(), b);
} } catch (IllegalAccessException | SecurityException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException e) {
catch (IllegalAccessException|SecurityException|NoSuchMethodException|InvocationTargetException|IllegalArgumentException e) { MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.2)");
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.2)"); e.printStackTrace();
e.printStackTrace(); }
} }
} }, 3);
}, 3); } catch (Exception e) {
} MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)");
catch (Exception e) { e.printStackTrace();
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)");
e.printStackTrace();
} }
} }
@EventHandler (priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void signChange(SignChangeEvent e) { public void signChange(SignChangeEvent e) {
Block block = e.getBlock(); Block block = e.getBlock();
if (block.hasMetadata("TabooLib-Sign")) { if (block.hasMetadata("TabooLib-Sign")) {
signs.remove(e.getPlayer().getName()); signs.remove(e.getPlayer().getName());
String signid = String.valueOf(block.getMetadata("TabooLib-Sign-UUID").get(0).value()); String signid = String.valueOf(block.getMetadata("TabooLib-Sign-UUID").get(0).value());
Bukkit.getPluginManager().callEvent(new TabooSignChangeEvent(e.getPlayer(), block, e.getLines(), signid)); Bukkit.getPluginManager().callEvent(new TabooSignChangeEvent(e.getPlayer(), block, e.getLines(), signid));
block.removeMetadata("TabooLib-Sign", Main.getInst()); block.removeMetadata("TabooLib-Sign", Main.getInst());
block.removeMetadata("TabooLib-Sign-UUID", Main.getInst()); block.removeMetadata("TabooLib-Sign-UUID", Main.getInst());
block.setType(Material.AIR); block.setType(Material.AIR);
block.setData((byte) 0); block.setData((byte) 0);
} }
} }
@EventHandler @EventHandler
public void quit(PlayerQuitEvent e) { public void quit(PlayerQuitEvent e) {
if (signs.containsKey(e.getPlayer().getName())) { if (signs.containsKey(e.getPlayer().getName())) {
Block block = signs.get(e.getPlayer().getName()); Block block = signs.get(e.getPlayer().getName());
if (block.hasMetadata("TabooLib-Sign")) { if (block.hasMetadata("TabooLib-Sign")) {
block.removeMetadata("TabooLib-Sign", Main.getInst()); block.removeMetadata("TabooLib-Sign", Main.getInst());
block.removeMetadata("TabooLib-Sign-UUID", Main.getInst()); block.removeMetadata("TabooLib-Sign-UUID", Main.getInst());
block.setType(Material.AIR); block.setType(Material.AIR);
block.setData((byte) 0); block.setData((byte) 0);
} }
} }
} }
@EventHandler @EventHandler
public void block(BlockPhysicsEvent e) { public void block(BlockPhysicsEvent e) {
Block block = e.getBlock(); Block block = e.getBlock();
if (block.hasMetadata("TabooLib-Sign")) { if (block.hasMetadata("TabooLib-Sign")) {
e.setCancelled(true); e.setCancelled(true);
} }
} }
@EventHandler @EventHandler
public void blocku(BlockBreakEvent e) { public void blocku(BlockBreakEvent e) {
Block block = e.getBlock(); Block block = e.getBlock();
if (block.hasMetadata("TabooLib-Sign") && !e.getPlayer().isOp()) { if (block.hasMetadata("TabooLib-Sign") && !e.getPlayer().isOp()) {
e.setCancelled(true); e.setCancelled(true);
} }
} }
} }

View File

@ -6,48 +6,43 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
@Deprecated @Deprecated
public class TabooSignChangeEvent public class TabooSignChangeEvent extends Event {
extends Event
{
private static final HandlerList handlers = new HandlerList();
private Player player;
private Block block;
private String[] lines;
private String uuid;
public TabooSignChangeEvent(Player player, Block block, String[] lines, String uuid)
{
this.player = player;
this.block = block;
this.lines = lines;
this.uuid = uuid;
}
public Player getPlayer()
{
return this.player;
}
public Block getBlock() {
return this.block;
}
public String[] getLines() {
return this.lines;
}
public String getUUID() {
return this.uuid;
}
@Override private static final HandlerList handlers = new HandlerList();
public HandlerList getHandlers() private Player player;
{ private Block block;
return handlers; private String[] lines;
} private String uuid;
public static HandlerList getHandlerList() public TabooSignChangeEvent(Player player, Block block, String[] lines, String uuid) {
{ this.player = player;
return handlers; this.block = block;
} this.lines = lines;
this.uuid = uuid;
}
public Player getPlayer() {
return this.player;
}
public Block getBlock() {
return this.block;
}
public String[] getLines() {
return this.lines;
}
public String getUUID() {
return this.uuid;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
} }

View File

@ -1,7 +1,10 @@
package me.skymc.taboolib.string; package me.skymc.taboolib.string;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/** /**
* @author Bkm016 * @author Bkm016
@ -9,12 +12,9 @@ import java.util.List;
*/ */
public class ArrayUtils { public class ArrayUtils {
@SuppressWarnings("unchecked")
public static <T> List<T> asList(T... args) { public static <T> List<T> asList(T... args) {
List<T> list = new ArrayList<>(); List<T> list = new ArrayList<>();
for (T value : args) { Collections.addAll(list, args);
list.add(value);
}
return list; return list;
} }
@ -39,11 +39,6 @@ public class ArrayUtils {
} }
public static String arrayJoin(String[] args, int start) { public static String arrayJoin(String[] args, int start) {
StringBuilder stringBuilder = new StringBuilder(); return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim();
for (int i = start ; i < args.length ; i++) {
stringBuilder.append(args[i]);
stringBuilder.append(" ");
}
return stringBuilder.toString().trim();
} }
} }

View File

@ -1,5 +1,13 @@
package me.skymc.taboolib.string; package me.skymc.taboolib.string;
import com.google.common.base.Charsets;
import me.skymc.taboolib.message.MsgUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -7,122 +15,112 @@ import java.io.InputStreamReader;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.bukkit.command.CommandSender; @Deprecated
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import com.google.common.base.Charsets;
import me.skymc.taboolib.message.MsgUtils;
public class Language { public class Language {
private FileConfiguration conf = null;
private String langName;
private Plugin plugin;
public Language(Plugin plugin) {
this("zh_CN", plugin, false);
}
public Language(String name, Plugin plugin) {
this(name, plugin, false);
}
public Language(String name, Plugin plugin, boolean utf8) {
this.plugin = plugin;
this.langName = name;
File file = new File(getLanguageDir(), name + ".yml");
if (!file.exists()) {
plugin.saveResource("Language/" + name + ".yml", true);
}
if (utf8) {
reloadUTF8(this.langName);
}
else {
reload(this.langName);
}
}
public FileConfiguration getConfiguration() {
return conf;
}
public void send(CommandSender sender, String key) {
sender.sendMessage(get(key));
}
public void send(Player player, String key) {
player.sendMessage(get(key));
}
public void sendList(CommandSender sender, String key) {
List<String> list = getList(key);
for (String msg : list) {
sender.sendMessage(msg);
}
}
public void sendList(Player player, String key) {
List<String> list = getList(key);
for (String msg : list) {
player.sendMessage(msg);
}
}
public String get(String key) {
if (conf == null || conf.getString(key) == null) {
return "§4[Language \"" + key + "\" Not Found]";
}
return conf.getString(key).replace("&", "§");
}
public List<String> getList(String key) {
if (conf == null || conf.getString(key) == null) {
return Collections.singletonList("§4[Language \"" + key + "\" Not Found]");
}
List<String> list = conf.getStringList(key);
for (int i = 0 ; i < list.size() ; i++) {
list.set(i, list.get(i).replace("&", "§"));
}
return list;
}
public void reload() {
reload(langName);
}
public void reload(String name) { private FileConfiguration conf = null;
File langFile = new File(getLanguageDir(), name + ".yml"); private String langName;
if (!langFile.exists()) { private Plugin plugin;
MsgUtils.warn("语言文件 " + langName + " 不存在, 请更改配置文件");
return; public Language(Plugin plugin) {
} this("zh_CN", plugin, false);
conf = YamlConfiguration.loadConfiguration(langFile); }
}
public Language(String name, Plugin plugin) {
public void reloadUTF8(String name) { this(name, plugin, false);
File langFile = new File(getLanguageDir(), name + ".yml"); }
if (!langFile.exists()) {
MsgUtils.warn("语言文件 " + langName + " 不存在, 请更改配置文件"); public Language(String name, Plugin plugin, boolean utf8) {
return; this.plugin = plugin;
} this.langName = name;
try {
conf = YamlConfiguration.loadConfiguration(new InputStreamReader(new FileInputStream(langFile), Charsets.UTF_8)); File file = new File(getLanguageDir(), name + ".yml");
} catch (FileNotFoundException e) { if (!file.exists()) {
conf = new YamlConfiguration(); plugin.saveResource("Language/" + name + ".yml", true);
} }
}
if (utf8) {
private File getLanguageDir() { reloadUTF8(this.langName);
File dir = new File(plugin.getDataFolder(), "Language"); } else {
if (!dir.exists()) { reload(this.langName);
dir.mkdirs(); }
} }
return dir;
} public FileConfiguration getConfiguration() {
return conf;
}
public void send(CommandSender sender, String key) {
sender.sendMessage(get(key));
}
public void send(Player player, String key) {
player.sendMessage(get(key));
}
public void sendList(CommandSender sender, String key) {
List<String> list = getList(key);
for (String msg : list) {
sender.sendMessage(msg);
}
}
public void sendList(Player player, String key) {
List<String> list = getList(key);
for (String msg : list) {
player.sendMessage(msg);
}
}
public String get(String key) {
if (conf == null || conf.getString(key) == null) {
return "§4[Language \"" + key + "\" Not Found]";
}
return conf.getString(key).replace("&", "§");
}
public List<String> getList(String key) {
if (conf == null || conf.getString(key) == null) {
return Collections.singletonList("§4[Language \"" + key + "\" Not Found]");
}
List<String> list = conf.getStringList(key);
for (int i = 0; i < list.size(); i++) {
list.set(i, list.get(i).replace("&", "§"));
}
return list;
}
public void reload() {
reload(langName);
}
public void reload(String name) {
File langFile = new File(getLanguageDir(), name + ".yml");
if (!langFile.exists()) {
MsgUtils.warn("语言文件 " + langName + " 不存在, 请更改配置文件");
return;
}
conf = YamlConfiguration.loadConfiguration(langFile);
}
public void reloadUTF8(String name) {
File langFile = new File(getLanguageDir(), name + ".yml");
if (!langFile.exists()) {
MsgUtils.warn("语言文件 " + langName + " 不存在, 请更改配置文件");
return;
}
try {
conf = YamlConfiguration.loadConfiguration(new InputStreamReader(new FileInputStream(langFile), Charsets.UTF_8));
} catch (FileNotFoundException e) {
conf = new YamlConfiguration();
}
}
private File getLanguageDir() {
File dir = new File(plugin.getDataFolder(), "Language");
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
} }

View File

@ -33,4 +33,67 @@ public class StringUtils {
return sb.toString(); return sb.toString();
} }
public static double similarDegree(String strA, String strB){
String newStrA = removeSign(max(strA, strB));
String newStrB = removeSign(min(strA, strB));
int temp = Math.max(newStrA.length(), newStrB.length());
int temp2 = longestCommonSubstring(newStrA, newStrB).length();
return temp2 * 1.0 / temp;
}
private static String max(String strA, String strB) {
return strA.length() >= strB.length() ? strA : strB;
}
private static String min(String strA, String strB) {
return strA.length() < strB.length() ? strA : strB;
}
private static String removeSign(String str) {
StringBuffer sb = new StringBuffer();
for (char item : str.toCharArray()) {
if (charReg(item)){
sb.append(item);
}
}
return sb.toString();
}
private static boolean charReg(char charValue) {
return (charValue >= 0x4E00 && charValue <= 0X9FA5) || (charValue >= 'a' && charValue <= 'z') || (charValue >= 'A' && charValue <= 'Z') || (charValue >= '0' && charValue <= '9');
}
private static String longestCommonSubstring(String strA, String strB) {
char[] chars_strA = strA.toCharArray();
char[] chars_strB = strB.toCharArray();
int m = chars_strA.length;
int n = chars_strB.length;
int[][] matrix = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (chars_strA[i - 1] == chars_strB[j - 1])
matrix[i][j] = matrix[i - 1][j - 1] + 1;
else
matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]);
}
}
char[] result = new char[matrix[m][n]];
int currentIndex = result.length - 1;
while (matrix[m][n] != 0) {
if (matrix[n] == matrix[n - 1])
n--;
else if (matrix[m][n] == matrix[m - 1][n])
m--;
else {
result[currentIndex] = chars_strA[m - 1];
currentIndex--;
n--;
m--;
}
}
return new String(result);
}
} }

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib.string.language2; package me.skymc.taboolib.string.language2;
import com.ilummc.tlib.resources.TLocale;
import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.fileutils.ConfigUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -74,10 +75,7 @@ public class Language2 {
languageFile = new File(languageFolder, languageName); languageFile = new File(languageFolder, languageName);
if (!languageFile.exists()) { if (!languageFile.exists()) {
if (plugin.getResource("Language2/" + languageName) == null) { if (plugin.getResource("Language2/" + languageName) == null) {
try { TLocale.Logger.error("LANGUAGE2.FALL-NOTFOUND-FILE", languageName);
throw new FileNotFoundException("语言文件 " + languageName + " 不存在");
} catch (Exception ignored) {
}
} else { } else {
plugin.saveResource("Language2/" + languageName, true); plugin.saveResource("Language2/" + languageName, true);
} }

View File

@ -142,15 +142,11 @@ public class Language2Format implements Language2Line {
@Override @Override
public void send(Player player) { public void send(Player player) {
for (Language2Line line : language2Lines) { language2Lines.forEach(line -> line.send(player));
line.send(player);
}
} }
@Override @Override
public void console() { public void console() {
for (Language2Line line : language2Lines) { language2Lines.forEach(Language2Line::console);
line.console();
}
} }
} }

View File

@ -8,6 +8,7 @@ import org.bukkit.entity.Player;
import java.util.*; import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.stream.IntStream;
/** /**
* @author sky * @author sky
@ -96,9 +97,7 @@ public class Language2Value {
* @param players 玩家 * @param players 玩家
*/ */
public void send(List<Player> players) { public void send(List<Player> players) {
for (Player player : players) { players.forEach(this::send);
send(player);
}
} }
/** /**
@ -206,9 +205,7 @@ public class Language2Value {
* @return * @return
*/ */
public List<String> asColored(List<String> list) { public List<String> asColored(List<String> list) {
for (int i = 0; i < list.size(); i++) { IntStream.range(0, list.size()).forEach(i -> list.set(i, ChatColor.translateAlternateColorCodes('&', list.get(i))));
list.set(i, ChatColor.translateAlternateColorCodes('&', list.get(i)));
}
return list; return list;
} }

View File

@ -31,17 +31,12 @@ public class Language2Sound implements Language2Line {
public Language2Sound(Language2Format format, List<String> list) { public Language2Sound(Language2Format format, List<String> list) {
this.value = format.getLanguage2Value(); this.value = format.getLanguage2Value();
// 遍历文本 list.forEach(line -> sounds.add(new SoundPack(line)));
for (String line : list) {
sounds.add(new SoundPack(line));
}
} }
@Override @Override
public void send(Player player) { public void send(Player player) {
for (SoundPack sound : sounds) { sounds.forEach(sound -> sound.play(player));
sound.play(player);
}
} }
@Override @Override

View File

@ -29,21 +29,16 @@ public class Language2Text implements Language2Line {
public Language2Text(Language2Format format, List<String> list) { public Language2Text(Language2Format format, List<String> list) {
this.value = format.getLanguage2Value(); this.value = format.getLanguage2Value();
// 遍历文本
text.addAll(list); text.addAll(list);
} }
@Override @Override
public void send(Player player) { public void send(Player player) {
for (String line : text) { text.forEach(player::sendMessage);
player.sendMessage(line);
}
} }
@Override @Override
public void console() { public void console() {
for (String line : text) { text.forEach(line -> Bukkit.getConsoleSender().sendMessage(line));
Bukkit.getConsoleSender().sendMessage(line);
}
} }
} }

View File

@ -1,170 +1,159 @@
package me.skymc.taboolib.timecycle; package me.skymc.taboolib.timecycle;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.database.GlobalDataManager;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.database.GlobalDataManager;
import me.skymc.taboolib.message.MsgUtils;
public class TimeCycleManager { public class TimeCycleManager {
/**
* 最后一次更新 2018年1月16日21:07:49
*
* @author sky
*/
private static ConcurrentHashMap<String, TimeCycle> cycles = new ConcurrentHashMap<>(); /**
* 最后一次更新 2018年1月16日21:07:49
/** *
* 获取周期管理器 * @author sky
* */
* @param name
* @return private static ConcurrentHashMap<String, TimeCycle> cycles = new ConcurrentHashMap<>();
*/
public static TimeCycle getTimeCycle(String name) { /**
return cycles.get(name); * 获取周期管理器
} *
* @param name
/** * @return
* 获取所有周期管理器 */
* public static TimeCycle getTimeCycle(String name) {
* @return return cycles.get(name);
*/ }
public static Collection<TimeCycle> getTimeCycles() {
return cycles.values(); /**
} * 获取所有周期管理器
*
/** * @return
* 彻底删除周期数据 */
* public static Collection<TimeCycle> getTimeCycles() {
* @param name return cycles.values();
*/ }
public static void deleteCycleData(String name) {
HashMap<String, String> map = GlobalDataManager.getVariables(); /**
for (String _name : map.keySet()) { * 彻底删除周期数据
if (_name.startsWith("timecycle")) { *
GlobalDataManager.setVariable(name, null); * @param name
} */
} public static void deleteCycleData(String name) {
} HashMap<String, String> map = GlobalDataManager.getVariables();
map.keySet().stream().filter(_name -> _name.startsWith("timecycle")).forEach(_name -> GlobalDataManager.setVariable(name, null));
/** }
* 注册周期管理器
* /**
* @param cycle * 注册周期管理器
*/ *
public static void register(TimeCycle cycle) { * @param cycle
if (!cycles.containsKey(cycle.getName())) { */
cycles.put(cycle.getName(), cycle); public static void register(TimeCycle cycle) {
} if (!cycles.containsKey(cycle.getName())) {
else { cycles.put(cycle.getName(), cycle);
MsgUtils.warn("注册周期管理器 §8" + cycle.getName() + "§c 失败, 原因: &4名称重复"); } else {
} TLocale.Logger.error("TIMECYCLE.FALL-CYCLE-EXISTS", cycle.getName());
} }
}
/**
* 注销周期管理器 /**
* * 注销周期管理器
* @param name *
* @return * @param name
*/ * @return
public static TimeCycle cancel(String name) { */
return cycles.remove(name); public static TimeCycle cancel(String name) {
} return cycles.remove(name);
}
/**
* 注销插件所有周期管理器 /**
* * 注销插件所有周期管理器
* @param plugin *
*/ * @param plugin
public static void cancel(Plugin plugin) { */
cycles.values().forEach(x -> { public static void cancel(Plugin plugin) {
if (x.getPlugin().equals(plugin)) { cycles.values().stream().filter(x -> x.getPlugin().equals(plugin)).forEach(x -> cycles.remove(x.getName()));
cycles.remove(x.getName()); }
}
}); /**
} * 设置上一次更新事件
*
/** * @param name
* 设置上一次更新事件 * @param time
* */
* @param name public static boolean setTimeline(String name, Long time) {
* @param time if (cycles.containsKey(name)) {
*/ GlobalDataManager.setVariable("timecycle:" + name, time.toString());
public static boolean setTimeline(String name, Long time) { return true;
if (cycles.containsKey(name)) { }
GlobalDataManager.setVariable("timecycle:" + name, time.toString()); return false;
return true; }
}
return false; /**
} * 获取下一次刷新时间
*
/** * @param name
* 获取下一次刷新时间 * @return
* */
* @param name public static long getAfterTimeline(String name) {
* @return if (cycles.containsKey(name)) {
*/ Long value = Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0"));
public static long getAfterTimeline(String name) { return value + cycles.get(name).getCycle();
if (cycles.containsKey(name)) { }
Long value = Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0")); return 0L;
return value + cycles.get(name).getCycle(); }
}
return 0L; /**
} * 获取上一次刷新时间
*
/** * @param name
* 获取上一次刷新时间 * @return
* */
* @param name public static long getBeforeTimeline(String name) {
* @return if (cycles.containsKey(name)) {
*/ return Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0"));
public static long getBeforeTimeline(String name) { }
if (cycles.containsKey(name)) { return 0L;
return Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0")); }
}
return 0L;
} public static void load() {
// 注册调度器
new BukkitRunnable() {
public static void load() { @Override
// 注册调度器 public void run() {
new BukkitRunnable() { for (TimeCycle cycle : cycles.values()) {
// 调度器没有被执行过
@Override if (!GlobalDataManager.contains("timecycle:" + cycle.getName())) {
public void run() { long time = new TimeCycleInitializeEvent(cycle, System.currentTimeMillis()).call().getTimeline();
for (TimeCycle cycle : cycles.values()) { // 初始化
// 调度器没有被执行过 GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time));
if (!GlobalDataManager.contains("timecycle:" + cycle.getName())) { // 触发器
long time = new TimeCycleInitializeEvent(cycle, System.currentTimeMillis()).call().getTimeline(); Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle));
// 初始化 }
GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time)); // 如果超出刷新时间
// 触发器 else if (System.currentTimeMillis() >= getAfterTimeline(cycle.getName())) {
Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle)); long time = System.currentTimeMillis();
} // 如果时间差大于 30
// 如果超出刷新时间 if (time - getAfterTimeline(cycle.getName()) > 30000) {
else if (System.currentTimeMillis() >= getAfterTimeline(cycle.getName())) { // 初始化
long time = System.currentTimeMillis(); time = new TimeCycleInitializeEvent(cycle, time).call().getTimeline();
// 如果时间差大于 30 }
if (time - getAfterTimeline(cycle.getName()) > 30000) { // 重置
// 初始化 GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time));
time = new TimeCycleInitializeEvent(cycle, time).call().getTimeline(); // 触发器
} Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle));
// 重置 }
GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time)); }
// 触发器 }
Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle)); }.runTaskTimerAsynchronously(Main.getInst(), 0, 20);
} }
}
}
}.runTaskTimerAsynchronously(Main.getInst(), 0, 20);
}
} }

View File

@ -2,6 +2,7 @@ package me.skymc.taboolib.update;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.fileutils.FileUtils; import me.skymc.taboolib.fileutils.FileUtils;
@ -14,37 +15,30 @@ import org.bukkit.scheduler.BukkitRunnable;
*/ */
public class UpdateTask { public class UpdateTask {
private static final String API = "https://api.github.com/repos/Bkm016/TabooLib/releases/latest"; private static final String API = "https://internal.github.com/repos/Bkm016/TabooLib/releases/latest";
/** /**
* 检测更新 * 检测更新
*/ */
public UpdateTask() { public UpdateTask() {
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
public void run() { public void run() {
if (!Main.getInst().getConfig().getBoolean("UPDATE-CHECK")) { if (!Main.getInst().getConfig().getBoolean("UPDATE-CHECK")) {
return; return;
} }
String value = FileUtils.getStringFromURL(API, "{}"); String value = FileUtils.getStringFromURL(API, "{}");
JsonObject json = new JsonParser().parse(value).getAsJsonObject(); JsonObject json = new JsonParser().parse(value).getAsJsonObject();
if (json.entrySet().size() > 0) { if (json.entrySet().size() > 0) {
double newVersion = Double.parseDouble(json.get("tag_name").getAsString()); double newVersion = Double.parseDouble(json.get("tag_name").getAsString());
if (TabooLib.getPluginVersion() >= newVersion) { if (TabooLib.getPluginVersion() >= newVersion) {
MsgUtils.send("插件已是最新版, 无需更新!"); TLocale.Logger.info("UPDATETASK.VERSION-LATEST");
} } else {
else { TLocale.Logger.info("UPDATETASK.VERSION-OUTDATED", String.valueOf(TabooLib.getPluginVersion()), String.valueOf(newVersion));
MsgUtils.send("&8####################################################"); }
MsgUtils.send("检测到有新的版本更新!"); }
MsgUtils.send("当前版本: &f" + TabooLib.getPluginVersion()); }
MsgUtils.send("最新版本: &f" + newVersion); }.runTaskLaterAsynchronously(Main.getInst(), 100);
MsgUtils.send("下载地址: &fhttp://www.mcbbs.net/thread-773065-1-1.html"); }
MsgUtils.send("开源地址: &fhttps://github.com/Bkm016/TabooLib/");
MsgUtils.send("&8####################################################");
}
}
}
}.runTaskLaterAsynchronously(Main.getInst(), 100);
}
} }

View File

@ -1,8 +1,8 @@
package me.skymc.tlm; package me.skymc.tlm;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.string.language2.Language2; import me.skymc.taboolib.string.language2.Language2;
import me.skymc.tlm.module.TabooLibraryModule; import me.skymc.tlm.module.TabooLibraryModule;
import me.skymc.tlm.module.sub.ModuleCommandChanger; import me.skymc.tlm.module.sub.ModuleCommandChanger;
@ -54,9 +54,8 @@ public class TLM {
// 载入模块 // 载入模块
TabooLibraryModule.getInst().loadModules(); TabooLibraryModule.getInst().loadModules();
// 提示 // 提示
MsgUtils.send("载入 &f" + TabooLibraryModule.getInst().getSize() + " &7个 &fTLM &7模块"); TLocale.Logger.info("TABOOLIB-MODULE.SUCCESS-LOADED", String.valueOf(TabooLibraryModule.getInst().getSize()));
} }
/** /**
@ -80,12 +79,7 @@ public class TLM {
*/ */
public void reloadConfig() { public void reloadConfig() {
config = ConfigUtils.saveDefaultConfig(Main.getInst(), "module.yml"); config = ConfigUtils.saveDefaultConfig(Main.getInst(), "module.yml");
// 载入语言文件 language = new Language2(config.getString("Language"), Main.getInst());
try {
language = new Language2(config.getString("Language"), Main.getInst());
} catch (Exception e) {
MsgUtils.warn("语言文件不存在: &4" + config.getString("Language"));
}
} }
/** /**
@ -97,4 +91,12 @@ public class TLM {
public boolean isEnableModule(String name) { public boolean isEnableModule(String name) {
return config.getStringList("EnableModule").contains(name); return config.getStringList("EnableModule").contains(name);
} }
public void loadedFall(String moduleName, String result, String location) {
TLocale.Logger.error("TABOOLIB-MODULE.FALL-LOADED", moduleName, result, location);
}
public void runtimeFall(String moduleName, String result, String location) {
TLocale.Logger.error("TABOOLIB-MODULE.FALL-RUNTIME", moduleName, result, location);
}
} }

View File

@ -1,10 +1,14 @@
package me.skymc.tlm.module.sub; package me.skymc.tlm.module.sub;
import java.util.ArrayList; import me.skymc.taboolib.Main;
import java.util.LinkedList; import me.skymc.taboolib.TabooLib;
import java.util.List; import me.skymc.taboolib.inventory.ItemUtils;
import java.util.Set; import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.tlm.TLM;
import me.skymc.tlm.annotation.DisableConfig;
import me.skymc.tlm.inventory.TLMInventoryHolder;
import me.skymc.tlm.module.ITabooLibraryModule;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -13,14 +17,10 @@ import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import me.skymc.taboolib.Main; import java.util.ArrayList;
import me.skymc.taboolib.TabooLib; import java.util.LinkedList;
import me.skymc.taboolib.inventory.ItemUtils; import java.util.List;
import me.skymc.taboolib.message.MsgUtils; import java.util.Set;
import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.tlm.annotation.DisableConfig;
import me.skymc.tlm.inventory.TLMInventoryHolder;
import me.skymc.tlm.module.ITabooLibraryModule;
/** /**
* @author sky * @author sky
@ -28,158 +28,148 @@ import me.skymc.tlm.module.ITabooLibraryModule;
*/ */
@DisableConfig @DisableConfig
public class ModuleInventorySave implements ITabooLibraryModule, Listener { public class ModuleInventorySave implements ITabooLibraryModule, Listener {
private FileConfiguration conf;
@Override private FileConfiguration conf;
public String getName() {
return "InventorySave"; @Override
} public String getName() {
return "InventorySave";
@Override }
public void onEnable() {
reloadConfig(); @Override
} public void onEnable() {
reloadConfig();
@Override }
public void onReload() {
reloadConfig(); @Override
} public void onReload() {
reloadConfig();
public void reloadConfig() { }
conf = DataUtils.addPluginData("InventorySave", Main.getInst());
} public void reloadConfig() {
conf = DataUtils.addPluginData("InventorySave", Main.getInst());
/** }
* 保存玩家背包
* /**
* @param player 玩家 * 保存玩家背包
* @param name 名称 *
*/ * @param player 玩家
public void saveInventory(Player player, String name) { * @param name 名称
// 设置物品 */
for (int i = 0 ; i < (TabooLib.getVerint() > 10800 ? 41 : 40) ; i++) { public void saveInventory(Player player, String name) {
ItemStack item = player.getInventory().getItem(i); // 设置物品
conf.set(name + "." + i, item == null ? new ItemStack(Material.AIR) : item.clone()); for (int i = 0; i < (TabooLib.getVerint() > 10800 ? 41 : 40); i++) {
} ItemStack item = player.getInventory().getItem(i);
} conf.set(name + "." + i, item == null ? new ItemStack(Material.AIR) : item.clone());
}
/** }
* 覆盖玩家背包
* /**
* @param player 玩家 * 覆盖玩家背包
* @param name 名称 *
*/ * @param player 玩家
public void pasteInventory(Player player, String name) { * @param name 名称
pasteInventory(player, name, "null"); */
} public void pasteInventory(Player player, String name) {
pasteInventory(player, name, "null");
/** }
* 覆盖玩家背包
* /**
* @param player 玩家 * 覆盖玩家背包
* @param name 名称 *
* @param module 模式 * @param player 玩家
*/ * @param name 名称
public void pasteInventory(Player player, String name, String module) { * @param module 模式
// 如果背包不存在 */
if (!conf.contains(name)) { public void pasteInventory(Player player, String name, String module) {
MsgUtils.warn("模块执行异常: &4背包不存在"); // 如果背包不存在
MsgUtils.warn("模块: &4InventorySave"); if (!conf.contains(name)) {
MsgUtils.warn("位于: &4" + name); TLM.getInst().runtimeFall("InventorySave", "InventoryNotFound", name);
return; return;
} }
// 异常物品 // 异常物品
List<ItemStack> otherItem = new ArrayList<>(); List<ItemStack> otherItem = new ArrayList<>();
// 设置物品 // 设置物品
for (int i = 0 ; i < (TabooLib.getVerint() > 10800 ? 41 : 40) ; i++) { for (int i = 0; i < (TabooLib.getVerint() > 10800 ? 41 : 40); i++) {
try { try {
ItemStack item = (ItemStack) conf.get(name + "." + i); ItemStack item = (ItemStack) conf.get(name + "." + i);
// 如果原本有物品 // 如果原本有物品
if (!ItemUtils.isNull(player.getInventory().getItem(i))) { if (!ItemUtils.isNull(player.getInventory().getItem(i))) {
// 跳过 // 跳过
if (module.equalsIgnoreCase("-b")) { if (module.equalsIgnoreCase("-b")) {
continue; continue;
} }
// 给予 // 给予
else if (module.equalsIgnoreCase("-a")) { else if (module.equalsIgnoreCase("-a")) {
otherItem.add(item); otherItem.add(item);
continue; continue;
} }
} }
// 覆盖 // 覆盖
player.getInventory().setItem(i, item); player.getInventory().setItem(i, item);
} } catch (Exception e) {
catch (Exception e) { TLM.getInst().runtimeFall("InventorySave", "InventoryCoverFall", name);
MsgUtils.warn("模块执行异常: &4物品覆盖出错"); }
MsgUtils.warn("模块: &4InventorySave"); }
MsgUtils.warn("位于: &4" + name + ":" + i); // 循环异常物品
} for (ItemStack item : otherItem) {
} player.getInventory().addItem(item);
// 循环异常物品 }
for (ItemStack item : otherItem) { }
player.getInventory().addItem(item);
} /**
} * 获取背包内所有物品
*
/** * @param name 背包名称
* 获取背包内所有物品 * @return {@link List}
* */
* @param name 背包名称 public List<ItemStack> getItems(String name) {
* @return {@link List} // 如果背包不存在
*/ if (!conf.contains(name)) {
public List<ItemStack> getItems(String name) { TLM.getInst().runtimeFall("InventorySave", "InventoryNotFound", name);
// 如果背包不存在 return new LinkedList<>();
if (!conf.contains(name)) { }
MsgUtils.warn("模块执行异常: &4背包不存在");
MsgUtils.warn("模块: &4InventorySave"); List<ItemStack> items = new LinkedList<>();
MsgUtils.warn("位于: &4" + name); // 设置物品
return new LinkedList<>(); for (int i = 0; i < (TabooLib.getVerint() > 10800 ? 41 : 40); i++) {
} try {
ItemStack item = (ItemStack) conf.get(name + "." + i);
List<ItemStack> items = new LinkedList<>(); items.add(item);
// 设置物品 } catch (Exception e) {
for (int i = 0 ; i < (TabooLib.getVerint() > 10800 ? 41 : 40) ; i++) { TLM.getInst().runtimeFall("InventorySave", "ItemStackLoadFall", name);
try { }
ItemStack item = (ItemStack) conf.get(name + "." + i); }
items.add(item); return items;
} }
catch (Exception e) {
MsgUtils.warn("模块执行异常: &4物品获取出错"); /**
MsgUtils.warn("模块: &4InventorySave"); * 获取所有背包
MsgUtils.warn("位于: &4" + name + ":" + i); *
} * @return {@link Set}
} */
return items; public Set<String> getInventorys() {
} return conf.getConfigurationSection("").getKeys(false);
}
/**
* 获取所有背包 /**
* * 删除背包
* @return {@link Set} *
*/ * @param name 名称
public Set<String> getInventorys() { */
return conf.getConfigurationSection("").getKeys(false); public void deleteInventory(String name) {
} conf.set(name, null);
}
/**
* 删除背包 @EventHandler
* public void onClick(InventoryClickEvent e) {
* @param name 名称 if (!(e.getInventory().getHolder() instanceof TLMInventoryHolder)) {
*/ return;
public void deleteInventory(String name) { }
conf.set(name, null);
} TLMInventoryHolder holder = (TLMInventoryHolder) e.getInventory().getHolder();
if (holder.getModule().equals(getName())) {
@EventHandler e.setCancelled(true);
public void onClick(InventoryClickEvent e) { }
if (!(e.getInventory().getHolder() instanceof TLMInventoryHolder)) { }
return;
}
TLMInventoryHolder holder = (TLMInventoryHolder) e.getInventory().getHolder();
if (holder.getModule().equals(getName())) {
e.setCancelled(true);
}
}
} }

View File

@ -1,169 +1,166 @@
package me.skymc.tlm.module.sub; package me.skymc.tlm.module.sub;
import java.util.ArrayList; import me.skymc.taboolib.inventory.ItemUtils;
import java.util.List; import me.skymc.taboolib.other.DateUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.tlm.TLM;
import me.skymc.tlm.module.ITabooLibraryModule;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import me.skymc.taboolib.inventory.ItemUtils; import java.util.ArrayList;
import me.skymc.taboolib.message.MsgUtils; import java.util.List;
import me.skymc.taboolib.other.DateUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.tlm.module.ITabooLibraryModule;
/** /**
* @author sky * @author sky
* @since 2018年2月18日 下午12:13:55 * @since 2018年2月18日 下午12:13:55
*/ */
public class ModuleKits implements ITabooLibraryModule { public class ModuleKits implements ITabooLibraryModule {
private FileConfiguration data;
@Override private FileConfiguration data;
public String getName() {
return "Kits"; @Override
} public String getName() {
return "Kits";
@Override }
public void onEnable() {
data = DataUtils.addPluginData("ModuleKits", null); @Override
} public void onEnable() {
data = DataUtils.addPluginData("ModuleKits", null);
/** }
* 设置玩家是否领取礼包
* /**
* @param player 玩家 * 设置玩家是否领取礼包
*/ *
public void setPlayerReward(Player player, String kit, boolean reward) { * @param player 玩家
data.set(kit + "." + player.getName(), reward ? System.currentTimeMillis() : null); */
} public void setPlayerReward(Player player, String kit, boolean reward) {
data.set(kit + "." + player.getName(), reward ? System.currentTimeMillis() : null);
/** }
* 清空礼包数据
* /**
* @param kit 礼包 * 清空礼包数据
*/ *
public void resetKit(String kit) { * @param kit 礼包
data.set(kit, null); */
} public void resetKit(String kit) {
data.set(kit, null);
/** }
* 玩家是否领取礼包
* /**
* @param player 玩家 * 玩家是否领取礼包
* @param kit 礼包 *
* @return boolean * @param player 玩家
*/ * @param kit 礼包
public boolean isPlayerRewared(Player player, String kit) { * @return boolean
return data.contains(kit + "." + player.getName()); */
} public boolean isPlayerRewared(Player player, String kit) {
return data.contains(kit + "." + player.getName());
/** }
* 礼包是否在冷却中
* /**
* @param player * 礼包是否在冷却中
* @param kit *
* @return * @param player
*/ * @param kit
public boolean isPlayerCooldown(Player player, String kit) { * @return
return System.currentTimeMillis() - data.getLong(kit + "." + player.getName()) < getCooldown(kit); */
} public boolean isPlayerCooldown(Player player, String kit) {
return System.currentTimeMillis() - data.getLong(kit + "." + player.getName()) < getCooldown(kit);
/** }
* 礼包是否存在
* /**
* @param kit 礼包名 * 礼包是否存在
* @return boolean *
*/ * @param kit 礼包名
public boolean contains(String kit) { * @return boolean
return getConfig().contains("Kits." + kit); */
} public boolean contains(String kit) {
return getConfig().contains("Kits." + kit);
/** }
* 获取礼包冷却时间
* /**
* @param kit 礼包名 * 获取礼包冷却时间
* @return long *
*/ * @param kit 礼包名
public long getCooldown(String kit) { * @return long
return DateUtils.formatDate(getConfig().getString("Kits." + kit + ".Cooldown")); */
} public long getCooldown(String kit) {
return DateUtils.formatDate(getConfig().getString("Kits." + kit + ".Cooldown"));
/** }
* 获取礼包空间不足时的处理方式
* /**
* @param kit 礼包名 * 获取礼包空间不足时的处理方式
* @return boolean *
*/ * @param kit 礼包名
public Boolean isFullDrop(String kit) { * @return boolean
return getConfig().getBoolean("Kits." + kit + ".FullDrop"); */
} public Boolean isFullDrop(String kit) {
return getConfig().getBoolean("Kits." + kit + ".FullDrop");
/** }
* 礼包是否只能领取一次
* /**
* @param kit 礼包名 * 礼包是否只能领取一次
* @return boolean *
*/ * @param kit 礼包名
public boolean isDisposable(String kit) { * @return boolean
return getConfig().getBoolean("Kits." + kit + ".Disposable"); */
} public boolean isDisposable(String kit) {
return getConfig().getBoolean("Kits." + kit + ".Disposable");
/** }
* 获取礼包权限
* /**
* @param kit 礼包名 * 获取礼包权限
* @return String *
*/ * @param kit 礼包名
public String getPermission(String kit) { * @return String
return getConfig().getString("Kits." + kit + ".Permission"); */
} public String getPermission(String kit) {
return getConfig().getString("Kits." + kit + ".Permission");
/** }
* 获取礼包权限提示
* /**
* @param kit 礼包名 * 获取礼包权限提示
* @return String *
*/ * @param kit 礼包名
public String getPermissionMessage(String kit) { * @return String
return getConfig().getString("Kits." + kit + ".Permission-message").replace("&", "§"); */
} public String getPermissionMessage(String kit) {
return getConfig().getString("Kits." + kit + ".Permission-message").replace("&", "§");
/** }
* 获取礼包物品
* /**
* @param kit 礼包名 * 获取礼包物品
* @return {@link List} *
*/ * @param kit 礼包名
public List<ItemStack> getItems(String kit) { * @return {@link List}
List<ItemStack> items = new ArrayList<>(); */
for (String itemStr : getConfig().getStringList("Kits." + kit + ".Items")) { public List<ItemStack> getItems(String kit) {
ItemStack item = ItemUtils.getCacheItem(itemStr.split(" ")[0]); List<ItemStack> items = new ArrayList<>();
if (item != null) { for (String itemStr : getConfig().getStringList("Kits." + kit + ".Items")) {
item = item.clone(); ItemStack item = ItemUtils.getCacheItem(itemStr.split(" ")[0]);
try { if (item != null) {
item.setAmount(NumberUtils.getInteger(itemStr.split(" ")[1])); item = item.clone();
items.add(item); try {
} catch (Exception e) { item.setAmount(NumberUtils.getInteger(itemStr.split(" ")[1]));
MsgUtils.warn("模块配置载入异常: &4物品数量错误"); items.add(item);
MsgUtils.warn("模块: &4Kits"); } catch (Exception e) {
MsgUtils.warn("位于: &4" + itemStr); TLM.getInst().runtimeFall("Kits", "InvalidAmount", itemStr);
} }
} }
} }
return items; return items;
} }
/** /**
* 获取礼包命令 * 获取礼包命令
* *
* @param kit 礼包名 * @param kit 礼包名
* @return {@link List} * @return {@link List}
*/ */
public List<String> getCommands(String kit) { public List<String> getCommands(String kit) {
return getConfig().contains("Kits." + kit + ".Commands") ? getConfig().getStringList("Kits." + kit + ".Commands") : new ArrayList<>(); return getConfig().contains("Kits." + kit + ".Commands") ? getConfig().getStringList("Kits." + kit + ".Commands") : new ArrayList<>();
} }
} }

View File

@ -1,112 +1,109 @@
package me.skymc.tlm.module.sub; package me.skymc.tlm.module.sub;
import java.util.Calendar;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.other.DateUtils; import me.skymc.taboolib.other.DateUtils;
import me.skymc.taboolib.other.NumberUtils; import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.timecycle.TimeCycle; import me.skymc.taboolib.timecycle.TimeCycle;
import me.skymc.taboolib.timecycle.TimeCycleEvent; import me.skymc.taboolib.timecycle.TimeCycleEvent;
import me.skymc.taboolib.timecycle.TimeCycleInitializeEvent; import me.skymc.taboolib.timecycle.TimeCycleInitializeEvent;
import me.skymc.taboolib.timecycle.TimeCycleManager; import me.skymc.taboolib.timecycle.TimeCycleManager;
import me.skymc.tlm.TLM;
import me.skymc.tlm.module.ITabooLibraryModule; import me.skymc.tlm.module.ITabooLibraryModule;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import java.util.Calendar;
/** /**
* @author sky * @author sky
* @since 2018年2月17日 下午11:23:38 * @since 2018年2月17日 下午11:23:38
*/ */
public class ModuleTimeCycle implements ITabooLibraryModule, Listener { public class ModuleTimeCycle implements ITabooLibraryModule, Listener {
@Override @Override
public String getName() { public String getName() {
return "TimeCycle"; return "TimeCycle";
} }
@Override @Override
public void onEnable() { public void onEnable() {
// 载入检查器 // 载入检查器
loadCycles(); loadCycles();
} }
@Override @Override
public void onDisable() { public void onDisable() {
// 注销检查器 // 注销检查器
unloadCycles(); unloadCycles();
} }
@Override @Override
public void onReload() { public void onReload() {
// 注销检查器 // 注销检查器
unloadCycles(); unloadCycles();
// 载入检查器 // 载入检查器
loadCycles(); loadCycles();
} }
@EventHandler @EventHandler
public void onTimeCycleInitialize(TimeCycleInitializeEvent e) { public void onTimeCycleInitialize(TimeCycleInitializeEvent e) {
if (e.getCycle().getName().contains("tlm|")) { if (e.getCycle().getName().contains("tlm|")) {
// 获取名称 // 获取名称
String name = e.getCycle().getName().replace("tlm|", ""); String name = e.getCycle().getName().replace("tlm|", "");
// 如果有初始化时间配置 // 如果有初始化时间配置
if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseDate")) { if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseDate")) {
// 获取时间 // 获取时间
Calendar date = Calendar.getInstance(); Calendar date = Calendar.getInstance();
// 遍历初始化规则 // 遍历初始化规则
for (String typeStr : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseDate")) { for (String typeStr : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseDate")) {
try { try {
int type = (int) Calendar.class.getField(typeStr.split("=")[0]).get(Calendar.class); int type = (int) Calendar.class.getField(typeStr.split("=")[0]).get(Calendar.class);
date.set(type, NumberUtils.getInteger(typeStr.split("=")[1])); date.set(type, NumberUtils.getInteger(typeStr.split("=")[1]));
} catch (Exception err) { } catch (Exception ignored) {
MsgUtils.warn("模块配置载入异常: &4日期类型错误"); TLM.getInst().runtimeFall("TimeCycle", "DateFormatFall", typeStr);
MsgUtils.warn("模块: &4TimeCycle"); }
MsgUtils.warn("位于: &4" + typeStr); }
} e.setTimeLine(date.getTimeInMillis());
} }
e.setTimeLine(date.getTimeInMillis()); // 如果有初始化命令
} if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseCommand")) {
// 如果有初始化命令 // 遍历初始化命令
if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseCommand")) { for (String command : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseCommand")) {
// 遍历初始化命令 // 执行命令
for (String command : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseCommand")) { Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command));
// 执行命令 }
Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)); }
} }
} }
}
} @EventHandler
public void onTimeCycle(TimeCycleEvent e) {
@EventHandler if (e.getCycle().getName().contains("tlm|")) {
public void onTimeCycle(TimeCycleEvent e) { // 获取名称
if (e.getCycle().getName().contains("tlm|")) { String name = e.getCycle().getName().replace("tlm|", "");
// 获取名称 // 如果有更新命令
String name = e.getCycle().getName().replace("tlm|", ""); if (getConfig().contains("TimeCycle." + name + ".UpdateCommand")) {
// 如果有更新命令 // 遍历更新命令
if (getConfig().contains("TimeCycle." + name + ".UpdateCommand")) { for (String command : getConfig().getStringList("TimeCycle." + name + ".UpdateCommand")) {
// 遍历更新命令 // 执行命令
for (String command : getConfig().getStringList("TimeCycle." + name + ".UpdateCommand")) { Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command));
// 执行命令 }
Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)); }
} }
} }
}
} private void loadCycles() {
for (String name : getConfig().getConfigurationSection("TimeCycle").getKeys(false)) {
private void loadCycles() { TimeCycleManager.register(new TimeCycle("tlm|" + name, DateUtils.formatDate(getConfig().getString("TimeCycle." + name + ".Cycle")), Main.getInst()));
for (String name : getConfig().getConfigurationSection("TimeCycle").getKeys(false)) { }
TimeCycleManager.register(new TimeCycle("tlm|" + name, DateUtils.formatDate(getConfig().getString("TimeCycle." + name + ".Cycle")), Main.getInst())); }
}
} private void unloadCycles() {
for (TimeCycle cycle : TimeCycleManager.getTimeCycles()) {
private void unloadCycles() { if (cycle.getName().startsWith("tlm|")) {
for (TimeCycle cycle : TimeCycleManager.getTimeCycles()) { TimeCycleManager.cancel(cycle.getName());
if (cycle.getName().startsWith("tlm|")) { }
TimeCycleManager.cancel(cycle.getName()); }
} }
}
}
} }

View File

@ -1,5 +1,3 @@
VERSION: 2
TLIB: TLIB:
INJECTION-SUCCESS: '注入成功' INJECTION-SUCCESS: '注入成功'
INJECTION-FAILED: '注入失败' INJECTION-FAILED: '注入失败'
@ -60,6 +58,10 @@ ENTITY-UTILS:
FILE-UTILS: FILE-UTILS:
FALL-LOAD-CONFIGURATION: '&4配置文件载入失败!, 插件: &c{0}&4, 文件: &c{1}' FALL-LOAD-CONFIGURATION: '&4配置文件载入失败!, 插件: &c{0}&4, 文件: &c{1}'
DATA-UTILS:
SUCCESS-SAVE-DATA: '&7保存 &f{0} &7条插件数据, 耗时: &f{1} &7(ms)'
FALL-SAVE-FILE: '&4文件 &c{0}&4 保存失败, 原因: &c{1}'
ITEM-UTILS: ITEM-UTILS:
FALL-LOAD-ITEMS: '物品库载入失败: &4{0}' FALL-LOAD-ITEMS: '物品库载入失败: &4{0}'
FALL-LOAD-ATTRIBUTE: '&c{0} &4不是一个有效的属性名称, 输入 &c/tlib attributes&4 查看所有属性' FALL-LOAD-ATTRIBUTE: '&c{0} &4不是一个有效的属性名称, 输入 &c/tlib attributes&4 查看所有属性'
@ -70,11 +72,45 @@ ITEM-UTILS:
SUCCESS-LOAD-CACHES: '&7载入 &f{0} &7项缓存物品' SUCCESS-LOAD-CACHES: '&7载入 &f{0} &7项缓存物品'
SUCCESS-LOAD-NAMES: '&7载入 &f{0} &7项物品名称' SUCCESS-LOAD-NAMES: '&7载入 &f{0} &7项物品名称'
EMPTY-ITEM: '空' EMPTY-ITEM: '空'
LANGUAGE2:
FALL-NOTFOUND-FILE: '语言文件 {0} 不存在'
TIMECYCLE:
FALL-CYCLE-EXISTS: '注册周期管理器 §8{0}§c 失败, 原因: &4名称重复'
UPDATETASK:
VERSION-LATEST: '插件已是最新版, 无需更新!'
VERSION-OUTDATED:
- '&8####################################################'
- '&7 检测到有新的版本更新!'
- '&7 当前版本: &f{0}'
- '&7 最新版本: &f{1}'
- '&7 下载地址: &fhttp://www.mcbbs.net/thread-773065-1-1.html'
- '&7 开源地址: &fhttps://github.com/Bkm016/TabooLib/'
- '&8####################################################'
TABOOLIB-MODULE:
SUCCESS-LOADED: '&7载入 &f{0} &7个 &fTLM &7模块'
FALL-LOADED: '&4模块载入异常: &c{0}&4, 模块: &c{1}&4, 位于: &c{2}'
FALL-RUNTIME: '&4模块运行异常: &c{0}&4, 模块: &c{1}&4, 位于: &c{2}'
COMMANDS: COMMANDS:
GLOBAL: GLOBAL:
ONLY-PLAYER: '&8[&3&lTabooLib&8] &4控制台无法这么做' ONLY-PLAYER: '&8[&3&lTabooLib&8] &4控制台无法这么做'
ONLY-STORAGE-SQL: '&8[&3&lTabooLib&8] &4只有启用数据库储存时才能这么做' ONLY-STORAGE-SQL: '&8[&3&lTabooLib&8] &4只有启用数据库储存时才能这么做'
INTERNAL:
ONLY-PLAYER: '&8[&3&lTabooLib&8] §7指令 §f{0} §7只能由 §f{1} §7执行'
TYPE-PLAYER: 玩家
TYPE-CONSOLE: 控制台
ERROR-USAGE:
- '&8[&3&lTabooLib&8] §7指令 §f{0} §7参数不足'
- '&8[&3&lTabooLib&8] §7正确用法:'
- '&8[&3&lTabooLib&8] §7{1}'
ERROR-COMMAND:
- '&8[&3&lTabooLib&8] §7指令 §f{0} §7不存在'
- '&8[&3&lTabooLib&8] §7你可能想要:'
- '&8[&3&lTabooLib&8] §7{1}'
PARAMETER: PARAMETER:
UNKNOWN: '&8[&3&lTabooLib&8] &4指令错误' UNKNOWN: '&8[&3&lTabooLib&8] &4指令错误'
INSUFFICIENT: '&8[&3&lTabooLib&8] &4参数不足' INSUFFICIENT: '&8[&3&lTabooLib&8] &4参数不足'
@ -325,3 +361,52 @@ COMMANDS:
- '§f /{0} send §8[§7玩家/ALL§8] §8[§7语言§8] §8<§7变量§8> §6- §e发送语言提示' - '§f /{0} send §8[§7玩家/ALL§8] §8[§7语言§8] §8<§7变量§8> §6- §e发送语言提示'
- '§f /{0} reload §6- §e重载语言库' - '§f /{0} reload §6- §e重载语言库'
- '' - ''
TPLUGIN:
COMMAND-TITLE: '§e§l----- §6§lTabooLibPlugin Commands §b§l-----'
LIST:
DESCRIPTION: '列出插件'
LIST-PLUGIN:
- '&8[&3&lTabooLib&8] &7插件总数: &f{0}'
- '&8[&3&lTabooLib&8] &7插件列表: &f{1}'
INFO:
DESCRIPTION: '查询插件'
ARGUMENTS:
0: '名称'
INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在'
INFO-PLUGIN:
- '&8[&3&lTabooLib&8] &7插件名称: &f{0}'
- '&8[&3&lTabooLib&8] &7描述: &f{1}'
- '&8[&3&lTabooLib&8] &7作者: &f{2}'
- '&8[&3&lTabooLib&8] &7依赖: &f{3}'
- '&8[&3&lTabooLib&8] &7兼容: &f{4}'
- '&8[&3&lTabooLib&8] &7主类: &f{5}'
- '&8[&3&lTabooLib&8] &7版本: &f{6}'
- '&8[&3&lTabooLib&8] &7网站: &f{7}'
- '&8[&3&lTabooLib&8] &7命令: &f{8}'
LOAD:
DESCRIPTION: '载入插件'
ARGUMENTS:
0: '名称'
INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4已经载入'
LOAD-SUCCESS: '&8[&3&lTabooLib&8] &7插件已载入'
LOAD-FALL: '&8[&3&lTabooLib&8] &7插件载入失败'
UNLOAD:
DESCRIPTION: '卸载插件'
ARGUMENTS:
0: '名称'
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-FALL: '&8[&3&lTabooLib&8] &7插件卸载失败'
RELOAD:
DESCRIPTION: '重载插件'
ARGUMENTS:
0: '名称'
INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在'
INVALID-PLUGIN-IGNORED: '&8[&3&lTabooLib&8] &4插件 &c{0} &4无法操作'
DATABASE:
CONNECTION-ESTABLISHED: '成功连接到 {0} 数据库,连接池大小 {1}'
CONNECTION-ERROR: '连接到数据库错误:{0}'
VERSION: 4.0

View File

@ -18,6 +18,9 @@ commands:
tabooliblocale: tabooliblocale:
aliases: [taboolocale, tlocale] aliases: [taboolocale, tlocale]
permission: taboolib.admin permission: taboolib.admin
taboolibplugin:
aliases: [tabooplugin, tplugin]
permission: taboolib.admin
taboolibrarymodule: taboolibrarymodule:
aliases: [tlm] aliases: [tlm]