feat: 新增Sponge的部分支持(测试中)

Signed-off-by: 502647092 <admin@yumc.pw>
merge/1/HEAD
502647092 2017-10-26 21:01:24 +08:00
parent 4bb2c48021
commit e387863061
18 changed files with 437 additions and 221 deletions

6
.gitignore vendored
View File

@ -37,4 +37,8 @@
# Atlassian Stuff
/atlassian-ide-plugin.xml
/src/main/resources/cache/
/src/main/resources/cache/
# ThinkPHP
vendor/
composer.lock

21
pom.xml
View File

@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>pw.yumc</groupId>
<artifactId>MiaoScript</artifactId>
<version>1.1.4</version>
<version>1.1.5</version>
<developers>
<developer>
<id>502647092</id>
@ -49,7 +49,7 @@
</execution>
</executions>
</plugin>
<plugin>
<!--<plugin>
<groupId>com.github.wvengen</groupId>
<artifactId>proguard-maven-plugin</artifactId>
<version>2.0.13</version>
@ -71,7 +71,7 @@
</configuration>
</execution>
</executions>
</plugin>
</plugin>-->
</plugins>
</build>
<ciManagement>
@ -94,6 +94,10 @@
<id>yumc-repo</id>
<url>http://repo.yumc.pw/content/groups/public/</url>
</repository>
<repository>
<id>sponge</id>
<url>https://repo.spongepowered.org/maven/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
@ -114,6 +118,17 @@
<artifactId>YumCore</artifactId>
<type>jar</type>
<version>[1.8,)</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.spongepowered</groupId>
<artifactId>spongeapi</artifactId>
<version>6.0.0</version>
</dependency>
</dependencies>
</project>

View File

@ -26,6 +26,9 @@
-keepclassmembers class * implements net.md_5.bungee.api.plugin.Listener {
@net.md_5.bungee.event.EventHandler <methods>;
}
-keepclassmembers class * {
@org.spongepowered.api.event.Listener <methods>;
}
# -----保护继承事件不被清理-----
-keep class ** extends org.bukkit.event.Event {*;}
@ -46,6 +49,9 @@
-keepclassmembers class **.commands.annotation.** {<methods>;}
-keepclassmembers class * implements **.commands.interfaces.Executor {<methods>;}
# -----保护注解命令方法不被清理-----
-keep @org.spongepowered.api.plugin.Plugin class * {*;}
# -----保护注解NotProguard标记-----
-keep class **.NotProguard
-keep @**.NotProguard class * {*;}

View File

@ -6,13 +6,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import org.bukkit.plugin.Plugin;
import lombok.val;
import pw.yumc.YumCore.annotation.NotProguard;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.bukkit.P;
import pw.yumc.YumCore.bukkit.compatible.C;
import pw.yumc.YumCore.mc.MinecraftTools;
/**
@ -23,25 +18,15 @@ import pw.yumc.YumCore.mc.MinecraftTools;
*/
@NotProguard
public class Base {
public Plugin getPlugin() {
return P.instance;
}
public Class getClass(String name) throws ClassNotFoundException {
return Class.forName(name);
}
public Class getLog() {
return Log.class;
}
public String read(String path) throws IOException {
Log.fd("读取文件 %s ...", path);
return new String(Files.readAllBytes(new File(path).toPath()), "UTF-8");
}
public void save(String path, String content) throws IOException {
Log.fd("保存文件 %s ...", path);
File file = new File(path);
file.getParentFile().mkdirs();
Files.write(file.toPath(), content.getBytes("UTF-8"));
@ -54,7 +39,6 @@ public class Base {
public void delete(Path path) throws IOException {
val file = path.toFile();
if (!file.exists()) { return; }
Log.fd("删除文件 %s ...", path);
if (file.isDirectory()) {
for (Path f : Files.list(file.toPath()).collect(Collectors.toList())) {
delete(f);
@ -63,18 +47,6 @@ public class Base {
Files.delete(path);
}
public Class getActionBar() {
return C.ActionBar.class;
}
public Class getTitle() {
return C.Title.class;
}
public Class getPlayer() {
return C.Player.class;
}
public Class getTools() {
return MinecraftTools.class;
}

View File

@ -1,10 +1,6 @@
package pw.yumc.MiaoScript;
import java.io.File;
import java.io.InputStreamReader;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
@ -19,7 +15,6 @@ import pw.yumc.YumCore.commands.CommandSub;
import pw.yumc.YumCore.commands.annotation.Cmd;
import pw.yumc.YumCore.commands.annotation.Help;
import pw.yumc.YumCore.commands.interfaces.Executor;
import pw.yumc.YumCore.engine.MiaoScriptEngine;
/**
*
@ -28,33 +23,34 @@ import pw.yumc.YumCore.engine.MiaoScriptEngine;
* @since 2016829 7:50:39
*/
public class MiaoScript extends JavaPlugin implements Executor {
private MiaoScriptEngine engine;
private ScriptEngine engine;
@Override
@SneakyThrows
public void onEnable() {
new CommandSub("ms", this);
saveScript();
enableEngine();
engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getClassLoader(), getLogger());
}
@Cmd
@Help("执行 JS 代码")
@SneakyThrows
public void js(CommandSender sender, String script) {
result(sender, engine.eval(script));
result(sender, engine.getEngine().eval(script));
}
@Cmd
@Help("执行 JS 代码文件")
@SneakyThrows
public void file(CommandSender sender, String file) {
result(sender, engine.eval("load('" + new File(getDataFolder(), file).getCanonicalPath() + "')"));
result(sender, engine.getEngine().eval("load('" + new File(getDataFolder(), file).getCanonicalPath() + "')"));
}
@Cmd
@Help("重启脚本引擎")
public void reload(CommandSender sender) {
disableEngine();
engine.disableEngine();
val server = Bukkit.getServer();
try {
server.getScheduler().cancelTasks(this);
@ -65,7 +61,7 @@ public class MiaoScript extends JavaPlugin implements Executor {
} catch (Exception ex) {
Log.d("Error reload", ex);
}
enableEngine();
engine.enableEngine();
Log.sender(sender, "§bMiaoScript §eEngine §a重启完成!");
}
@ -82,34 +78,8 @@ public class MiaoScript extends JavaPlugin implements Executor {
P.saveFile("plugins");
}
private void enableEngine() {
Thread currentThread = Thread.currentThread();
ClassLoader previousClassLoader = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(getClassLoader());
try {
ScriptEngineManager manager = new ScriptEngineManager();
this.engine = new MiaoScriptEngine(manager, "nashorn");
this.engine.put("base", new Base());
this.engine.eval(new InputStreamReader(this.getResource("bios.js")));
engine.invokeFunction("boot", this);
} catch (Exception e) {
Log.d(e);
} finally {
currentThread.setContextClassLoader(previousClassLoader);
}
}
private void disableEngine() {
try {
engine.invokeFunction("disable");
} catch (ScriptException | NoSuchMethodException e) {
Log.w("脚本引擎关闭失败! %s:%s", e.getClass().getName(), e.getMessage());
Log.d(e);
}
}
@Override
public void onDisable() {
disableEngine();
engine.disableEngine();
}
}

View File

@ -0,0 +1,91 @@
package pw.yumc.MiaoScript;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Logger;
import javax.script.ScriptException;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.text.Text;
import com.google.inject.Inject;
import lombok.SneakyThrows;
/**
* Created with IntelliJ IDEA
*
* @author
* Created on 2017/10/25 20:35.
*/
@Plugin(id = "miaoscript", name = "MiaoScript", version = "1.0", authors = "喵♂呜")
public class MiaoScriptSponge {
private ScriptEngine engine;
@Inject
private Logger logger;
@Inject
@ConfigDir(sharedRoot = false)
private File pluginConfigDir;
@Listener
public void onInit(GameInitializationEvent event) {
}
private CommandSpec main() {
return CommandSpec.builder()
.description(Text.of("喵式脚本主命令"))
.permission("MiaoScript.admin")
.child(js(), "js")
.child(file(), "file")
.build();
}
private CommandSpec js() {
return CommandSpec.builder()
.description(Text.of("执行JS命令"))
.arguments(GenericArguments.onlyOne(GenericArguments.remainingJoinedStrings(Text.of("js"))))
.executor((src, args) -> {
try {
engine.getEngine().eval(args.<String>getOne("js").orElse(""));
} catch (ScriptException e) {
e.printStackTrace();
}
return CommandResult.success();
})
.build();
}
private CommandSpec file() {
return CommandSpec.builder()
.description(Text.of("执行JS文件"))
.arguments(GenericArguments.onlyOne(GenericArguments.remainingJoinedStrings(Text.of("js"))))
.executor((src, args) -> {
try {
engine.getEngine().eval(new FileReader(new File(pluginConfigDir, args.<String>getOne("js").orElse(""))));
} catch (ScriptException | IOException e) {
e.printStackTrace();
}
return CommandResult.success();
})
.build();
}
@Listener
@SneakyThrows
public void onStart(GameStartedServerEvent event) {
Sponge.getServer().getConsole();
Sponge.getCommandManager().register(this, main(), "ms", "mscript", "MiaoScript");
engine = new ScriptEngine(pluginConfigDir.getCanonicalPath(), Thread.currentThread().getContextClassLoader(), logger);
}
}

View File

@ -0,0 +1,54 @@
package pw.yumc.MiaoScript;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import pw.yumc.YumCore.engine.MiaoScriptEngine;
/**
* Created with IntelliJ IDEA
*
* @author
* Created on 2017/10/25 21:01.
*/
public class ScriptEngine {
private String root;
private ClassLoader classLoader;
private Logger logger;
private MiaoScriptEngine engine;
public ScriptEngine(String root, ClassLoader classLoader, Logger logger) {
this.root = root;
this.classLoader = classLoader;
this.logger = logger;
enableEngine();
}
public void enableEngine() {
try {
ScriptEngineManager manager = new ScriptEngineManager(null);
this.engine = new MiaoScriptEngine(manager, "nashorn");
this.engine.put("base", new Base());
this.engine.eval(new InputStreamReader(classLoader.getResourceAsStream("bios.js")));
engine.invokeFunction("boot", root, logger);
} catch (Exception e) {
logger.log(Level.SEVERE, "MiaoScript 启动失败!", e);
}
}
public void disableEngine() {
try {
engine.invokeFunction("disable");
} catch (ScriptException | NoSuchMethodException e) {
logger.log(Level.SEVERE, "MiaoScript 关闭失败!", e);
}
}
public MiaoScriptEngine getEngine() {
return engine;
}
}

View File

@ -1,26 +1,62 @@
'use strict';
var log = base.getLog().static;
var log;
var boot;
var disable;
/**
* 初始化框架引擎
*/
(function () {
boot = function (plugin) {
boot = function (root, logger) {
log = logger;
// 开发环境下初始化
var root = "src/main/resources";
if (plugin !== null) {
// noinspection JSUnresolvedVariable
root = plugin.dataFolder.canonicalPath;
}
root = root || "src/main/resources";
// 解压文件到根目录
release(root, "[core|modules]/.*", true);
release(root, "plugins/.*");
load(root + '/core/init.js');
try {
init(root);
} catch (ex) {
log.w("MiaoScript 初始化失败! %s", ex);
throw ex;
} finally {
disable = disablePlugins
}
};
function release(root, regex, replace) {
print(Array.prototype.join.call(arguments, ' '));
var Files = Java.type("java.nio.file.Files");
var Paths = Java.type("java.nio.file.Paths");
var StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
var classLoader = java.lang.Thread.currentThread().getContextClassLoader();
var url = classLoader.getResource("plugin.yml");
if (url === null) {
return;
}
var upath = url.getFile().substring(url.getFile().indexOf("/") + 1);
var jarPath = java.net.URLDecoder.decode(upath.substring(0, upath.indexOf('!')));
if (!Files.exists(Paths.get(jarPath))) {
jarPath = "/" + jarPath;
}
try {
var jar = new java.util.jar.JarFile(jarPath);
var r = new RegExp(regex);// "[core|modules]/.*"
jar.stream().forEach(function (entry) {
if (!entry.isDirectory()) {
if (r.test(entry.name)) {
var path = Paths.get(root, entry.name);
var parentFile = path.toFile().parentFile;
if (!parentFile.exists()) {
parentFile.mkdirs();
}
Files.copy(classLoader.getResourceAsStream(entry.name), path, StandardCopyOption[replace ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
}
}
})
} catch (ex) {
} finally {
}
}
})();

View File

@ -2,9 +2,10 @@
* 控制台输出类
*/
/*global base*/
(function(global){
(function (global) {
var Arrays = Java.type('java.util.Arrays');
var Level = Java.type('java.util.logging.Level');
var String = Java.type('java.lang.String');
var Console = function (name) {
Object.defineProperty(this, 'name', {
get: function () {
@ -17,38 +18,66 @@
});
this.name = name;
this.log = function () {
log.i(this.name + Array.prototype.join.call(arguments, ' '));
},
log.info(this.name + Array.prototype.join.call(arguments, ' '));
};
this.warn = function () {
log.w(this.name + Array.prototype.join.call(arguments, ' '));
},
log.warning(this.name + Array.prototype.join.call(arguments, ' '));
};
this.error = function () {
log.log(Level.SEVERE, this.name + Array.prototype.join.call(arguments, ' '));
},
this.debug = function () {
log.d(this.name + Array.prototype.join.call(arguments, ' '));
}
this.sender = function () {
var sender = arguments[0];
if (!(sender instanceof org.bukkit.command.CommandSender)) { console.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!") }
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(this.prefix + args.join(' '));
}
this.ex = function (ex) {
log.console('§4' + ex);
var track = ex.getStackTrace();
if (track.class) { track = Arrays.asList(track) }
if (track.forEach) {
track.forEach(function (stack) {
if (stack.className.startsWith('<')) {
log.console(' §e位于 §c%s => §c%s §4行%s', stack.fileName, stack.methodName, stack.lineNumber);
} else {
log.console(' §e位于 §c%s.%s(§4%s:%s§c)', stack.className, stack.methodName, stack.fileName, stack.lineNumber);
};
switch (DetectServerType) {
case ServerType.Bukkit:
this.sender = function () {
var sender = arguments[0];
if (!(sender instanceof org.bukkit.command.CommandSender)) {
console.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
}
});
}
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(this.prefix + args.join(' '));
};
this.console = function () {
this.sender(MServer.consoleSender, Array.prototype.join.call(arguments, ' '));
};
break;
case ServerType.Sponge:
this.sender = function () {
var Text = Java.type("org.spongepowered.api.text.Text");
var sender = arguments[0];
if (!(sender instanceof org.spongepowered.api.command.CommandSource)) {
console.error("第一个参数未实现 org.spongepowered.api.command.CommandSource 无法发送消息!")
}
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(Text.of(this.prefix + args.join(' ')));
};
this.console = function () {
this.sender(MServer.server.console, Array.prototype.join.call(arguments, ' '));
};
break;
default:
this.sender = function () {
throw Error("console.sender 不支持的服务器类型: " + DetectServerType);
};
this.console = function () {
throw Error("console.console 不支持的服务器类型: " + DetectServerType);
};
}
}
this.debug = this.log;
this.ex = function (ex) {
this.console('§4' + ex);
var track = ex.getStackTrace();
if (track.class) {
track = Arrays.asList(track)
}
track.forEach(function (stack) {
if (stack.className.startsWith('<')) {
this.console(String.format(' §e位于 §c%s => §c%s §4行%s', stack.fileName, stack.methodName, stack.lineNumber));
} else {
this.console(String.format(' §e位于 §c%s.%s(§4%s:%s§c)', stack.className, stack.methodName, stack.fileName, stack.lineNumber));
}
}.bind(this));
}
};
global.Console = Console;
global.console = new Console();
})(global)
})(global);

View File

@ -0,0 +1,22 @@
/**
* 服务器探测类
*/
/*global base*/
var ServerType = {
Bukkit: 1,
Sponge: 2
};
var MServer;
var DetectServerType = ServerType.Bukkit;
try {
MServer = Java.type("org.bukkit.Bukkit");
DetectServerType = ServerType.Bukkit;
} catch (ex) {
// IGNORE
}
try {
MServer = Java.type("org.spongepowered.api.Sponge");
DetectServerType = ServerType.Sponge;
} catch (ex) {
// IGNORE
}

View File

@ -18,6 +18,7 @@ function init(root) {
function loadCore() {
// 加载基础模块
load(root + '/core/ext.js');
load(root + '/core/detect.js');
load(root + '/core/console.js');
}

View File

@ -7,7 +7,7 @@
'use strict';
var File = Java.type("java.io.File");
var separatorChar = File.separatorChar;
var paths = [parent, '', parent + separatorChar + 'core', parent + separatorChar + 'modules'];
var paths = [parent, parent + separatorChar + 'core', parent + separatorChar + 'modules'];
/**
* 解析模块名称为文件
@ -17,21 +17,22 @@
* 核心目录 /core
* 模块目录 /modules
* @param name 模块名称
* @param parent 父目录
*/
function resolve(name, parent) {
if (_canonical(name)) {
name = _canonical(name);
}
// 解析本地目录
if(name.startsWith('./') || name.startsWith('../')){
if (name.startsWith('./') || name.startsWith('../')) {
return resolveAsFile(parent, name) || resolveAsDirectory(parent, name) || undefined;
} else {
// 查找可能存在的路径
for(var i in paths) {
for (var i in paths) {
var path = paths[i];
var result = resolveAsFile(path, name) || resolveAsDirectory(path, name);
if (result) {
return result;
return result;
}
}
}
@ -43,7 +44,7 @@
* @returns {*}
*/
function resolveAsFile(dir, file) {
var file = ext.notNull(dir) ? new File(dir, file) : new File(file);
file = ext.notNull(dir) ? new File(dir, file) : new File(file);
if (file.isFile()) {
return file;
}
@ -52,13 +53,13 @@
return ef;
}
}
/**
* 解析目录
* @returns {*}
*/
function resolveAsDirectory(dir, file) {
var dir = ext.notNull(dir) ? new File(dir, file) : new File(file);
dir = ext.notNull(dir) ? new File(dir, file) : new File(file);
var _package = new File(dir, 'package.json');
if (_package.exists()) {
var json = JSON.parse(base.read(_package));
@ -80,7 +81,8 @@
/**
* 预编译模块
* @param file
* @param file JS文件
* @param optional 附加选项
* @returns {Object}
*/
function compileJs(file, optional) {
@ -98,13 +100,14 @@
/**
* 编译模块
* @param id
* @param name
* @param file
* @param id 模块ID
* @param name 模块名称
* @param file 模块文件
* @param optional 附加选项
* @returns {Object}
*/
function compileModule(id, name, file, optional) {
log.fd('加载模块 %s 位于 %s Optional %s', name, id, optional.toJson());
console.debug('加载模块 %s 位于 %s Optional %s', name, id, optional.toJson());
// noinspection JSUnresolvedVariable
var module = {
id: id,
@ -117,11 +120,11 @@
compiledWrapper.apply(module.exports, [
module, module.exports, module.require, file.parentFile, file
]);
log.fd('模块 %s 编译成功!', name);
console.debug('模块 %s 编译成功!', name);
module.loaded = true;
} catch (ex) {
log.console("§4警告! §b模块 §a%s §4编译失败! ERR: %s", name, ex);
log.d(ex);
console.console("§4警告! §b模块 §a%s §4编译失败! ERR: %s", name, ex);
console.ex(ex);
}
return module;
}
@ -145,16 +148,17 @@
* 加载模块
* @param name 模块名称
* @param path 路径
* @param optional 附加选项
* @returns {*}
* @private
*/
function _require(name, path, optional) {
var file = _canonical(name) ? name : resolve(name, path);
if (file === undefined) {
log.console("§c模块 §a%s §c加载失败! §4未找到该模块!", name);
return {exports:{}};
console.console("§c模块 §a%s §c加载失败! §4未找到该模块!", name);
return {exports: {}};
}
if (!optional) optional = { cache: true }
if (!optional) optional = {cache: true};
// 重定向文件名称和类型
name = file.name.split(".")[0];
var id = _canonical(file);
@ -185,6 +189,6 @@
parent = new File(parent);
}
var cacheModules = [];
log.d("初始化 require 模块组件 父目录 %s", _canonical(parent));
console.debug("初始化 require 模块组件 父目录 %s", _canonical(parent));
return exports(parent);
});

View File

@ -19,14 +19,14 @@ exports.nmsVersion = Bukkit.server.class.name.split('.')[3];
*/
exports.nmsCls = function (name) {
return Java.type(['net.minecraft.server', exports.nmsVersion, name].join('.'));
}
};
exports.command = function (name) {
return Server.getPluginCommand(name);
}
};
/**
* 获取玩家
*/
exports.player = function(){
exports.player = function () {
switch (arguments.length) {
case 0:
return undefined;
@ -35,18 +35,18 @@ exports.player = function(){
default:
return Bukkit.getPlayerExtra(arguments[0]);
}
}
};
/**
* 获取在线玩家
*/
exports.players = function(){
exports.players = function () {
switch (arguments.length) {
case 1:
return Bukkit.onlinePlayers.forEach(arguments[0]);
default:
return Bukkit.onlinePlayers;
}
}
};
/**
* 插件管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}

View File

@ -13,13 +13,13 @@ var PluginCommand = Java.type('org.bukkit.command.PluginCommand');
var StringUtil = Java.type('org.bukkit.util.StringUtil');
var ArrayList = Java.type('java.util.ArrayList');
var Arrays = Java.type('java.util.Arrays')
var Arrays = Java.type('java.util.Arrays');
function enable(jsp){
function enable(jsp) {
var commands = jsp.description.commands;
if(commands){
if (commands) {
var pluginCmds = [];
for (var name in commands){
for (var name in commands) {
var command = commands[name];
if (typeof command !== 'object') continue;
var newCmd = create(jsp, name);
@ -29,7 +29,7 @@ function enable(jsp){
if (command.permission) newCmd.setPermission(command.permission);
if (command['permission-message']) newCmd.setPermissionMessage(command['permission-message']);
pluginCmds.push(newCmd);
log.d('插件 %s 注册命令 %s ...', jsp.description.name, name);
console.debug('插件 %s 注册命令 %s ...', jsp.description.name, name);
}
commandMap.registerAll(jsp.description.name, Arrays.asList(pluginCmds));
}
@ -43,7 +43,7 @@ function create(jsp, name) {
return register(jsp, ref.on(PluginCommand).create(name, plugin).get());
}
function register(jsp, cmd){
function register(jsp, cmd) {
commandMap.register(jsp.description.name, cmd);
return cmd;
}
@ -59,13 +59,13 @@ function register(jsp, cmd){
function on(jsp, name, exec) {
var c = get(name) || create(jsp, name);
log.d('插件 %s 设置命令 %s(%s) 执行器 ...', jsp.description.name, name, c);
console.debug('插件 %s 设置命令 %s(%s) 执行器 ...', jsp.description.name, name, c);
if (exec.cmd) {
c.setExecutor(function (sender, cmd, command, args) {
try {
return exec.cmd(sender, command, args);
} catch (ex) {
log.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常 §4%s', sender.name, jsp.description.name, command, Java.from(args).join(' '), ex);
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常 §4%s', sender.name, jsp.description.name, command, Java.from(args).join(' '), ex);
console.ex(ex);
}
});
@ -78,14 +78,14 @@ function on(jsp, name, exec) {
StringUtil.copyPartialMatches(token, Arrays.asList(exec.tab(sender, command, args)), completions);
return completions;
} catch (ex) {
log.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6补全时发生异常 §4%s',sender.name ,jsp.description.name, command, Java.from(args).join(' '), ex);
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6补全时发生异常 §4%s', sender.name, jsp.description.name, command, Java.from(args).join(' '), ex);
console.ex(ex);
}
});
}
}
exports.enable = enable
exports.enable = enable;
exports.on = on;
exports.off = function () {

View File

@ -46,7 +46,7 @@ function mapEventName() {
if (isVaildEvent(clz)) {
// noinspection JSUnresolvedVariable
var simpleName = clz.simpleName.toLowerCase();
log.fd("Mapping Event [%s] => %s", clz.name, simpleName);
console.debug("Mapping Event [%s] => %s", clz.name, simpleName);
mapEvent[simpleName] = clz;
count++;
}
@ -85,12 +85,12 @@ function isVaildEvent(clz) {
function listen(jsp, event, exec, priority, ignoreCancel) {
var name = jsp.description.name;
if (ext.isNull(name)) throw new TypeError('插件名称为空 请检查传入参数!');
var eventCls = mapEvent[event] || mapEvent[event.toLowerCase()] || mapEvent[event +'Event'] || mapEvent[event.toLowerCase() + 'event'];
var eventCls = mapEvent[event] || mapEvent[event.toLowerCase()] || mapEvent[event + 'Event'] || mapEvent[event.toLowerCase() + 'event'];
if (!eventCls) {
try {
eventCls = base.getClass(eventCls);
} catch (ex) {
log.w("事件 %s 未找到!", event);
console.warn("事件 %s 未找到!", event);
return;
}
}
@ -115,10 +115,10 @@ function listen(jsp, event, exec, priority, ignoreCancel) {
EventPriority[priority],
new EventExecutor({
execute: function (listener, event) {
try{
try {
exec(event);
} catch (ex){
log.console('§6插件 §b%s §6处理 §d%s §6事件时发生异常 §4%s', name, event.class.simpleName, ex);
} catch (ex) {
console.console('§6插件 §b%s §6处理 §d%s §6事件时发生异常 §4%s', name, event.class.simpleName, ex);
console.ex(ex);
}
}
@ -131,20 +131,20 @@ function listen(jsp, event, exec, priority, ignoreCancel) {
var off = {
event: eventCls,
listener: listener,
off: function(){
off: function () {
ref.on(this.event).call('getHandlerList').get().unregister(this.listener);
log.d('插件 %s 注销事件 %s', name, this.event.simpleName);
console.debug('插件 %s 注销事件 %s', name, this.event.simpleName);
}
}
listeners.push(off);
// noinspection JSUnresolvedVariable
log.d('插件 %s 注册事件 %s 方法 %s', name, eventCls.simpleName, exec.name === '' ? '匿名方法' : exec.name);
console.debug('插件 %s 注册事件 %s 方法 %s', name, eventCls.simpleName, exec.name === '' ? '匿名方法' : exec.name);
return off;
}
var mapEvent = [];
// 映射事件名称
log.i('Bukkit 事件映射完毕 共计 %s 个事件!', mapEventName().toFixed(0));
console.info('Bukkit 事件映射完毕 共计 %s 个事件!', mapEventName().toFixed(0));
module.exports = {
on: listen,

View File

@ -12,37 +12,37 @@ var manager = require('./bukkit').plugin.manager;
var Permission = Java.type("org.bukkit.permissions.Permission");
var PermissionDefault = Java.type('org.bukkit.permissions.PermissionDefault');
function enable (plugin) {
function enable(plugin) {
var permissions = plugin.description.permissions;
if(permissions){
for (var name in permissions){
var permission = permissions[name];
if (typeof permission !== 'object') continue;
var desc = permission.description;
var def = permission.default || 'OP';
try {
manager.addPermission(new Permission(name, desc, PermissionDefault.getByName(def)));
} catch (ex) {
// ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined!
}
log.d('插件 %s 注册权限 %s Default %s ...', plugin.description.name, name, def);
}
if (permissions) {
for (var name in permissions) {
var permission = permissions[name];
if (typeof permission !== 'object') continue;
var desc = permission.description;
var def = permission.default || 'OP';
try {
manager.addPermission(new Permission(name, desc, PermissionDefault.getByName(def)));
} catch (ex) {
// ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined!
}
console.debug('插件 %s 注册权限 %s Default %s ...', plugin.description.name, name, def);
}
}
}
function disable (plugin) {
function disable(plugin) {
var permissions = plugin.description.permissions;
if(permissions){
for (var name in permissions){
try {
manager.removePermission(name);
} catch (ex) {
// ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined!
}
log.d('插件 %s 注销权限 %s ...', plugin.description.name, name);
}
if (permissions) {
for (var name in permissions) {
try {
manager.removePermission(name);
} catch (ex) {
// ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined!
}
console.debug('插件 %s 注销权限 %s ...', plugin.description.name, name);
}
}
}
exports.enable = enable
exports.disable = disable
exports.enable = enable;
exports.disable = disable;

View File

@ -18,9 +18,9 @@ var permission = require('./permission');
function loadPlugins(dir) {
var plugin = fs.file(root, dir);
if (!plugin) {
log.i("首次加载 创建文件夹 %s ...", plugin);
console.info("首次加载 创建文件夹 %s ...", plugin);
} else {
log.i("开始扫描 %s 下的插件 ...", plugin);
console.info("开始扫描 %s 下的插件 ...", plugin);
createUpdate(plugin);
var files = [];
fs.list(plugin).forEach(function (file) {
@ -71,8 +71,8 @@ function loadJsPlugins(files) {
function loadPlugin(file) {
var update = fs.file(fs.file(file.parentFile, 'update'), file.name);
if (update.exists()) {
log.i('自动升级插件 %s', file.name);
fs.move(update, file, true);
console.info('自动升级插件 %s', file.name);
fs.move(update, file, true);
}
var plugin = require(file, {
cache: false,
@ -80,16 +80,16 @@ function loadPlugin(file) {
return beforeLoadHook(origin);
}
});
log.d("插件编译结果: %s", plugin.toJson());
console.debug("插件编译结果: %s", plugin.toJson());
var desc = plugin.description;
if (!desc || !desc.name) {
log.w("文件 %s 不存在 description 描述信息 无法加载插件!", file);
console.warn("文件 %s 不存在 description 描述信息 无法加载插件!", file);
} else {
initPlugin(file, plugin);
afterLoadHook(plugin);
plugins.push(plugin);
plugins[plugin.description.name] = plugin;
log.i('载入插件 %s 版本 %s By %s', desc.name, desc.version || '未知', desc.author || '未知');
console.info('载入插件 %s 版本 %s By %s', desc.name, desc.version || '未知', desc.author || '未知');
}
return plugin;
}
@ -110,7 +110,7 @@ function afterLoadHook(plugin) {
// 给 console 添加插件名称
plugin.console.name = plugin.description.name;
// 赋值 self
for (var i in plugin){
for (var i in plugin) {
plugin.self[i] = plugin[i];
}
}
@ -118,15 +118,19 @@ function afterLoadHook(plugin) {
/**
* 初始化插件内容(提供config,__DATA__等参数)
*/
function initPlugin(file, plugin){
function initPlugin(file, plugin) {
// 初始化 __FILE__
plugin.__FILE__ = file;
// 初始化 __DATA__
plugin.__DATA__ = fs.file(file.parentFile, plugin.description.name);
// 初始化 getDataFolder()
plugin.getDataFolder = function() { return plugin.__DATA__; }
plugin.getDataFolder = function () {
return plugin.__DATA__;
};
// 初始化 getFile()
plugin.getFile = function(name) { return fs.file(plugin.getDataFolder(), name); }
plugin.getFile = function (name) {
return fs.file(plugin.getDataFolder(), name);
};
// 初始化插件配置相关方法
initPluginConfig(plugin);
@ -138,7 +142,7 @@ function initPlugin(file, plugin){
/**
* 初始化插件配置
*/
function initPluginConfig(plugin){
function initPluginConfig(plugin) {
// 初始化 config
plugin.configFile = plugin.getFile('config.yml');
/**
@ -146,7 +150,7 @@ function initPluginConfig(plugin){
* @constructor
* @constructor (file|string)
*/
plugin.getConfig = function() {
plugin.getConfig = function () {
switch (arguments.length) {
case 0:
return plugin.config;
@ -157,34 +161,34 @@ function initPluginConfig(plugin){
}
return yaml.safeLoad(base.read(file));
}
}
};
/**
* 重载配置文件
* @constructor
* @constructor (file|string)
*/
plugin.reloadConfig = function() {
plugin.reloadConfig = function () {
plugin.config = plugin.getConfig(plugin.configFile);
}
};
/**
* 保存配置文件
* @constructor
* @constructor (file, content)
*/
plugin.saveConfig = function() {
plugin.saveConfig = function () {
switch (arguments.length) {
case 0:
plugin.configFile.parentFile.mkdirs()
plugin.configFile.parentFile.mkdirs();
base.save(plugin.configFile, plugin.config.toYaml());
break;
case 2:
base.save(arguments[0], arguments[1].toYaml());
break;
}
}
};
if (plugin.configFile.isFile()) {
plugin.config = plugin.getConfig('config.yml');
} else if (plugin.description.config ){
} else if (plugin.description.config) {
plugin.config = plugin.description.config;
plugin.saveConfig();
}
@ -195,20 +199,28 @@ function runAndCatch(jsp, exec, ext) {
try {
// 绑定方法的this到插件自身
exec.bind(jsp)();
if (ext) { ext(); }
if (ext) {
ext();
}
} catch (ex) {
log.console('§6插件 §b%s §6执行 §d%s §6方法时发生错误 §4%s', jsp.description.name, exec.name, ex.message);
console.console('§6插件 §b%s §6执行 §d%s §6方法时发生错误 §4%s', jsp.description.name, exec.name, ex.message);
console.ex(ex);
}
}
}
function checkAndGet(args) {
if (args.length === 0) { return plugins; }
if (args.length === 0) {
return plugins;
}
var name = args[0];
// 如果是插件 则直接返回
if (name.description) { return [name]; }
if (!exports.plugins[name]) { throw new Error("插件 " + name + " 不存在!"); }
if (name.description) {
return [name];
}
if (!exports.plugins[name]) {
throw new Error("插件 " + name + " 不存在!");
}
return [exports.plugins[name]];
}
@ -220,7 +232,7 @@ exports.init = function (plugin, path) {
if (plugin !== null) {
// 如果过plugin不等于null 则代表是正式环境
exports.$ = plugin;
log.i("初始化 MiaoScript 插件系统 版本: %s", plugin.description.version);
console.info("初始化 MiaoScript 插件系统 版本: %s", plugin.description.version);
}
loadPlugins(path);
};
@ -231,7 +243,7 @@ exports.enable = function () {
checkAndGet(arguments).forEach(function (p) runAndCatch(p, p.enable));
};
exports.disable = function () {
checkAndGet(arguments).forEach(function (p) runAndCatch(p, p.disable, function(){
checkAndGet(arguments).forEach(function (p) runAndCatch(p, p.disable, function () {
event.disable(p);
// task.cancel();
}));

View File

@ -49,7 +49,7 @@ function load() {
function enable() {
command.on(self, 'mtag', {
cmd: function cmd (sender, command, args){
cmd: function cmd(sender, command, args) {
var subcommand = args[0];
switch (subcommand) {
case 'reload':
@ -59,18 +59,18 @@ function enable() {
break;
}
},
tab: function tab (sender, command, args){
tab: function tab(sender, command, args) {
return ['reload'];
}
})
});
bukkit.players(function (p) fakeTag.set(p));
event.on(self, 'PlayerJoin', function (event) fakeTag.set(event.player));
var entityUpdate = function (event) {
var player = event.entity || event.player;
if(player instanceof org.bukkit.entity.Player){
setTimeout(function () {
fakeTag.update(player);
}, 1);
if (player instanceof org.bukkit.entity.Player) {
setTimeout(function () {
fakeTag.update(player);
}, 1);
}
};
event.on(self, 'EntityRegainHealth', entityUpdate, false);
@ -92,14 +92,14 @@ function FakeTag(name) {
var PacketPlayOutScoreboardScore = bukkit.nmsCls('PacketPlayOutScoreboardScore');
var PacketPlayOutScoreboardObjective = bukkit.nmsCls('PacketPlayOutScoreboardObjective');
var PacketPlayOutScoreboardDisplayObjective = bukkit.nmsCls('PacketPlayOutScoreboardDisplayObjective');
var scoreboardManager = bukkit.$.scoreboardManager;
var mainScoreboard = scoreboardManager.mainScoreboard.handle;
try {
// 注册tag对象
mainScoreboard.registerObjective(name, new ScoreboardBaseCriteria(name));
} catch (ex){
} catch (ex) {
// ignore 忽略创建错误 eg: java.lang.IllegalArgumentException: An objective with the name 'xxxxx' already exists!
}
var objective = mainScoreboard.getObjective(name);
@ -118,24 +118,24 @@ function FakeTag(name) {
sendPacket(player, cache.objective);
sendPacket(player, cache.display);
this.update(player);
}
this.update = function (player){
};
this.update = function (player) {
var score = mainScoreboard.getPlayerScoreForObjective(player.name, objective);
score.setScore(player.getHealth());
var scorePack = new PacketPlayOutScoreboardScore(score);
//把其他玩家缓存的包发给这个玩家
bukkit.players(function (t) {
sendPacket(t, scorePack);
if (t.name != player.name) {
if (t.name !== player.name) {
var outher = mainScoreboard.getPlayerScoreForObjective(t.name, objective);
outher.setScore(t.getHealth());
sendPacket(player, new PacketPlayOutScoreboardScore(outher));
}
});
}
this.disable = function (){
};
this.disable = function () {
// 注销tag对象
mainScoreboard.unregisterObjective(objective);
}