Compare commits
46 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f3c799531 | |||
| 3389dbd566 | |||
| 54604e10b8 | |||
| d7247bae19 | |||
| 3ee2dcad0b | |||
| bc19021c63 | |||
| e9a4f2f351 | |||
| 9be9c400ad | |||
| 8eaf789bce | |||
| 7d6f6124b1 | |||
| e06fcc29e9 | |||
| 79ece8db63 | |||
| 66c1d25888 | |||
| ca8d4778bb | |||
| 7dcc5ed45a | |||
| 91d2d836fc | |||
| e5e1bb70a1 | |||
| e93a53aa9f | |||
| e3bceda06b | |||
| 9367e8c2c9 | |||
| 31c7ea2a29 | |||
| 2589633069 | |||
| bc17e2f376 | |||
| 20749d3381 | |||
| 6261b85413 | |||
| da9d590374 | |||
| 0af3ca8c79 | |||
| 561d5b60e8 | |||
| 878a5368af | |||
| 018b972aea | |||
| 4138cf9448 | |||
| 646176b43c | |||
| 506184a104 | |||
| 392f01d509 | |||
| 75b892e1c0 | |||
| c2d825eed0 | |||
| 393e63c017 | |||
| 46d6748f31 | |||
| b6803ed01c | |||
| bbfc70fdd6 | |||
| e28af3fbbc | |||
| 14eef46e67 | |||
| 1c4f512c89 | |||
| a8ae60625b | |||
| e7bc14294e | |||
| 4750f31b6e |
@@ -21,3 +21,4 @@ wallaby.js
|
||||
.theia
|
||||
type_definitions
|
||||
tsconfig.tsbuildinfo
|
||||
*.tsbuildinfo
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
@@ -10,6 +10,7 @@
|
||||
"stream": true
|
||||
},
|
||||
"publish": {
|
||||
"access": "public",
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,14 +12,14 @@
|
||||
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
|
||||
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
|
||||
"ug": "yarn upgrade-interactive --latest",
|
||||
"np": "lerna exec \"npm publish --registry https://registry.npmjs.org\" --scope=\"@ccms/!(client|plugins)\"",
|
||||
"np": "lerna exec \"npm publish --access=public --registry https://registry.npmjs.org\" --scope=\"@ccms/!(client|plugins)\"",
|
||||
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
|
||||
"lp": "lerna publish"
|
||||
"lp": "lerna publish --registry https://registry.npmjs.org"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"devDependencies": {
|
||||
"lerna": "^3.21.0"
|
||||
"lerna": "^3.22.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/amqp",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript amqp package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,14 +19,17 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0",
|
||||
"@ccms/nashorn": "^0.8.0"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/common": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.3",
|
||||
"@javatypes/amqp-client": "^0.0.2",
|
||||
"@javatypes/spring-amqp": "^0.0.2",
|
||||
"@javatypes/spring-rabbit": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/api",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,16 +19,16 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0",
|
||||
"@ccms/ployfill": "^0.8.0",
|
||||
"@ccms/common": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3",
|
||||
"@ccms/ployfill": "^0.9.3",
|
||||
"base64-js": "^1.3.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/base64-js": "^1.2.5",
|
||||
"@types/base64-js": "^1.3.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { injectable } from "@ccms/container";
|
||||
import { injectable, inject, provideSingleton } from "@ccms/container"
|
||||
|
||||
export namespace channel {
|
||||
/**
|
||||
@@ -17,32 +17,32 @@ export namespace channel {
|
||||
* @param exec 执行器
|
||||
*/
|
||||
listen(plugin: any, channel: string, exec: ChannelListener) {
|
||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!');
|
||||
let name = plugin.description.name;
|
||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!')
|
||||
let name = plugin.description.name
|
||||
let listener = this.register(channel, exec)
|
||||
if (!this.listenerMap[name]) this.listenerMap[name] = [];
|
||||
if (!this.listenerMap[name]) this.listenerMap[name] = []
|
||||
let offExec = () => {
|
||||
this.unregister(channel, listener);
|
||||
console.debug(`[${name}] unregister channel ${channel}`);
|
||||
};
|
||||
this.unregister(channel, listener)
|
||||
console.debug(`[${name}] unregister channel ${channel}`)
|
||||
}
|
||||
var off = {
|
||||
channel,
|
||||
listener,
|
||||
off: offExec
|
||||
};
|
||||
this.listenerMap[name].push(off);
|
||||
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`);
|
||||
return off;
|
||||
}
|
||||
this.listenerMap[name].push(off)
|
||||
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`)
|
||||
return off
|
||||
}
|
||||
/**
|
||||
* 关闭插件注册的通道
|
||||
* @param plugin 插件
|
||||
*/
|
||||
disable(plugin: any) {
|
||||
var channelCache = this.listenerMap[plugin.description.name];
|
||||
var channelCache = this.listenerMap[plugin.description.name]
|
||||
if (channelCache) {
|
||||
channelCache.forEach(t => t.off());
|
||||
delete this.listenerMap[plugin.description.name];
|
||||
channelCache.forEach(t => t.off())
|
||||
delete this.listenerMap[plugin.description.name]
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -63,4 +63,156 @@ export namespace channel {
|
||||
*/
|
||||
abstract unregister(channel: string, listener?: any): void
|
||||
}
|
||||
export namespace proxy {
|
||||
const CHANNEL_NAME = "BungeeCord"
|
||||
const ByteArrayOutputStream = Java.type('java.io.ByteArrayOutputStream')
|
||||
const DataOutputStream = Java.type('java.io.DataOutputStream')
|
||||
const ByteStreams = Java.type('com.google.common.io.ByteStreams')
|
||||
namespace bungeecord {
|
||||
export class SubChannelBuilder {
|
||||
private channel: Channel
|
||||
private player: any
|
||||
private params: string[]
|
||||
constructor(channel: Channel, player: any) {
|
||||
this.channel = channel
|
||||
this.player = player
|
||||
this.params = []
|
||||
}
|
||||
connect(server: string) {
|
||||
this.params.push("Connect")
|
||||
this.params.push(server)
|
||||
}
|
||||
connectOther(player: string, server: string) {
|
||||
this.params.push("ConnectOther")
|
||||
this.params.push(player)
|
||||
this.params.push(server)
|
||||
}
|
||||
ip() {
|
||||
this.params.push("IP")
|
||||
}
|
||||
ipOther(player: string) {
|
||||
this.params.push("IPOther")
|
||||
this.params.push(player)
|
||||
}
|
||||
playerCount(server: string | "ALL") {
|
||||
this.params.push("PlayerCount")
|
||||
this.params.push(server)
|
||||
}
|
||||
/**
|
||||
* Get a list of players connected on a certain server, or on ALL the servers.
|
||||
* @param server count server
|
||||
* Response:
|
||||
* String server = in.readUTF(); // The name of the server you got the player list of, as given in args.
|
||||
* String[] playerList = in.readUTF().split(", ");
|
||||
*/
|
||||
playerList(server: string | "ALL") {
|
||||
this.params.push("PlayerList")
|
||||
this.params.push(server)
|
||||
}
|
||||
/**
|
||||
* Get a list of server name strings, as defined in BungeeCord's config.yml
|
||||
* Response:
|
||||
* String[] serverList = in.readUTF().split(", ");
|
||||
*/
|
||||
getServers() {
|
||||
this.params.push("GetServers")
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Get this server's name, as defined in BungeeCord's config.yml
|
||||
*/
|
||||
getServer() {
|
||||
this.params.push("GetServer")
|
||||
return this.finalSend()
|
||||
}
|
||||
broadcast(message: string) {
|
||||
this.message("ALL", message)
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Send a message (as in, a chat message) to the specified player.
|
||||
* @param player who reciver message
|
||||
* @param message message content
|
||||
*/
|
||||
message(player: string | "ALL", message: string) {
|
||||
this.params.push("Message")
|
||||
this.params.push(player)
|
||||
this.params.push(message)
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Send a raw message (as in, a chat message) to the specified player. The advantage of this method over Message is that you can include click events and hover events.
|
||||
* @param player who reciver message
|
||||
* @param message message content
|
||||
*/
|
||||
messageRaw(player: string | "ALL", json: string) {
|
||||
this.params.push("MessageRaw")
|
||||
this.params.push(player)
|
||||
this.params.push(json)
|
||||
return this.finalSend()
|
||||
}
|
||||
forwardAll(channel: string, data: any) {
|
||||
this.forward("ALL", channel, data)
|
||||
}
|
||||
/**
|
||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||
* Remember, the sending and receiving server(s) need to have a player online.
|
||||
* @param server reciver
|
||||
* @param channel channelName
|
||||
* @param data data
|
||||
*/
|
||||
forward(server: string | "ALL", channel: string, data: any) {
|
||||
this.params.push("Forward")
|
||||
this.params.push(server)
|
||||
this.params.push(channel)
|
||||
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||
* Remember, the sending and receiving server(s) need to have a player online.
|
||||
* @param server reciver
|
||||
* @param channel channelName
|
||||
* @param data data
|
||||
*/
|
||||
forwardToPlayer(server: string | "ALL", channel: string, data: any) {
|
||||
this.params.push("Forward")
|
||||
this.params.push(server)
|
||||
this.params.push(channel)
|
||||
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
|
||||
return this.finalSend()
|
||||
}
|
||||
generic(...args: string[]) {
|
||||
args && this.params.concat(...args)
|
||||
return this.finalSend()
|
||||
}
|
||||
private send(...middlewares: ((out: java.io.DataOutputStream) => void)[]) {
|
||||
let byteArray = new ByteArrayOutputStream()
|
||||
let out = new DataOutputStream(byteArray)
|
||||
this.params.forEach(utf => out.writeUTF(utf))
|
||||
for (let middleware of middlewares) {
|
||||
middleware(out)
|
||||
}
|
||||
this.channel.send(this.player, CHANNEL_NAME, byteArray.toByteArray())
|
||||
}
|
||||
private finalSend() {
|
||||
return {
|
||||
send: this.send.bind(this)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@provideSingleton(BungeeCord)
|
||||
export class BungeeCord {
|
||||
@inject(Channel)
|
||||
private channel: Channel
|
||||
/**
|
||||
* 获得代理
|
||||
* @param player 玩家
|
||||
*/
|
||||
for(player: any): bungeecord.SubChannelBuilder {
|
||||
return new bungeecord.SubChannelBuilder(this.channel, player)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
31
packages/api/src/chat.ts
Normal file
31
packages/api/src/chat.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
export namespace chat {
|
||||
@injectable()
|
||||
export abstract class Chat {
|
||||
/**
|
||||
* sendJsonChat
|
||||
* @param sender reciver
|
||||
* @param json json
|
||||
* @param type chat Type 0: chat 1: system 2: actionBar
|
||||
*/
|
||||
sendJson(sender: any, json: string | object, type = 0) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
sendMessage(sender: any, message: string) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
sendActionBar(sender: any, message: string) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
clearActionBar(sender: any) {
|
||||
this.sendActionBar(sender, '')
|
||||
}
|
||||
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
clearTitle(sender: any) {
|
||||
this.sendTitle(sender, '', '', 0, 0, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,9 @@ export namespace command {
|
||||
this.onTabComplete(plugin, cmd, exec.tab)
|
||||
}
|
||||
}
|
||||
public tabComplete(sender: any, input: string, index?: number): string[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
/**
|
||||
* 取消命令注册
|
||||
* @param plugin 插件
|
||||
|
||||
@@ -97,10 +97,11 @@ export class MiaoScriptConsole implements Console {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = null
|
||||
let sourceLine = base.read(fileName).split('\n')
|
||||
let lastLine = sourceLine[sourceLine.length - 1]
|
||||
// lastLine is similar //# sourceMappingURL=data:application/json;base64,
|
||||
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||
let sourceContent = null
|
||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
||||
if (sourceMappingURL.startsWith('data:application/jsonbase64,')) {
|
||||
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||
} else if (sourceMappingURL.startsWith('http')) {
|
||||
// TODO
|
||||
@@ -122,6 +123,9 @@ export class MiaoScriptConsole implements Console {
|
||||
}
|
||||
} catch (error) {
|
||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
return {
|
||||
fileName,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import i18n from '@ccms/i18n'
|
||||
import { injectable, unmanaged } from '@ccms/container'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread');
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
|
||||
export namespace event {
|
||||
/**
|
||||
@@ -30,7 +30,7 @@ export namespace event {
|
||||
protected baseEventDir = '';
|
||||
|
||||
constructor(@unmanaged() baseEventDir: string) {
|
||||
this.baseEventDir = baseEventDir;
|
||||
this.baseEventDir = baseEventDir
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -39,74 +39,74 @@ export namespace event {
|
||||
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
|
||||
*/
|
||||
mapEventName() {
|
||||
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')); }
|
||||
let count = 0;
|
||||
let jar = this.getJarFile(this.baseEventDir);
|
||||
let entries = jar.entries();
|
||||
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')) }
|
||||
let count = 0
|
||||
let jar = this.getJarFile(this.baseEventDir)
|
||||
let entries = jar.entries()
|
||||
while (entries.hasMoreElements()) {
|
||||
let entry = entries.nextElement();
|
||||
let name = entry.name;
|
||||
let entry = entries.nextElement()
|
||||
let name = entry.name
|
||||
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
||||
// replace name to qualifiedName
|
||||
let qualifiedName = name.replaceAll('/', '.');
|
||||
let qualifiedName = name.replaceAll('/', '.')
|
||||
try {
|
||||
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
|
||||
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6))
|
||||
if (this.isValidEvent(clazz)) {
|
||||
let simpleName = this.class2Name(clazz).toLowerCase();
|
||||
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }));
|
||||
this.mapEvent[simpleName] = clazz;
|
||||
count++;
|
||||
let simpleName = this.class2Name(clazz).toLowerCase()
|
||||
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }))
|
||||
this.mapEvent[simpleName] = clazz
|
||||
count++
|
||||
}
|
||||
} catch (ex) {
|
||||
//ignore already loaded class
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
return count
|
||||
}
|
||||
|
||||
getJarFile(resource: string, loader?: any) {
|
||||
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource);
|
||||
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource)
|
||||
if (dirs.hasMoreElements()) {
|
||||
let url = dirs.nextElement();
|
||||
if (url.protocol === "jar") { return url.openConnection().jarFile; }
|
||||
let url = dirs.nextElement()
|
||||
if (url.protocol === "jar") { return url.openConnection().jarFile }
|
||||
}
|
||||
throw new Error(i18n.translate("ms.api.event.resource.not.found", { resource }))
|
||||
}
|
||||
|
||||
class2Name(clazz: any) {
|
||||
return clazz.simpleName;
|
||||
return clazz.simpleName
|
||||
}
|
||||
|
||||
name2Class(name: any, event: string) {
|
||||
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
|
||||
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']
|
||||
if (!eventCls) {
|
||||
try {
|
||||
eventCls = base.getClass(eventCls);
|
||||
this.mapEvent[event] = eventCls;
|
||||
eventCls = base.getClass(eventCls)
|
||||
this.mapEvent[event] = eventCls
|
||||
} catch (ex) {
|
||||
console.i18n("ms.api.event.not.found", { name, event })
|
||||
return;
|
||||
return
|
||||
}
|
||||
}
|
||||
return eventCls;
|
||||
return eventCls
|
||||
}
|
||||
|
||||
execute(name, exec, eventCls) {
|
||||
return (...args: any[]) => {
|
||||
try {
|
||||
let event = args[args.length - 1];
|
||||
let event = args[args.length - 1]
|
||||
if (eventCls.isAssignableFrom(event.getClass())) {
|
||||
let time = Date.now()
|
||||
exec(event);
|
||||
let cost = Date.now() - time;
|
||||
exec(event)
|
||||
let cost = Date.now() - time
|
||||
if (cost > 20) {
|
||||
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||
}
|
||||
}
|
||||
} catch (ex) {
|
||||
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
||||
console.ex(ex);
|
||||
console.ex(ex)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,34 +120,33 @@ export namespace event {
|
||||
* @param ignoreCancel
|
||||
*/
|
||||
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
|
||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"));
|
||||
var name = plugin.description.name;
|
||||
var eventCls = this.name2Class(name, event);
|
||||
if (!eventCls) { return; }
|
||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"))
|
||||
var name = plugin.description.name
|
||||
var eventCls = this.name2Class(name, event)
|
||||
if (!eventCls) { return }
|
||||
if (typeof priority === 'boolean') {
|
||||
ignoreCancel = priority;
|
||||
priority = EventPriority.NORMAL;
|
||||
ignoreCancel = priority
|
||||
priority = EventPriority.NORMAL
|
||||
}
|
||||
priority = priority || EventPriority.NORMAL;
|
||||
ignoreCancel = ignoreCancel || false;
|
||||
priority = priority || EventPriority.NORMAL
|
||||
ignoreCancel = ignoreCancel || false
|
||||
// @ts-ignore
|
||||
let executor = exec.name || exec.executor || '[anonymous]'
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
|
||||
var listenerMap = this.listenerMap;
|
||||
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel)
|
||||
var listenerMap = this.listenerMap
|
||||
// add to cache Be used for close plugin to close event
|
||||
if (!listenerMap[name]) listenerMap[name] = [];
|
||||
var offExec = () => {
|
||||
this.unregister(eventCls, listener);
|
||||
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls) }));
|
||||
};
|
||||
var off = {
|
||||
event: eventCls,
|
||||
listener: listener,
|
||||
off: offExec
|
||||
};
|
||||
listenerMap[name].push(off);
|
||||
if (!listenerMap[name]) listenerMap[name] = []
|
||||
var off = () => {
|
||||
if (off['offed']) return
|
||||
off['offed'] = true
|
||||
this.unregister(eventCls, listener)
|
||||
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls), exec: executor }))
|
||||
}
|
||||
listenerMap[name].push(off)
|
||||
// noinspection JSUnresolvedVariable
|
||||
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls) }));
|
||||
return off;
|
||||
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls), exec: executor }))
|
||||
return off
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -155,10 +154,10 @@ export namespace event {
|
||||
* @param plugin 插件
|
||||
*/
|
||||
disable(plugin: any) {
|
||||
var eventCache = this.listenerMap[plugin.description.name];
|
||||
var eventCache = this.listenerMap[plugin.description.name]
|
||||
if (eventCache) {
|
||||
eventCache.forEach(t => t.off());
|
||||
delete this.listenerMap[plugin.description.name];
|
||||
eventCache.forEach(off => off())
|
||||
delete this.listenerMap[plugin.description.name]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,7 +165,7 @@ export namespace event {
|
||||
* 判断
|
||||
* @param clazz 事件类
|
||||
*/
|
||||
abstract isValidEvent(clazz: any): boolean;
|
||||
abstract isValidEvent(clazz: any): boolean
|
||||
/**
|
||||
* 注册事件
|
||||
* @param eventCls 事件类
|
||||
@@ -174,12 +173,12 @@ export namespace event {
|
||||
* @param priority 优先级
|
||||
* @param ignoreCancel 是否忽略已取消的事件
|
||||
*/
|
||||
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
|
||||
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any
|
||||
/**
|
||||
* 取消监听事件
|
||||
* @param event 事件
|
||||
* @param listener 监听器
|
||||
*/
|
||||
abstract unregister(event: any, listener: any): void;
|
||||
abstract unregister(event: any, listener: any): void
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import "@ccms/nashorn"
|
||||
|
||||
export * from './chat'
|
||||
export * from './task'
|
||||
export * from './event'
|
||||
export * from './console'
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
export namespace plugin {
|
||||
/**
|
||||
* MiaoScript Plugin
|
||||
@@ -11,25 +13,56 @@ export namespace plugin {
|
||||
* Runtime Plugin Instance
|
||||
*/
|
||||
export const PluginInstance = Symbol("PluginInstance")
|
||||
/**
|
||||
* MiaoScript Plugin Manager Symbol
|
||||
*/
|
||||
export const PluginManager = Symbol("PluginManager")
|
||||
/**
|
||||
* MiaoScript Plugin Manager Interface
|
||||
*/
|
||||
export interface PluginManager {
|
||||
scan(folder: string): void
|
||||
build(): void
|
||||
loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
|
||||
load(...args: any[]): void
|
||||
enable(...args: any[]): void
|
||||
disable(...args: any[]): void
|
||||
reload(...args: any[]): void
|
||||
getPlugin(name: string): plugin.Plugin
|
||||
getPlugins(): Map<string, plugin.Plugin>
|
||||
@injectable()
|
||||
export abstract class PluginManager {
|
||||
abstract scan(folder: string): void
|
||||
abstract build(): void
|
||||
abstract loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
|
||||
abstract load(...args: any[]): void
|
||||
abstract enable(...args: any[]): void
|
||||
abstract disable(...args: any[]): void
|
||||
abstract reload(...args: any[]): void
|
||||
abstract getPlugin(name: string): plugin.Plugin
|
||||
abstract getPlugins(): Map<string, plugin.Plugin>
|
||||
}
|
||||
export const PluginScanner = Symbol("PluginScanner")
|
||||
/**
|
||||
* 插件加载元信息
|
||||
*/
|
||||
export interface PluginLoadMetadata {
|
||||
/**
|
||||
* 插件加载类型
|
||||
*/
|
||||
type: string
|
||||
/**
|
||||
* 插件文件
|
||||
*/
|
||||
file?: string
|
||||
/**
|
||||
* 插件实例
|
||||
*/
|
||||
instance?: any
|
||||
/**
|
||||
* 插件元信息
|
||||
*/
|
||||
metadata?: PluginMetadata
|
||||
/**
|
||||
* 插件扫描器
|
||||
*/
|
||||
scanner: PluginScanner
|
||||
/**
|
||||
* 插件加载器
|
||||
*/
|
||||
loader?: PluginLoader
|
||||
/**
|
||||
* 是否已加载
|
||||
*/
|
||||
loaded?: boolean
|
||||
[key: string]: any
|
||||
}
|
||||
/**
|
||||
* 插件扫描器
|
||||
*/
|
||||
@@ -39,15 +72,20 @@ export namespace plugin {
|
||||
*/
|
||||
type: string
|
||||
/**
|
||||
* 扫描插件 返回插件加载列表
|
||||
* 扫描插件目录 返回插件加载元信息列表
|
||||
* @param target 扫描目标
|
||||
*/
|
||||
scan(target: any): string[]
|
||||
scan(target: any): PluginLoadMetadata[]
|
||||
/**
|
||||
* 读取插件 返回插件加载元信息
|
||||
* @param target
|
||||
*/
|
||||
read(target: any): PluginLoadMetadata
|
||||
/**
|
||||
* 加载扫描到的目标
|
||||
* @param target 加载目标
|
||||
*/
|
||||
load(target: any): any
|
||||
load(target: PluginLoadMetadata): PluginLoadMetadata
|
||||
}
|
||||
export const PluginLoader = Symbol("PluginLoader")
|
||||
/**
|
||||
@@ -63,32 +101,32 @@ export namespace plugin {
|
||||
* @param target 加载目标
|
||||
* @param result 扫描器加载的结果
|
||||
*/
|
||||
require(target: any, result: any): PluginMetadata
|
||||
require(loadMetadata: PluginLoadMetadata): PluginLoadMetadata
|
||||
/**
|
||||
* 构建插件
|
||||
* @param metadata 插件元信息
|
||||
*/
|
||||
build(metadata: any): Plugin
|
||||
build(metadata: PluginMetadata): Plugin
|
||||
/**
|
||||
* Load 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
load(plugin: Plugin): void
|
||||
load?(plugin: Plugin): void
|
||||
/**
|
||||
* Enable 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
enable(plugin: Plugin): void
|
||||
enable?(plugin: Plugin): void
|
||||
/**
|
||||
* Disable 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
disable(plugin: Plugin): void
|
||||
disable?(plugin: Plugin): void
|
||||
/**
|
||||
* Reload 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
reload(plugin: Plugin): void
|
||||
reload?(plugin: Plugin): void
|
||||
}
|
||||
export interface Plugin {
|
||||
description: PluginMetadata
|
||||
@@ -109,21 +147,21 @@ export namespace plugin {
|
||||
}
|
||||
export interface PluginMetadata extends BaseMetadata {
|
||||
/**
|
||||
* 插件名称
|
||||
* 插件名称 不填默认为类名
|
||||
*/
|
||||
name: string
|
||||
name?: string
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
prefix?: string
|
||||
/**
|
||||
* 插件版本
|
||||
* 插件版本 不填默认为 1.0.0
|
||||
*/
|
||||
version: string
|
||||
version?: string
|
||||
/**
|
||||
* 插件版本
|
||||
* 插件作者 不填默认为 Unknow
|
||||
*/
|
||||
author: string | string[]
|
||||
author?: string | string[]
|
||||
/**
|
||||
* 插件源文件 必须指定为 __filename
|
||||
*/
|
||||
@@ -133,13 +171,9 @@ export namespace plugin {
|
||||
*/
|
||||
type?: string
|
||||
/**
|
||||
* 插件扫描器
|
||||
* 插件加载信息
|
||||
*/
|
||||
scanner?: PluginScanner
|
||||
/**
|
||||
* 插件加载器
|
||||
*/
|
||||
loader?: PluginLoader
|
||||
loadMetadata?: PluginLoadMetadata
|
||||
/**
|
||||
* 插件本体
|
||||
*/
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
import { injectable } from '@ccms/container'
|
||||
import { injectable, inject } from '@ccms/container'
|
||||
|
||||
import { NativePluginManager } from './native_plugin'
|
||||
import { constants } from '../../constants'
|
||||
|
||||
export { NativePluginManager } from './native_plugin'
|
||||
|
||||
export namespace server {
|
||||
/**
|
||||
* Runtime ServerType
|
||||
@@ -13,10 +15,6 @@ export namespace server {
|
||||
* Runtime Console
|
||||
*/
|
||||
export const Console = Symbol("Console")
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
export const Server = Symbol("Server")
|
||||
/**
|
||||
* Runtime Server Instance
|
||||
*/
|
||||
@@ -24,47 +22,24 @@ export namespace server {
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
export interface Server {
|
||||
getVersion(): string
|
||||
getPlayer(name: string): any
|
||||
getOnlinePlayers(): any[]
|
||||
getConsoleSender(): any
|
||||
getService(service: string): any
|
||||
dispatchCommand(sender: string | any, command: string): boolean
|
||||
dispatchConsoleCommand(command: string): boolean
|
||||
getPluginsFolder(): string
|
||||
getNativePluginManager(): NativePluginManager
|
||||
getDedicatedServer?(): any
|
||||
getNettyPipeline(): any
|
||||
getRootLogger(): any
|
||||
sendJson(sender: string | any, json: object | string): void
|
||||
tabComplete?(sender: string | any, input: string, index?: number): string[]
|
||||
}
|
||||
@injectable()
|
||||
export abstract class ReflectServer implements server.Server {
|
||||
protected pipeline: any
|
||||
protected rootLogger: any
|
||||
|
||||
constructor() {
|
||||
this.reflect()
|
||||
}
|
||||
|
||||
export abstract class Server {
|
||||
getVersion(): string {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getPlayer(name: string) {
|
||||
getPlayer(name: string): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getOnlinePlayers(): any[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getConsoleSender() {
|
||||
getConsoleSender(): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getService(service: string) {
|
||||
getService(service: string): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchCommand(sender: any, command: string): boolean {
|
||||
dispatchCommand(sender: string | any, command: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
@@ -76,21 +51,43 @@ export namespace server {
|
||||
getNativePluginManager(): NativePluginManager {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getDedicatedServer() {
|
||||
getDedicatedServer?(): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getNettyPipeline() {
|
||||
getNettyPipeline(): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getRootLogger() {
|
||||
getRootLogger(): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
sendJson(sender: any, json: string | object): void {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
@injectable()
|
||||
export class ServerChecker {
|
||||
@inject(ServerType)
|
||||
private serverType: string
|
||||
check(servers: string[]) {
|
||||
// Not set servers -> allow
|
||||
if (!servers || !servers.length) return true
|
||||
// include !type -> deny
|
||||
let denyServers = servers.filter(svr => svr.startsWith("!"))
|
||||
if (denyServers.length !== 0) {
|
||||
return !denyServers.includes(`!${this.serverType}`)
|
||||
} else {
|
||||
// only include -> allow
|
||||
return servers.includes(this.serverType)
|
||||
}
|
||||
}
|
||||
tabComplete?(sender: any, input: string, index?: number): string[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
@injectable()
|
||||
export abstract class ReflectServer extends server.Server {
|
||||
protected pipeline: any
|
||||
protected rootLogger: any
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this.reflect()
|
||||
}
|
||||
|
||||
protected reflect() {
|
||||
try {
|
||||
let consoleServer = this.getDedicatedServer()
|
||||
|
||||
@@ -1,34 +1,62 @@
|
||||
import { plugin } from './index'
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
export namespace task {
|
||||
export const TaskManager = Symbol('TaskManager')
|
||||
export interface TaskManager {
|
||||
@injectable()
|
||||
export abstract class TaskManager {
|
||||
protected cacheTasks = new Map<string, task.Task[]>()
|
||||
|
||||
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
||||
if (!this.cacheTasks.has(plugin.description.name)) {
|
||||
this.cacheTasks.set(plugin.description.name, [])
|
||||
}
|
||||
this.cacheTasks.get(plugin.description.name).push(task)
|
||||
return task
|
||||
}
|
||||
protected pluginDisable(plugin: plugin.Plugin) {
|
||||
if (this.cacheTasks.has(plugin.description.name)) {
|
||||
this.cacheTasks.get(plugin.description.name).forEach(task => task.cancel())
|
||||
this.cacheTasks.delete(plugin.description.name)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 创建任务
|
||||
* @param func 任务内容
|
||||
*/
|
||||
create(func: Function): task.Task;
|
||||
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
||||
let task = this.create0(func)
|
||||
if (plugin) { return this.pluginCreate(plugin, task) }
|
||||
return task
|
||||
}
|
||||
abstract create0(func: Function): task.Task
|
||||
/**
|
||||
* 在主线程执行代码
|
||||
* @param func 执行内容
|
||||
*/
|
||||
callSyncMethod(func: Function): any;
|
||||
abstract callSyncMethod(func: Function): any
|
||||
/**
|
||||
* 关闭任务管理器
|
||||
*/
|
||||
disable();
|
||||
disable(plugin?: plugin.Plugin) {
|
||||
if (plugin) { return this.pluginDisable(plugin) }
|
||||
this.disable0()
|
||||
}
|
||||
abstract disable0()
|
||||
}
|
||||
/**
|
||||
* 任务抽象
|
||||
*/
|
||||
export abstract class Task {
|
||||
protected plugin: any;
|
||||
protected func: Function;
|
||||
protected plugin: any
|
||||
protected func: Function
|
||||
protected isAsync: boolean = false;
|
||||
protected laterTime: number = 0;
|
||||
protected interval: number = 0;
|
||||
|
||||
constructor(plugin: any, func: Function) {
|
||||
this.plugin = plugin;
|
||||
this.func = func;
|
||||
this.plugin = plugin
|
||||
this.func = func
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,8 +64,8 @@ export namespace task {
|
||||
* @param isAsync 是否异步
|
||||
*/
|
||||
async(isAsync: boolean = true): task.Task {
|
||||
this.isAsync = isAsync;
|
||||
return this;
|
||||
this.isAsync = isAsync
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -45,8 +73,8 @@ export namespace task {
|
||||
* @param tick 延时 Tick
|
||||
*/
|
||||
later(tick: number): task.Task {
|
||||
this.laterTime = tick;
|
||||
return this;
|
||||
this.laterTime = tick
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,16 +82,23 @@ export namespace task {
|
||||
* @param tick 循环时间 Tick
|
||||
*/
|
||||
timer(tick: number): task.Task {
|
||||
this.interval = tick;
|
||||
return this;
|
||||
this.interval = tick
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消任务
|
||||
*/
|
||||
cancel(): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
|
||||
protected run(...args: any[]): void {
|
||||
try {
|
||||
this.func(...args);
|
||||
this.func(...args)
|
||||
} catch (ex) {
|
||||
console.console('§4插件执行任务时发生错误', ex)
|
||||
console.ex(ex);
|
||||
console.ex(ex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,12 +106,22 @@ export namespace task {
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
*/
|
||||
abstract submit(...args: any[]): Cancelable;
|
||||
submit(...args: any[]): Cancelable {
|
||||
let cancelable = this.submit0(...args)
|
||||
this.cancel = cancelable.cancel
|
||||
return cancelable
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
*/
|
||||
abstract submit0(...args: any[]): Cancelable
|
||||
}
|
||||
/**
|
||||
* 返可取消的对象
|
||||
*/
|
||||
export interface Cancelable {
|
||||
cancel(): boolean;
|
||||
cancel(): boolean
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bukkit",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/spigot-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/common": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,21 +8,47 @@ const Messenger = Bukkit.getMessenger()
|
||||
@provideSingleton(channel.Channel)
|
||||
export class BukkitChannel extends channel.Channel {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
|
||||
send(player: any, channel: string, data: any) {
|
||||
player.sendPluginMessage(this.pluginInstance, channel, data);
|
||||
private pluginInstance: any
|
||||
private cacheChannel = new Map<string, any[]>()
|
||||
/**
|
||||
* 给玩家发送通道消息
|
||||
* @param player 接受消息的玩家
|
||||
* @param channel 通道
|
||||
* @param data 数据
|
||||
*/
|
||||
send(player: any, channel: string, data: number[]) {
|
||||
player.sendPluginMessage(this.pluginInstance, channel, data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册通道监听器
|
||||
* @param channel 通道
|
||||
* @param listener 监听器
|
||||
*/
|
||||
register(channel: string, listener: channel.ChannelListener) {
|
||||
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, new PluginMessageListener({
|
||||
if (!this.cacheChannel.has(channel)) this.cacheChannel.set(channel, [])
|
||||
this.cacheChannel.get(channel).push(listener)
|
||||
let pluginMessageListener = new PluginMessageListener({
|
||||
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
||||
listener(data, { channel, player, data })
|
||||
try {
|
||||
listener(data, { channel, player, data })
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}));
|
||||
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel);
|
||||
})
|
||||
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, pluginMessageListener)
|
||||
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel)
|
||||
return pluginMessageListener
|
||||
}
|
||||
unregister(channel: string, listener: any) {
|
||||
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel)
|
||||
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
|
||||
if (!this.cacheChannel.has(channel)) return
|
||||
let cacheListener = this.cacheChannel.get(channel)
|
||||
cacheListener = cacheListener.filter(l => l != listener)
|
||||
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel, listener)
|
||||
if (cacheListener.length == 0) {
|
||||
this.cacheChannel.delete(channel)
|
||||
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
19
packages/bukkit/src/chat.ts
Normal file
19
packages/bukkit/src/chat.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { chat } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
import bukkitChat from './enhance/chat'
|
||||
|
||||
@provideSingleton(chat.Chat)
|
||||
export class BukkitChat extends chat.Chat {
|
||||
sendJson(sender: any, json: string | object, type = 0) {
|
||||
bukkitChat.send(sender, typeof json === "string" ? json : JSON.stringify(json), type)
|
||||
}
|
||||
sendMessage(sender: any, message: string) {
|
||||
this.sendJson(sender, { text: message }, 0)
|
||||
}
|
||||
sendActionBar(sender: any, message: string) {
|
||||
this.sendJson(sender, { text: message }, 2)
|
||||
}
|
||||
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
||||
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
|
||||
}
|
||||
}
|
||||
@@ -4,44 +4,47 @@ import { command, plugin } from '@ccms/api'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||
|
||||
let Bukkit = org.bukkit.Bukkit;
|
||||
let TabCompleter = Java.type('org.bukkit.command.TabCompleter');
|
||||
let PluginCommand = Java.type('org.bukkit.command.PluginCommand');
|
||||
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor');
|
||||
let Bukkit = org.bukkit.Bukkit
|
||||
let TabCompleter = Java.type('org.bukkit.command.TabCompleter')
|
||||
let PluginCommand = Java.type('org.bukkit.command.PluginCommand')
|
||||
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor')
|
||||
|
||||
@provideSingleton(command.Command)
|
||||
export class BukkitCommand extends command.Command {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
private commandMap: any;
|
||||
private commandMap: any
|
||||
|
||||
@postConstruct()
|
||||
init() {
|
||||
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get();
|
||||
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get()
|
||||
}
|
||||
create(plugin: any, command: string) {
|
||||
var cmd = this.commandMap.getCommand(command)
|
||||
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
||||
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get();
|
||||
this.commandMap.register(plugin.description.name, cmd);
|
||||
return cmd;
|
||||
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get()
|
||||
this.commandMap.register(plugin.description.name, cmd)
|
||||
return cmd
|
||||
}
|
||||
remove(plugin: any, command: string) {
|
||||
var cmd = this.commandMap.getCommand(command)
|
||||
if (cmd && cmd instanceof PluginCommand) {
|
||||
cmd.unregister(this.commandMap);
|
||||
cmd.unregister(this.commandMap)
|
||||
}
|
||||
}
|
||||
tabComplete(sender: any, input: string, index?: number): string[] {
|
||||
return Java.from(this.commandMap.tabComplete(sender, input))
|
||||
}
|
||||
onCommand(plugin: any, command: any, executor: Function) {
|
||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||
command.setExecutor(new CommandExecutor({
|
||||
onCommand: super.setExecutor(plugin, command, executor)
|
||||
}));
|
||||
}))
|
||||
}
|
||||
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||
command.setTabCompleter(new TabCompleter({
|
||||
onTabComplete: super.setTabCompleter(plugin, command, tabCompleter)
|
||||
}));
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,28 @@
|
||||
/*global Java, base, module, exports, require*/
|
||||
var nmsChatSerializerClass;
|
||||
var nmsChatSerializerMethod;
|
||||
var packetTypeConstructor;
|
||||
var nmsChatMessageTypeClass;
|
||||
var chatMessageTypes;
|
||||
let ChatSerializer: any
|
||||
let nmsChatSerializerMethodName: string
|
||||
let PacketPlayOutChat: any
|
||||
let chatMessageTypes: any
|
||||
|
||||
var RemapUtils;
|
||||
let RemapUtils: any
|
||||
|
||||
var playerConnectionFieldName;
|
||||
var sendPacketMethod;
|
||||
let playerConnectionFieldName: string
|
||||
let sendPacketMethodName: string
|
||||
|
||||
var downgrade = false;
|
||||
let above_1_16 = false
|
||||
let downgrade = false
|
||||
/**
|
||||
* 获取NMS版本
|
||||
*/
|
||||
//@ts-ignore
|
||||
var nmsVersion = org.bukkit.Bukkit.server.class.name.split('.')[3];
|
||||
let nmsVersion = undefined
|
||||
/**
|
||||
* 获取NMS类
|
||||
*/
|
||||
function nmsCls(name) {
|
||||
function nmsCls(name: string) {
|
||||
return base.getClass(['net.minecraft.server', nmsVersion, name].join('.'))
|
||||
}
|
||||
|
||||
function remapMethod(clazz: any, origin: string, test: string, params) {
|
||||
function remapMethod(clazz: any, origin: string, test: string, params: any) {
|
||||
try {
|
||||
return clazz.getMethod(origin, params)
|
||||
} catch (ex) {
|
||||
@@ -48,67 +47,72 @@ function remapFieldName(clazz: any, origin: string, test: string) {
|
||||
}
|
||||
|
||||
function init() {
|
||||
//@ts-ignore
|
||||
nmsVersion = org.bukkit.Bukkit.server.class.name.split('.')[3]
|
||||
try {
|
||||
RemapUtils = Java.type('catserver.server.remapper.RemapUtils');
|
||||
RemapUtils = Java.type('catserver.server.remapper.RemapUtils')
|
||||
} catch (ex) {
|
||||
}
|
||||
nmsChatSerializerClass = nmsCls(nmsVersion.split("_")[1] > 7 ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer");
|
||||
nmsChatSerializerMethod = remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||
var packetTypeClass = nmsCls("PacketPlayOutChat");
|
||||
Java.from(packetTypeClass.constructors).forEach(function(c) {
|
||||
let nmsChatSerializerClass = nmsCls(nmsVersion.split("_")[1] > 7 ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer")
|
||||
let nmsChatSerializerMethod = remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||
nmsChatSerializerMethodName = nmsChatSerializerMethod.getName()
|
||||
ChatSerializer = Java.type(nmsChatSerializerClass.getName())
|
||||
let packetTypeClass = nmsCls("PacketPlayOutChat")
|
||||
PacketPlayOutChat = Java.type(packetTypeClass.getName())
|
||||
let packetTypeConstructor: { parameterTypes: any[] }
|
||||
let constructors = packetTypeClass.constructors
|
||||
Java.from(constructors).forEach(function (c) {
|
||||
if (c.parameterTypes.length === 2) {
|
||||
packetTypeConstructor = c
|
||||
}
|
||||
});
|
||||
nmsChatMessageTypeClass = packetTypeConstructor.parameterTypes[1];
|
||||
if (nmsChatMessageTypeClass.isEnum()) {
|
||||
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants();
|
||||
} else {
|
||||
switch (nmsChatMessageTypeClass.name) {
|
||||
case "int":
|
||||
//@ts-ignore
|
||||
nmsChatMessageTypeClass = java.lang.Integer;
|
||||
break;
|
||||
case "byte":
|
||||
//@ts-ignore
|
||||
nmsChatMessageTypeClass = java.lang.Byte;
|
||||
break;
|
||||
if (c.parameterTypes.length === 3) {
|
||||
packetTypeConstructor = c
|
||||
above_1_16 = true
|
||||
}
|
||||
})
|
||||
let parameterTypes = packetTypeConstructor.parameterTypes
|
||||
let nmsChatMessageTypeClass = parameterTypes[1]
|
||||
if (nmsChatMessageTypeClass.isEnum()) {
|
||||
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
|
||||
}
|
||||
var entityPlayerClass = nmsCls('EntityPlayer');
|
||||
var packetClass = nmsCls('Packet');
|
||||
var playerConnectionField = remapFieldName(entityPlayerClass, 'playerConnection', 'field_71135_a')
|
||||
let playerConnectionField = remapFieldName(nmsCls('EntityPlayer'), 'playerConnection', 'field_71135_a')
|
||||
playerConnectionFieldName = playerConnectionField.getName()
|
||||
sendPacketMethod = remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', packetClass)
|
||||
sendPacketMethodName = remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', nmsCls('Packet')).getName()
|
||||
}
|
||||
|
||||
function json(sender, json) {
|
||||
function json(sender: { name: string }, json: string) {
|
||||
if (downgrade) {
|
||||
return '/tellraw ' + sender.name + ' ' + json
|
||||
} else {
|
||||
send(sender, json, 0);
|
||||
return false;
|
||||
send(sender, json, 0)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function send(sender, json, type) {
|
||||
//@ts-ignore
|
||||
sendPacket(sender, packetTypeConstructor.newInstance(nmsChatSerializerMethod.invoke(null, json), chatMessageTypes == null ? nmsChatMessageTypeClass.valueOf(java.lang.String.valueOf(type)) : chatMessageTypes[type]))
|
||||
function send(sender: any, json: any, type: number) {
|
||||
let packet
|
||||
if (above_1_16) {
|
||||
packet = new PacketPlayOutChat(ChatSerializer[nmsChatSerializerMethodName](json), chatMessageTypes == null ? type : chatMessageTypes[type], sender.getUniqueId())
|
||||
} else {
|
||||
packet = new PacketPlayOutChat(ChatSerializer[nmsChatSerializerMethodName](json), chatMessageTypes == null ? type : chatMessageTypes[type])
|
||||
}
|
||||
sendPacket(sender, packet)
|
||||
}
|
||||
|
||||
function sendPacket(player, p) {
|
||||
sendPacketMethod.invoke(player.handle[playerConnectionFieldName], p)
|
||||
function sendPacket(player: { handle: { [x: string]: { [x: string]: (arg0: any) => void } } }, p: any) {
|
||||
player.handle[playerConnectionFieldName][sendPacketMethodName](p)
|
||||
}
|
||||
|
||||
try {
|
||||
init();
|
||||
init()
|
||||
} catch (ex) {
|
||||
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
||||
downgrade = true;
|
||||
downgrade = true
|
||||
}
|
||||
|
||||
let chat = {
|
||||
json
|
||||
json,
|
||||
send
|
||||
}
|
||||
|
||||
export default chat
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
import { BukkitConsole } from './console';
|
||||
import './event';
|
||||
import './server';
|
||||
import './command';
|
||||
import './channel';
|
||||
import './task';
|
||||
import { BukkitConsole } from './console'
|
||||
import './chat'
|
||||
import './task'
|
||||
import './event'
|
||||
import './server'
|
||||
import './command'
|
||||
import './channel'
|
||||
|
||||
export default function BukkitImpl(container: Container) {
|
||||
container.bind(server.Console).toConstantValue(BukkitConsole);
|
||||
container.bind(server.Console).toConstantValue(BukkitConsole)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { server, constants } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container';
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
import chat from './enhance/chat'
|
||||
|
||||
let Bukkit = org.bukkit.Bukkit;
|
||||
let Bukkit = org.bukkit.Bukkit
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
export class BukkitServer extends server.ReflectServer {
|
||||
private pluginsFolder: string;
|
||||
private pluginsFolder: string
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
|
||||
super()
|
||||
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath()
|
||||
}
|
||||
|
||||
getPlayer(name: string) {
|
||||
@@ -40,27 +40,18 @@ export class BukkitServer extends server.ReflectServer {
|
||||
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
|
||||
}
|
||||
getPluginsFolder(): string {
|
||||
return this.pluginsFolder;
|
||||
return this.pluginsFolder
|
||||
}
|
||||
getNativePluginManager() {
|
||||
return Bukkit.getPluginManager() as any;
|
||||
return Bukkit.getPluginManager() as any
|
||||
}
|
||||
getDedicatedServer() {
|
||||
return reflect.on(Bukkit.getServer()).get('console').get()
|
||||
}
|
||||
getNettyPipeline() {
|
||||
return this.pipeline;
|
||||
return this.pipeline
|
||||
}
|
||||
getRootLogger() {
|
||||
return this.rootLogger;
|
||||
}
|
||||
sendJson(sender: string | any, json: object | string): void {
|
||||
if (typeof sender === "string") {
|
||||
sender = this.getPlayer(sender)
|
||||
}
|
||||
let result = chat.json(sender, json)
|
||||
if (result !== false) {
|
||||
this.dispatchConsoleCommand(result)
|
||||
}
|
||||
return this.rootLogger
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,28 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container';
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
|
||||
const Bukkit = Java.type('org.bukkit.Bukkit');
|
||||
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable');
|
||||
const Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable')
|
||||
const Callable = Java.type('java.util.concurrent.Callable')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class BukkitTaskManager implements task.TaskManager {
|
||||
export class BukkitTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private pluginInstance: any
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new BukkitTask(this.pluginInstance, func);
|
||||
create0(func: Function): task.Task {
|
||||
return new BukkitTask(this.pluginInstance, func)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
||||
}
|
||||
disable() {
|
||||
Bukkit.getScheduler().cancelTasks(this.pluginInstance);
|
||||
disable0() {
|
||||
Bukkit.getScheduler().cancelTasks(this.pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
export class BukkitTask extends task.Task {
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
submit0(...args: any[]): task.Cancelable {
|
||||
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bungee",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/bungee-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/common": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,29 +3,29 @@ import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
||||
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
|
||||
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
export class BungeeServer implements server.Server {
|
||||
private pluginsFolder: string;
|
||||
private pipeline: any;
|
||||
private rootLogger: any;
|
||||
private pluginsFolder: string
|
||||
private pipeline: any
|
||||
private rootLogger: any
|
||||
|
||||
@inject(task.TaskManager)
|
||||
private task: task.TaskManager
|
||||
|
||||
constructor() {
|
||||
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath();
|
||||
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath()
|
||||
}
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
let count = 0;
|
||||
let count = 0
|
||||
let wait = this.task.create(() => {
|
||||
try {
|
||||
// @ts-ignore
|
||||
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
||||
wait.cancel();
|
||||
wait.cancel()
|
||||
} catch (ex) {
|
||||
count++
|
||||
if (count > 50) {
|
||||
@@ -44,7 +44,7 @@ export class BungeeServer implements server.Server {
|
||||
}
|
||||
|
||||
getPlayer(name: string) {
|
||||
return Bungee.getPlayer(name);
|
||||
return Bungee.getPlayer(name)
|
||||
}
|
||||
getVersion(): string {
|
||||
return Bungee.getVersion()
|
||||
@@ -56,7 +56,7 @@ export class BungeeServer implements server.Server {
|
||||
return Bungee.getConsole()
|
||||
}
|
||||
getService(service: string) {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchCommand(sender: string | any, command: string): boolean {
|
||||
if (typeof sender === 'string') {
|
||||
@@ -68,18 +68,15 @@ export class BungeeServer implements server.Server {
|
||||
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
|
||||
}
|
||||
getPluginsFolder(): string {
|
||||
return this.pluginsFolder;
|
||||
return this.pluginsFolder
|
||||
}
|
||||
getNativePluginManager() {
|
||||
return Bungee.getPluginManager() as any
|
||||
}
|
||||
getNettyPipeline() {
|
||||
return this.pipeline;
|
||||
return this.pipeline
|
||||
}
|
||||
getRootLogger() {
|
||||
return this.rootLogger;
|
||||
}
|
||||
sendJson(sender: string | any, json: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
return this.rootLogger
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container';
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
|
||||
var Runnable = Java.type('java.lang.Runnable')
|
||||
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class BungeeTaskManager implements task.TaskManager {
|
||||
export class BungeeTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private pluginInstance: any
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new BungeeTask(this.pluginInstance, func);
|
||||
create0(func: Function): task.Task {
|
||||
return new BungeeTask(this.pluginInstance, func)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func();
|
||||
return func()
|
||||
}
|
||||
disable() {
|
||||
disable0() {
|
||||
this.pluginInstance.getProxy().getScheduler().cancel(this.pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
export class BungeeTask extends task.Task {
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
submit0(...args: any[]): task.Cancelable {
|
||||
let run = new Runnable({ run: () => this.run(...args) })
|
||||
if (this.isAsync) {
|
||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ccms/client",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.0",
|
||||
"description": "MiaoScript client package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,10 +22,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"minecraft-protocol": "^1.11.0"
|
||||
"minecraft-protocol": "^1.13.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/common",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.3",
|
||||
"@javatypes/jdk": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.8.0",
|
||||
"@javatypes/jdk": "^1.14.0"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import * as querystring from 'querystring'
|
||||
|
||||
const URL = Java.type('java.net.URL')
|
||||
const Paths = Java.type('java.nio.file.Paths');
|
||||
const Files = Java.type('java.nio.file.Files');
|
||||
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption');
|
||||
const Paths = Java.type('java.nio.file.Paths')
|
||||
const Files = Java.type('java.nio.file.Files')
|
||||
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption')
|
||||
|
||||
export type Method =
|
||||
| 'get' | 'GET'
|
||||
@@ -13,36 +15,49 @@ export type Method =
|
||||
| 'patch' | 'PATCH'
|
||||
|
||||
interface RequestConfig {
|
||||
url?: string;
|
||||
method?: Method;
|
||||
headers?: { [key: string]: string };
|
||||
params?: { [key: string]: string };
|
||||
data?: any;
|
||||
url?: string
|
||||
method?: Method
|
||||
headers?: { [key: string]: string }
|
||||
params?: { [key: string]: string }
|
||||
data?: any
|
||||
}
|
||||
|
||||
function request(config: RequestConfig) {
|
||||
// @ts-ignore
|
||||
let xhr = new XMLHttpRequest();
|
||||
xhr.open(config.method, config.url, false);
|
||||
let xhr = new XMLHttpRequest()
|
||||
xhr.open(config.method, config.url, false)
|
||||
for (const header in config.headers) {
|
||||
xhr.setRequestHeader(header, config.headers[header]);
|
||||
xhr.setRequestHeader(header, config.headers[header])
|
||||
}
|
||||
xhr.send(typeof config.data === "string" ? config.data : JSON.stringify(config.data));
|
||||
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
|
||||
let body = config.data
|
||||
if (body && typeof body !== "string") {
|
||||
switch (config.headers['Content-Type']) {
|
||||
case "application/json":
|
||||
body = JSON.stringify(body)
|
||||
break
|
||||
case "application/x-www-form-urlencoded":
|
||||
body = querystring.encode(body)
|
||||
break
|
||||
}
|
||||
}
|
||||
xhr.send(body)
|
||||
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
|
||||
xhr.responseType = "json"
|
||||
}
|
||||
return xhr.get();
|
||||
return xhr.get()
|
||||
}
|
||||
|
||||
function download(url: string, target: string) {
|
||||
console.debug(`Start Download file ${target} from ${url}....`)
|
||||
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING)
|
||||
console.debug(`File ${target} Download Complate...`)
|
||||
}
|
||||
|
||||
function _proxy(method: Method) {
|
||||
return function (url: string, data?: any, config?: RequestConfig) {
|
||||
return request({ url, method, data, ...config });
|
||||
return function (url: string, data?: any, config: RequestConfig = {}) {
|
||||
if (!config.headers) { config.headers = {} }
|
||||
config.headers['Content-Type'] = config.headers['Content-Type'] ?? 'application/json'
|
||||
return request({ url, method, data, ...config })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
1243
packages/common/src/qrcode.ts
Normal file
1243
packages/common/src/qrcode.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -96,10 +96,7 @@ function types(values: any[], def?: any) {
|
||||
}
|
||||
|
||||
function accessible<T extends java.lang.reflect.AccessibleObject>(accessible: T): T {
|
||||
if (accessible === null) {
|
||||
return null
|
||||
}
|
||||
if (!accessible.isAccessible()) {
|
||||
if (!accessible?.isAccessible()) {
|
||||
accessible.setAccessible(true)
|
||||
}
|
||||
return accessible
|
||||
@@ -143,7 +140,8 @@ function declaredMethod(clazz: java.lang.Class<any>, name: string, ...clazzs: ja
|
||||
let key = clazz.getName() + '.' + name + ':' + (clazzs || []).join(':')
|
||||
if (!methodCache[key]) {
|
||||
try {
|
||||
methodCache[key] = clazz.getMethod(name, ...clazzs)
|
||||
// @ts-ignore
|
||||
methodCache[key] = clazz.getMethod(name, clazzs)
|
||||
} catch (ex) {
|
||||
try {
|
||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs as any)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/compile",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.0",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,6 +21,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/container",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,12 +19,12 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.8.0",
|
||||
"inversify": "^5.0.1",
|
||||
"inversify-binding-decorators": "^4.0.0"
|
||||
}
|
||||
|
||||
@@ -36,10 +36,10 @@ export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<a
|
||||
* @param className Java全类名
|
||||
*/
|
||||
export const JavaClass = (className: string) => {
|
||||
return function (target: any, propertyKey: string, index?: number) {
|
||||
return function (target: object, propertyKey: string, index?: number) {
|
||||
try { target[propertyKey] = Java.type(className).class; return } catch (error) { }
|
||||
try { target[propertyKey] = base.getClass(className); return } catch (error) { }
|
||||
console.warn('JavaClass Inject target', target, 'propertyKey', propertyKey, 'failed!')
|
||||
console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,10 +48,10 @@ export const JavaClass = (className: string) => {
|
||||
* @param className Java 全类名
|
||||
*/
|
||||
export const JSClass = (className: string) => {
|
||||
return function (target: any, propertyKey: string, index?: number) {
|
||||
return function (target: object, propertyKey: string, index?: number) {
|
||||
try { target[propertyKey] = Java.type(className); return } catch (error) { }
|
||||
try { target[propertyKey] = base.getClass(className).static; return } catch (error) { }
|
||||
console.warn('JSClass Inject target', target, 'propertyKey', propertyKey, 'failed!')
|
||||
console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,8 +60,22 @@ export const JSClass = (className: string) => {
|
||||
* @param className 类名
|
||||
*/
|
||||
export const Autowired = (className?: string | any) => {
|
||||
return function (target: any, propertyKey: string) {
|
||||
target[propertyKey] = getContainer().getNamed(ioc.Autowired, className || propertyKey)
|
||||
return function (target: any, propertyKey: string, index?: number) {
|
||||
let container = getContainer()
|
||||
let type = Reflect.getMetadata('design:type', target, propertyKey)
|
||||
if (type && type !== Object) {
|
||||
try {
|
||||
return target[propertyKey] = container.getNamed(type, className || propertyKey)
|
||||
} catch (error) {
|
||||
try {
|
||||
return target[propertyKey] = container.get(type)
|
||||
} catch (error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (container.isBound(ioc.Autowired)) {
|
||||
target[propertyKey] = container.getNamed(ioc.Autowired, className || propertyKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +84,7 @@ export const Autowired = (className?: string | any) => {
|
||||
* @param className 类名
|
||||
*/
|
||||
export const Resource = (resourceName?: string | any) => {
|
||||
return function (target: any, propertyKey: string) {
|
||||
return function (target: any, propertyKey: string, index?: number) {
|
||||
target[propertyKey] = getContainer().getNamed(ioc.Resource, resourceName || propertyKey)
|
||||
}
|
||||
}
|
||||
@@ -82,8 +96,18 @@ export const reduceMetadata = (ctx: interfaces.Context): any => {
|
||||
}, {})
|
||||
}
|
||||
|
||||
function initAutowired(container: Container) {
|
||||
container.bind(ioc.Autowired).toDynamicValue((ctx) => {
|
||||
var metadata: any = reduceMetadata(ctx)
|
||||
let key = Object.toString.call(metadata.named)
|
||||
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
|
||||
return undefined
|
||||
})
|
||||
}
|
||||
|
||||
export const DefaultContainer = new Container()
|
||||
initContainer(DefaultContainer)
|
||||
initAutowired(DefaultContainer)
|
||||
|
||||
export * from 'inversify'
|
||||
export * from './constants'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/core",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { plugin, server, task, constants } from '@ccms/api'
|
||||
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ccms/container'
|
||||
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
||||
import http from '@ccms/common/dist/http'
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
@provideSingleton(MiaoScriptCore)
|
||||
class MiaoScriptCore {
|
||||
@@ -50,11 +49,12 @@ class MiaoScriptCore {
|
||||
}
|
||||
|
||||
disable() {
|
||||
let disableStartTime = Date.now()
|
||||
console.i18n("ms.core.engine.disable")
|
||||
this.pluginManager.disable(this.pluginManager.getPlugins())
|
||||
this.taskManager.disable()
|
||||
process.emit('exit', 0)
|
||||
process.exit(0)
|
||||
console.i18n("ms.core.engine.disable.finish", { version: 'v' + global.ScriptEngineVersion, time: (new Date().getTime() - disableStartTime) / 1000 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ function detectServer(): constants.ServerType {
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
// @ts-ignore
|
||||
global.ScriptEngineVersion = require('../package.json').version
|
||||
try { engineLoad({ script: http.get("http://ms.yumc.pw/api/plugin/download/name/initialize"), name: 'core/initialize.js' }) } catch (error) { console.debug(error) }
|
||||
try {
|
||||
let corePackageStartTime = new Date().getTime()
|
||||
@@ -98,13 +98,14 @@ function initialize() {
|
||||
let type = detectServer()
|
||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
||||
container.bind(server.ServerType).toConstantValue(type)
|
||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
||||
require(`${global.scope}/${type}`).default(container)
|
||||
require(`${global.scope}/plugin`)
|
||||
container.load(buildProviderModule())
|
||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
||||
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 })
|
||||
console.i18n("ms.core.engine.completed", { version: 'v' + global.ScriptEngineVersion, time: (Date.now() - global.ScriptEngineStartTime) / 1000 })
|
||||
return disable
|
||||
} catch (error) {
|
||||
console.i18n("ms.core.initialize.error", { error })
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/database",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript database package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,12 +19,13 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/spring-jdbc": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,9 @@ ms.core.package.initialize: "初始化 MiaoScript 扩展 {scope}/core {scope}/{t
|
||||
ms.core.package.completed: "MiaoScript 扩展 {scope}/core {scope}/{type} {scope}/plugin 加载完成 耗时({time}s)"
|
||||
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
||||
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
||||
ms.core.engine.completed: "MiaoScript 脚本引擎 加载完毕... 耗时({time}s)!"
|
||||
ms.core.engine.disable: "关闭 MiaoScript 引擎..."
|
||||
ms.core.engine.completed: "MiaoScript 脚本引擎 {version} 加载完毕... 耗时({time}s)!"
|
||||
ms.core.engine.disable: "MiaoScript 关闭脚本引擎 请稍候..."
|
||||
ms.core.engine.disable.finish: "MiaoScript 脚本引擎 {version} 关闭完成... 耗时({time}s)!"
|
||||
ms.core.engine.disable.abnormal: "引擎异常启动或初始化未完成 跳过关闭流程..."
|
||||
|
||||
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
||||
@@ -21,8 +22,8 @@ ms.api.event.not.found: "§6插件 §b{name} §6注册事件 §c{event} §6失
|
||||
ms.api.event.execute.slow: "§c注意! §6插件 §b{name} §6处理 §d{event} §6事件 §c耗时 §4{cost}ms !"
|
||||
ms.api.event.execute.error: "§6插件 §b{name} §6处理 §d{event} §6事件时发生异常 §4{ex}"
|
||||
ms.api.event.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
|
||||
ms.api.event.register: "[{name}] 注册事件 {event}"
|
||||
ms.api.event.unregister: "[{name}] 注销事件 {event}"
|
||||
ms.api.event.register: "[{name}] 注册事件 {event} => 执行器 {exec}"
|
||||
ms.api.event.unregister: "[{name}] 注销事件 {event} => 执行器 {exec}"
|
||||
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
||||
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
||||
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/i18n",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript i18n package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,14 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/js-yaml": "^3.12.3",
|
||||
"@ccms/nashorn": "^0.9.3",
|
||||
"@types/js-yaml": "^3.12.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.8.0",
|
||||
"js-yaml": "^3.13.1"
|
||||
"js-yaml": "^3.14.0"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
1
packages/keyvalue/.npmignore
Symbolic link
1
packages/keyvalue/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
36
packages/keyvalue/package.json
Normal file
36
packages/keyvalue/package.json
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "@ccms/keyvalue",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript keyvalue package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/common": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.3",
|
||||
"@javatypes/amqp-client": "^0.0.2",
|
||||
"@javatypes/spring-amqp": "^0.0.2",
|
||||
"@javatypes/spring-rabbit": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||
}
|
||||
17
packages/keyvalue/src/adapter/admin.ts
Normal file
17
packages/keyvalue/src/adapter/admin.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { RabbitTemplateAdapter } from "./template"
|
||||
import { JSClass } from "@ccms/container"
|
||||
|
||||
export const RabbitAdmin = Java.type('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
|
||||
export class RabbitAdminAdapter {
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
constructor(config: RabbitTemplateAdapter | org.springframework.amqp.rabbit.core.RabbitTemplate | ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory) {
|
||||
this._Handler = new RabbitAdmin((config instanceof RabbitTemplateAdapter || config instanceof ConnectionFactoryAdapter) ? config.getHandler() : config)
|
||||
}
|
||||
getHandler(): org.springframework.amqp.rabbit.core.RabbitAdmin {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
30
packages/keyvalue/src/adapter/callback.ts
Normal file
30
packages/keyvalue/src/adapter/callback.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
export const ConfirmCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback')
|
||||
export const ReturnCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback')
|
||||
|
||||
export abstract class ConfirmCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback
|
||||
constructor() {
|
||||
let ConfirmCallbackImpl = Java.extend(ReturnCallback, {
|
||||
confirm: (correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string) => this.confirm(correlationData, ack, cause)
|
||||
})
|
||||
this._Handler = new ConfirmCallbackImpl()
|
||||
}
|
||||
abstract confirm(correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class ReturnCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback
|
||||
constructor() {
|
||||
let ReturnCallbackImpl = Java.extend(ReturnCallback, {
|
||||
returnedMessage: (message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string) => this.returnedMessage(message, replyCode, replyText, exchange, routingKey)
|
||||
})
|
||||
this._Handler = new ReturnCallbackImpl()
|
||||
}
|
||||
abstract returnedMessage(message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
31
packages/keyvalue/src/adapter/connection.ts
Normal file
31
packages/keyvalue/src/adapter/connection.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import threadPool from '@ccms/common/dist/thread-pool'
|
||||
|
||||
export const ConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.ConnectionFactory')
|
||||
const CachingConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.CachingConnectionFactory')
|
||||
interface ConnectionConfig {
|
||||
url: string,
|
||||
username?: string,
|
||||
password?: string,
|
||||
publisherConfirms?: boolean
|
||||
cacheSize?: number
|
||||
}
|
||||
|
||||
export class ConnectionFactoryAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.connection.CachingConnectionFactory
|
||||
|
||||
constructor(config: ConnectionConfig) {
|
||||
if (!config.url) { throw new Error('Connection UrI Can\'t be undefiend!') }
|
||||
config = { publisherConfirms: true, cacheSize: 50, ...config }
|
||||
this._Handler = new CachingConnectionFactory(new java.net.URI(config.url))
|
||||
config.username && this._Handler.setUsername(config.username)
|
||||
config.password && this._Handler.setPassword(config.password)
|
||||
this._Handler.setPublisherConfirms(config.publisherConfirms)
|
||||
this._Handler.setExecutor(threadPool.create({
|
||||
groupName: '@ccms/amqp-rabbit'
|
||||
}))
|
||||
this._Handler.setChannelCacheSize(config.cacheSize)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
30
packages/keyvalue/src/adapter/container.ts
Normal file
30
packages/keyvalue/src/adapter/container.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { ConnectionFactoryAdapter, ConnectionFactory } from "./connection"
|
||||
import { ChannelAwareMessageListenerAdapter, ChannelAwareMessageListener } from "./listener"
|
||||
|
||||
export const SimpleMessageListenerContainer = org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
export const AcknowledgeMode: org.springframework.amqp.core.AcknowledgeMode = Java.type('org.springframework.amqp.core.AcknowledgeMode')
|
||||
interface ContainerConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | typeof ConnectionFactory
|
||||
queueNames: string[]
|
||||
messageListener: ChannelAwareMessageListenerAdapter | typeof ChannelAwareMessageListener
|
||||
maxConcurrentConsumers?: number
|
||||
concurrentConsumers?: number
|
||||
acknowledgeMode?: org.springframework.amqp.core.AcknowledgeMode
|
||||
}
|
||||
|
||||
export class MessageListenerContainerAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
constructor(config: ContainerConfig) {
|
||||
config = { concurrentConsumers: 5, maxConcurrentConsumers: 10, acknowledgeMode: AcknowledgeMode.AUTO, ...config }
|
||||
this._Handler = new SimpleMessageListenerContainer(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
//@ts-ignore
|
||||
this._Handler.setQueueNames(config.queueNames)
|
||||
this._Handler.setMaxConcurrentConsumers(config.maxConcurrentConsumers)
|
||||
this._Handler.setConcurrentConsumers(config.concurrentConsumers)
|
||||
this._Handler.setAcknowledgeMode(config.acknowledgeMode)
|
||||
this._Handler.setMessageListener(config.messageListener instanceof ChannelAwareMessageListenerAdapter ? config.messageListener.getHandler() : config.messageListener)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
37
packages/keyvalue/src/adapter/converter.ts
Normal file
37
packages/keyvalue/src/adapter/converter.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
const Message = org.springframework.amqp.core.Message
|
||||
|
||||
export const MessageConverter = Java.type('org.springframework.amqp.support.converter.MessageConverter')
|
||||
|
||||
export class MessageConverterAdapter {
|
||||
private _Handler: org.springframework.amqp.support.converter.MessageConverter
|
||||
constructor() {
|
||||
var MessageConverterImpl = Java.extend(MessageConverter, {
|
||||
toMessage: (object: any, messageProperties: org.springframework.amqp.core.MessageProperties) => this.toMessage(object, messageProperties),
|
||||
fromMessage: (message: org.springframework.amqp.core.Message) => this.fromMessage(message)
|
||||
})
|
||||
this._Handler = new MessageConverterImpl()
|
||||
}
|
||||
toMessage(object: any, messageProperties: org.springframework.amqp.core.MessageProperties) {
|
||||
if (typeof object == "string") {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
|
||||
return new Message(new JavaString(object).getBytes(), messageProperties)
|
||||
} else {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
return new Message(new JavaString(JSON.stringify(object)).getBytes(), messageProperties)
|
||||
}
|
||||
}
|
||||
fromMessage(message: org.springframework.amqp.core.Message) {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_TEXT_PLAIN) {
|
||||
return new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding())
|
||||
}
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
return JSON.parse(new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding()))
|
||||
}
|
||||
return message
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
7
packages/keyvalue/src/adapter/index.ts
Normal file
7
packages/keyvalue/src/adapter/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export * from './admin'
|
||||
export * from './callback'
|
||||
export * from './connection'
|
||||
export * from './container'
|
||||
export * from './converter'
|
||||
export * from './listener'
|
||||
export * from './template'
|
||||
49
packages/keyvalue/src/adapter/listener.ts
Normal file
49
packages/keyvalue/src/adapter/listener.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
export const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
export const ChannelAwareMessageListener = Java.type('org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener')
|
||||
export const AmqpRejectAndDontRequeueException = org.springframework.amqp.AmqpRejectAndDontRequeueException
|
||||
export const Channel: com.rabbitmq.client.Channel = Java.type('com.rabbitmq.client.Channel')
|
||||
export const Message = org.springframework.amqp.core.Message
|
||||
export type MessageHandler<T> = (content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => any
|
||||
export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener
|
||||
constructor(manual: boolean = false) {
|
||||
let ChannelAwareMessageListenerImpl = Java.extend(ChannelAwareMessageListener, {
|
||||
onMessage: (message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => {
|
||||
let content = new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding() || "UTF-8")
|
||||
try {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
content = JSON.parse(content)
|
||||
}
|
||||
} catch (error) {
|
||||
if (manual) {
|
||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
|
||||
} else {
|
||||
throw new AmqpRejectAndDontRequeueException(`${error}`, error)
|
||||
}
|
||||
}
|
||||
manual ? this.manualOnMessage(content, message, channel) : this.onMessage(content, message, channel)
|
||||
}
|
||||
})
|
||||
this._Handler = new ChannelAwareMessageListenerImpl()
|
||||
}
|
||||
abstract onMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any
|
||||
onError(error: Error, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any { }
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
private manualOnMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
let deliveryTag = message.getMessageProperties().getDeliveryTag()
|
||||
try {
|
||||
if (this.onMessage(content, message, channel)) {
|
||||
channel.basicAck(deliveryTag, false)
|
||||
} else if (message.getMessageProperties().getRedelivered()) {
|
||||
channel.basicReject(deliveryTag, true)
|
||||
} else {
|
||||
channel.basicNack(deliveryTag, false, true)
|
||||
}
|
||||
} catch (error) {
|
||||
channel.basicReject(deliveryTag, this.onError(error, message, channel))
|
||||
}
|
||||
}
|
||||
}
|
||||
27
packages/keyvalue/src/adapter/template.ts
Normal file
27
packages/keyvalue/src/adapter/template.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { MessageConverterAdapter } from "./converter"
|
||||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { ConfirmCallbackAdapter, ReturnCallbackAdapter } from "./callback"
|
||||
|
||||
export const RabbitTemplate = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate')
|
||||
|
||||
interface TemplateConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory
|
||||
confirmCallback?: ConfirmCallbackAdapter
|
||||
returnCallback?: ReturnCallbackAdapter
|
||||
messageConverter?: MessageConverterAdapter
|
||||
}
|
||||
export class RabbitTemplateAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate
|
||||
constructor(config: TemplateConfig) {
|
||||
config = { messageConverter: new MessageConverterAdapter(), ...config }
|
||||
console.debug(JSON.stringify(config))
|
||||
this._Handler = new RabbitTemplate(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
config.returnCallback && this._Handler.setReturnCallback(config.returnCallback.getHandler())
|
||||
config.confirmCallback && this._Handler.setConfirmCallback(config.confirmCallback.getHandler())
|
||||
config.messageConverter && this._Handler.setMessageConverter(config.messageConverter.getHandler())
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
89
packages/keyvalue/src/admin.ts
Normal file
89
packages/keyvalue/src/admin.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { JSClass } from "@ccms/container"
|
||||
import { RabbitAdminAdapter, MessageListenerContainerAdapter, AcknowledgeMode, MessageHandler, ChannelAwareMessageListenerAdapter } from "./adapter"
|
||||
|
||||
export class AmqpAdmin {
|
||||
@JSClass('org.springframework.amqp.core.TopicExchange')
|
||||
private TopicExchange: typeof org.springframework.amqp.core.TopicExchange
|
||||
@JSClass('org.springframework.amqp.core.Queue')
|
||||
private Queue: typeof org.springframework.amqp.core.Queue
|
||||
@JSClass('org.springframework.amqp.core.Binding')
|
||||
private Binding: typeof org.springframework.amqp.core.Binding
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: typeof org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
@JSClass('org.springframework.amqp.core.Binding.DestinationType')
|
||||
private DestinationType: org.springframework.amqp.core.Binding.DestinationType
|
||||
|
||||
private amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
|
||||
constructor(amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin | any) {
|
||||
if (amqpAdmin instanceof this.RabbitAdmin) {
|
||||
this.amqpAdmin = amqpAdmin
|
||||
} else if (amqpAdmin instanceof RabbitAdminAdapter) {
|
||||
this.amqpAdmin = amqpAdmin.getHandler()
|
||||
} else {
|
||||
this.amqpAdmin = new RabbitAdminAdapter(amqpAdmin).getHandler()
|
||||
}
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this.amqpAdmin
|
||||
}
|
||||
|
||||
getQueueProperties(name: string) {
|
||||
return this.amqpAdmin.getQueueProperties(name)
|
||||
}
|
||||
|
||||
declareExchange(name: string) {
|
||||
let exchange = new this.TopicExchange(name, true, false)
|
||||
this.amqpAdmin.declareExchange(exchange)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueue(name: string) {
|
||||
let queue = new this.Queue(name, true)
|
||||
this.amqpAdmin.declareQueue(queue)
|
||||
return this
|
||||
}
|
||||
|
||||
declareBinding(queue: string, exchange: string, routerKey: string, argument: any = null) {
|
||||
let binding = new this.Binding(queue, this.DestinationType.QUEUE, exchange, routerKey, argument)
|
||||
this.amqpAdmin.declareBinding(binding)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueueAndBindExchange(queue: string, exchange: string, routerKey: string) {
|
||||
return this.declareQueue(queue).declareExchange(exchange).declareBinding(queue, exchange, routerKey)
|
||||
}
|
||||
|
||||
createContainer<T>(queue: string, listener: MessageHandler<T>, acknowledgeMode = AcknowledgeMode.AUTO) {
|
||||
let connection = this.amqpAdmin.getRabbitTemplate().getConnectionFactory()
|
||||
return new MessageListenerContainerAdapter({
|
||||
connectionFactory: connection,
|
||||
queueNames: [queue],
|
||||
messageListener: new SimpleMessageHandler(listener),
|
||||
acknowledgeMode: acknowledgeMode
|
||||
}).getHandler()
|
||||
}
|
||||
|
||||
send()
|
||||
send() {
|
||||
|
||||
}
|
||||
|
||||
getTemplate() {
|
||||
return this.amqpAdmin.getRabbitTemplate()
|
||||
}
|
||||
|
||||
close() {
|
||||
this.getTemplate().stop()
|
||||
}
|
||||
}
|
||||
|
||||
export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
|
||||
constructor(private handler: MessageHandler<any>) {
|
||||
super()
|
||||
}
|
||||
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
return this.handler(content, message, channel)
|
||||
}
|
||||
}
|
||||
3
packages/keyvalue/src/constants.ts
Normal file
3
packages/keyvalue/src/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const METADATA_KEY = {
|
||||
|
||||
}
|
||||
34
packages/keyvalue/src/index.ts
Normal file
34
packages/keyvalue/src/index.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/spring-amqp" />
|
||||
/// <reference types="@javatypes/spring-rabbit" />
|
||||
/// <reference types="@javatypes/amqp-client" />
|
||||
|
||||
import { amqp } from '@ccms/api'
|
||||
import { getContainer, reduceMetadata } from '@ccms/container'
|
||||
|
||||
function init() {
|
||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
getContainer().bind(amqp.rabbit.Template).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitTemplate')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitTemplate`)
|
||||
}
|
||||
})
|
||||
getContainer().bind(amqp.rabbit.Admin).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitAdmin')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitAdmin`)
|
||||
}
|
||||
})
|
||||
}
|
||||
init()
|
||||
|
||||
export * from './admin'
|
||||
export * from './adapter'
|
||||
export * from './manager'
|
||||
export * from './constants'
|
||||
5
packages/keyvalue/src/listener.ts
Normal file
5
packages/keyvalue/src/listener.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export class AmqpListener {
|
||||
constructor() {
|
||||
|
||||
}
|
||||
}
|
||||
18
packages/keyvalue/src/manager.ts
Normal file
18
packages/keyvalue/src/manager.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { amqp } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
|
||||
import { ConnectionFactoryAdapter, RabbitTemplateAdapter, RabbitAdminAdapter } from "./adapter"
|
||||
import { AmqpAdmin } from "./admin"
|
||||
|
||||
@provideSingleton(amqp.Manager)
|
||||
export class AmqpManager {
|
||||
createConnection(url: string, username: string, password: string) {
|
||||
return new ConnectionFactoryAdapter({ url, username, password })
|
||||
}
|
||||
createTemplate(adapter: ConnectionFactoryAdapter) {
|
||||
return new RabbitTemplateAdapter({ connectionFactory: adapter })
|
||||
}
|
||||
createAdmin(adapter: RabbitTemplateAdapter | ConnectionFactoryAdapter) {
|
||||
return new AmqpAdmin(new RabbitAdminAdapter(adapter))
|
||||
}
|
||||
}
|
||||
7
packages/keyvalue/tsconfig.json
Normal file
7
packages/keyvalue/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nashorn",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,6 +22,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,8 @@ declare global {
|
||||
logger: any
|
||||
debug: boolean
|
||||
level: string
|
||||
NashornEngineStartTime: number
|
||||
ScriptEngineVersion: string
|
||||
ScriptEngineStartTime: number
|
||||
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void
|
||||
noop: () => void
|
||||
console: Console
|
||||
@@ -73,6 +74,7 @@ declare global {
|
||||
interface Console {
|
||||
ex(err: Error): void
|
||||
stack(err: Error, color?: boolean): string[]
|
||||
sender(sender: any, ...args: any): void
|
||||
sender(...args: any): void
|
||||
console(...args: any): void
|
||||
i18n(name: string, ...params: any[]): void
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nodejs",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript nodejs package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,12 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.8.0"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nukkit",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript nukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/nukkit-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/common": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,32 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container';
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
|
||||
const NukkitRunnable = Java.type('cn.nukkit.scheduler.NukkitRunnable');
|
||||
const NukkitRunnable = Java.type('cn.nukkit.scheduler.NukkitRunnable')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class NukkitTaskManager implements task.TaskManager {
|
||||
export class NukkitTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private pluginInstance: any
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new NukkitTask(this.pluginInstance, func);
|
||||
create0(func: Function): task.Task {
|
||||
return new NukkitTask(this.pluginInstance, func)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func()
|
||||
}
|
||||
disable() {
|
||||
disable0() {
|
||||
base.getInstance().getServer().getScheduler().cancelTask(this.pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
export class NukkitTask extends task.Task {
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
submit0(...args: any[]): task.Cancelable {
|
||||
let run = new NukkitRunnable({ run: () => this.run(...args) })
|
||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
run[funcName](this.plugin, this.laterTime, this.interval);
|
||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||
} else {
|
||||
run[funcName](this.plugin, this.laterTime);
|
||||
return run[funcName](this.plugin, this.laterTime)
|
||||
}
|
||||
return run;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/ployfill",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript ployfill package",
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
@@ -14,13 +14,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/i18n": "^0.8.0",
|
||||
"@ccms/nashorn": "^0.8.0",
|
||||
"@ccms/i18n": "^0.9.3",
|
||||
"@ccms/nodejs": "^0.9.3",
|
||||
"core-js": "^3.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
|
||||
import '@ccms/nodejs'
|
||||
import i18n from '@ccms/i18n'
|
||||
let ployfillStartTime = new Date().getTime()
|
||||
i18n.initialize()
|
||||
|
||||
@@ -28,8 +28,9 @@ class Process extends EventEmitter {
|
||||
queueMicrotask(func: Function) {
|
||||
microTaskPool.execute(func)
|
||||
}
|
||||
exit() {
|
||||
microTaskPool.shutdown();
|
||||
exit(code: number) {
|
||||
process.emit('exit', code)
|
||||
microTaskPool.shutdown()
|
||||
}
|
||||
}
|
||||
global.setGlobal('process', new Process(), {})
|
||||
|
||||
@@ -1,39 +1,39 @@
|
||||
import '@ccms/nashorn'
|
||||
|
||||
const URL = Java.type("java.net.URL");
|
||||
const Files = Java.type("java.nio.file.Files");
|
||||
const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
||||
const JavaString = Java.type("java.lang.String");
|
||||
const SecureRandom = Java.type("java.security.SecureRandom");
|
||||
const SSLContext = Java.type("javax.net.ssl.SSLContext");
|
||||
const HttpsURLConnection = Java.type("javax.net.ssl.HttpsURLConnection");
|
||||
const HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier");
|
||||
const X509TrustManager = Java.type("javax.net.ssl.X509TrustManager");
|
||||
const URL = Java.type("java.net.URL")
|
||||
const Files = Java.type("java.nio.file.Files")
|
||||
const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption")
|
||||
const JavaString = Java.type("java.lang.String")
|
||||
const SecureRandom = Java.type("java.security.SecureRandom")
|
||||
const SSLContext = Java.type("javax.net.ssl.SSLContext")
|
||||
const HttpsURLConnection = Java.type("javax.net.ssl.HttpsURLConnection")
|
||||
const HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier")
|
||||
const X509TrustManager = Java.type("javax.net.ssl.X509TrustManager")
|
||||
|
||||
const SocketTimeoutException = Java.type('java.net.SocketTimeoutException');
|
||||
const SocketTimeoutException = Java.type('java.net.SocketTimeoutException')
|
||||
|
||||
const Callable = Java.type('java.util.concurrent.Callable');
|
||||
const Callable = Java.type('java.util.concurrent.Callable')
|
||||
const Executors = Java.type('java.util.concurrent.Executors')
|
||||
|
||||
const UTF_8 = "UTF-8"
|
||||
|
||||
const TrustAnyHostnameVerifier = new HostnameVerifier({ verify: () => true });
|
||||
const TrustAnyHostnameVerifier = new HostnameVerifier({ verify: () => true })
|
||||
|
||||
const SSLSocketFactory = function initSSLSocketFactory() {
|
||||
let sslContext = SSLContext.getInstance("TLS");
|
||||
let sslContext = SSLContext.getInstance("TLS")
|
||||
sslContext.init(null, [new X509TrustManager({
|
||||
getAcceptedIssuers: () => null,
|
||||
checkClientTrusted: () => { },
|
||||
checkServerTrusted: () => { }
|
||||
})], new SecureRandom());
|
||||
return sslContext.getSocketFactory();
|
||||
}();
|
||||
})], new SecureRandom())
|
||||
return sslContext.getSocketFactory()
|
||||
}()
|
||||
|
||||
interface Future<T> {
|
||||
cancel(): boolean;
|
||||
isCancelled(): boolean;
|
||||
isDone(): boolean;
|
||||
get(): T;
|
||||
cancel(): boolean
|
||||
isCancelled(): boolean
|
||||
isDone(): boolean
|
||||
get(): T
|
||||
}
|
||||
|
||||
enum ReadyState {
|
||||
@@ -50,14 +50,14 @@ type RequestMethod =
|
||||
| 'options' | 'OPTIONS'
|
||||
| 'post' | 'POST'
|
||||
| 'put' | 'PUT'
|
||||
| 'patch' | 'PATCH';
|
||||
| 'patch' | 'PATCH'
|
||||
type ResponseType =
|
||||
| 'arraybuffer'
|
||||
| 'blob'
|
||||
| 'document'
|
||||
| 'json'
|
||||
| 'text'
|
||||
| 'stream';
|
||||
| 'stream'
|
||||
type EventType =
|
||||
| 'load'
|
||||
| 'error'
|
||||
@@ -65,191 +65,191 @@ type EventType =
|
||||
| 'progress'
|
||||
| 'timeout'
|
||||
| 'loadend'
|
||||
| 'loadstart';
|
||||
type HttpHeader = { [key: string]: string };
|
||||
| 'loadstart'
|
||||
type HttpHeader = { [key: string]: string }
|
||||
|
||||
|
||||
const executor = Executors.newCachedThreadPool();
|
||||
const executor = Executors.newCachedThreadPool()
|
||||
|
||||
export class XMLHttpRequest {
|
||||
private _timeout: number;
|
||||
private _timeout: number
|
||||
private _responseType: ResponseType = 'text';
|
||||
private _withCredentials: boolean;
|
||||
private _withCredentials: boolean
|
||||
|
||||
private _readyState: ReadyState = ReadyState.UNSENT;
|
||||
|
||||
private _method: RequestMethod;
|
||||
private _url: string;
|
||||
private _async: boolean;
|
||||
private _mimeType: string;
|
||||
private _method: RequestMethod
|
||||
private _url: string
|
||||
private _async: boolean
|
||||
private _mimeType: string
|
||||
private _requestHeaders: HttpHeader = {};
|
||||
|
||||
private _status: number = 0;
|
||||
private _statusText: string = null;
|
||||
private _response: any;
|
||||
private _responseText: any;
|
||||
private _responseURL: string;
|
||||
private _response: any
|
||||
private _responseText: any
|
||||
private _responseURL: string
|
||||
private _responseHeaders: HttpHeader = {};
|
||||
|
||||
private _connection = null;
|
||||
|
||||
get timeout() {
|
||||
return this._timeout;
|
||||
return this._timeout
|
||||
}
|
||||
set timeout(timeout: number) {
|
||||
this._timeout = timeout
|
||||
}
|
||||
get readyState() {
|
||||
return this._readyState;
|
||||
return this._readyState
|
||||
}
|
||||
set responseType(type: ResponseType) {
|
||||
this._responseType = type;
|
||||
this._responseType = type
|
||||
}
|
||||
get responseType() {
|
||||
return this._responseType;
|
||||
return this._responseType
|
||||
}
|
||||
|
||||
get status() {
|
||||
return this._status;
|
||||
return this._status
|
||||
}
|
||||
get statusText() {
|
||||
return this._statusText;
|
||||
return this._statusText
|
||||
}
|
||||
get response() {
|
||||
return this._response || this.get();
|
||||
return this._response || this.get()
|
||||
}
|
||||
get responseText() {
|
||||
return this._responseText;
|
||||
return this._responseText
|
||||
}
|
||||
get responseXML() {
|
||||
return this._response;
|
||||
return this._response
|
||||
}
|
||||
get responseURL() {
|
||||
return this._responseURL;
|
||||
return this._responseURL
|
||||
}
|
||||
|
||||
public onload: () => void;
|
||||
public onerror: (ex: Error) => void;
|
||||
public onabort: () => void;
|
||||
public onprogress: () => void;
|
||||
public ontimeout: (ex: Error) => void;
|
||||
public onloadend: () => void;
|
||||
public onloadstart: () => void;
|
||||
public onreadystatechange: () => void;
|
||||
public onload: () => void
|
||||
public onerror: (ex: Error) => void
|
||||
public onabort: () => void
|
||||
public onprogress: () => void
|
||||
public ontimeout: (ex: Error) => void
|
||||
public onloadend: () => void
|
||||
public onloadstart: () => void
|
||||
public onreadystatechange: () => void
|
||||
|
||||
setRequestHeader(key: string, val: string) {
|
||||
this._requestHeaders[key] = val;
|
||||
this._requestHeaders[key] = val
|
||||
}
|
||||
getResponseHeader(key: string): string {
|
||||
return this._responseHeaders[key];
|
||||
return this._responseHeaders[key]
|
||||
}
|
||||
getAllResponseHeaders(): any {
|
||||
return this._responseHeaders;
|
||||
return this._responseHeaders
|
||||
}
|
||||
addEventListener(event: EventType, callback: Function) {
|
||||
this[`on${event.toLowerCase()}`] = callback;
|
||||
this[`on${event.toLowerCase()}`] = callback
|
||||
}
|
||||
overrideMimeType(mimeType: string) {
|
||||
this._mimeType = mimeType;
|
||||
this._mimeType = mimeType
|
||||
}
|
||||
open(method: RequestMethod, url: string, async: boolean = true, user?: string, password?: string) {
|
||||
if (this._readyState !== ReadyState.UNSENT) { throw new Error(`Error Status ${this._readyState}!`) }
|
||||
|
||||
this._method = method;
|
||||
this._url = url;
|
||||
this._async = async;
|
||||
this._method = method
|
||||
this._url = url
|
||||
this._async = async
|
||||
|
||||
this._connection = new URL(this._url).openConnection()
|
||||
if (this._connection instanceof HttpsURLConnection) {
|
||||
this._connection.setHostnameVerifier(TrustAnyHostnameVerifier);
|
||||
this._connection.setSSLSocketFactory(SSLSocketFactory);
|
||||
this._connection.setHostnameVerifier(TrustAnyHostnameVerifier)
|
||||
this._connection.setSSLSocketFactory(SSLSocketFactory)
|
||||
}
|
||||
this._connection.setRequestMethod(this._method);
|
||||
this._connection.setDoOutput(true);
|
||||
this._connection.setDoInput(true);
|
||||
this._connection.setConnectTimeout(this._timeout);
|
||||
this._connection.setReadTimeout(this._timeout);
|
||||
this._connection.setRequestMethod(this._method)
|
||||
this._connection.setDoOutput(true)
|
||||
this._connection.setDoInput(true)
|
||||
this._connection.setConnectTimeout(this._timeout)
|
||||
this._connection.setReadTimeout(this._timeout)
|
||||
|
||||
this.setReadyState(ReadyState.OPENED);
|
||||
this.setReadyState(ReadyState.OPENED)
|
||||
}
|
||||
send(body?: string | object): Future<string> {
|
||||
for (const header in this._requestHeaders) {
|
||||
this._connection.setRequestProperty(header, this._requestHeaders[header]);
|
||||
this._connection.setRequestProperty(header, this._requestHeaders[header])
|
||||
}
|
||||
if (this._readyState !== ReadyState.OPENED) { throw new Error(`Error Status ${this._readyState}!`) }
|
||||
let future = executor.submit(new Callable({ call: () => this._send(body) }));
|
||||
let future = executor.submit(new Callable({ call: () => this._send(body) }))
|
||||
if (!this._async) { future.get() }
|
||||
return future;
|
||||
return future
|
||||
}
|
||||
get() {
|
||||
if (this._response === undefined) {
|
||||
switch (this._responseType) {
|
||||
case "json":
|
||||
return this._response = JSON.parse(this._responseText);
|
||||
return this._response = JSON.parse(this._responseText)
|
||||
case "text":
|
||||
return this._response = this._responseText;
|
||||
return this._response = this._responseText
|
||||
default:
|
||||
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
|
||||
}
|
||||
}
|
||||
return this._response;
|
||||
return this._response
|
||||
}
|
||||
abort() {
|
||||
this._connection.disconnect();
|
||||
this.onabort && this.onabort();
|
||||
this._connection.disconnect()
|
||||
this.onabort && this.onabort()
|
||||
}
|
||||
|
||||
private _send(body?: string | object) {
|
||||
try {
|
||||
this._connection.connect();
|
||||
this.onloadstart && this.onloadstart();
|
||||
this._connection.connect()
|
||||
this.onloadstart && this.onloadstart()
|
||||
if (body) {
|
||||
let bodyType = Object.prototype.toString.call(body);
|
||||
let bodyType = Object.prototype.toString.call(body)
|
||||
if (typeof body !== "string") { throw new Error(`body(${bodyType}) must be string!`) }
|
||||
var out = this._connection.getOutputStream();
|
||||
out.write(new JavaString(body).getBytes(UTF_8));
|
||||
out.flush();
|
||||
out.close();
|
||||
var out = this._connection.getOutputStream()
|
||||
out.write(new JavaString(body).getBytes(UTF_8))
|
||||
out.flush()
|
||||
out.close()
|
||||
}
|
||||
this.setReadyState(ReadyState.LOADING);
|
||||
this._status = this._connection.getResponseCode();
|
||||
this._statusText = this._connection.getResponseMessage();
|
||||
this.setReadyState(ReadyState.LOADING)
|
||||
this._status = this._connection.getResponseCode()
|
||||
this._statusText = this._connection.getResponseMessage()
|
||||
if (this._status >= 0 && this._status < 300) {
|
||||
this._responseText = this.readOutput(this._connection.getInputStream());
|
||||
this._responseText = this.readOutput(this._connection.getInputStream())
|
||||
} else if (this._status >= 300 && this._status < 400) {
|
||||
this._responseURL = this.getResponseHeader('Location');
|
||||
this._responseURL = this.getResponseHeader('Location')
|
||||
} else {
|
||||
this._responseText = this.readOutput(this._connection.getErrorStream());
|
||||
this._responseText = this.readOutput(this._connection.getErrorStream())
|
||||
}
|
||||
this.setResponseHeaders(this._connection.getHeaderFields());
|
||||
this.onloadend && this.onloadend();
|
||||
this.setResponseHeaders(this._connection.getHeaderFields())
|
||||
this.onloadend && this.onloadend()
|
||||
} catch (ex) {
|
||||
if (ex instanceof SocketTimeoutException && this.ontimeout) {
|
||||
return this.ontimeout(ex)
|
||||
} else if (this.onerror) {
|
||||
return this.onerror(ex);
|
||||
return this.onerror(ex)
|
||||
}
|
||||
throw ex;
|
||||
throw ex
|
||||
} finally {
|
||||
this._connection.disconnect();
|
||||
this.setReadyState(ReadyState.DONE);
|
||||
this._connection.disconnect()
|
||||
this.setReadyState(ReadyState.DONE)
|
||||
}
|
||||
}
|
||||
|
||||
private setResponseHeaders(header: any) {
|
||||
header.forEach((key: string | number, value: string | any[]) => {
|
||||
this._responseHeaders[key] = value[value.length - 1]
|
||||
});
|
||||
this._responseHeaders[key + ''] = value[value.length - 1] + ''
|
||||
})
|
||||
}
|
||||
|
||||
private setReadyState(state: ReadyState) {
|
||||
this._readyState = state;
|
||||
this.onreadystatechange && this.onreadystatechange();
|
||||
this._readyState = state
|
||||
this.onreadystatechange && this.onreadystatechange()
|
||||
}
|
||||
|
||||
private readOutput(input: any) {
|
||||
var tempFile = Files.createTempFile('xhr', '.response');
|
||||
Files.copy(input, tempFile, StandardCopyOption['REPLACE_EXISTING']); tempFile.toFile().deleteOnExit();
|
||||
return new JavaString(Files.readAllBytes(tempFile), 'UTF-8');
|
||||
var tempFile = Files.createTempFile('xhr', '.response')
|
||||
Files.copy(input, tempFile, StandardCopyOption['REPLACE_EXISTING']); tempFile.toFile().deleteOnExit()
|
||||
return new JavaString(Files.readAllBytes(tempFile), 'UTF-8')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/plugin",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,16 +19,16 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/js-yaml": "^3.12.3",
|
||||
"@types/js-yaml": "^3.12.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0",
|
||||
"@ccms/i18n": "^0.8.0",
|
||||
"js-yaml": "^3.13.1"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/common": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3",
|
||||
"@ccms/i18n": "^0.9.3",
|
||||
"js-yaml": "^3.14.0"
|
||||
}
|
||||
}
|
||||
|
||||
36
packages/plugin/src/command.ts
Normal file
36
packages/plugin/src/command.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { command, plugin, server } from '@ccms/api'
|
||||
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||
import { getPluginCommandMetadata, getPluginTabCompleterMetadata } from './utils'
|
||||
|
||||
@provideSingleton(PluginCommandManager)
|
||||
export class PluginCommandManager {
|
||||
@inject(server.ServerChecker)
|
||||
private ServerChecker: server.ServerChecker
|
||||
@inject(command.Command)
|
||||
private CommandManager: command.Command
|
||||
|
||||
constructor() {
|
||||
process.on('plugin.before.enable', (plugin: plugin.Plugin) => this.registryCommand(plugin))
|
||||
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.unregistryCommand(plugin))
|
||||
}
|
||||
|
||||
private registryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||
for (const [_, cmd] of cmds) {
|
||||
let tab = tabs.get(cmd.name)
|
||||
if (!this.ServerChecker.check(cmd.servers)) { continue }
|
||||
this.CommandManager.on(pluginInstance, cmd.name, {
|
||||
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
||||
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private unregistryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
cmds.forEach(cmd => {
|
||||
this.CommandManager.off(pluginInstance, cmd.name)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,75 @@
|
||||
import * as yaml from 'js-yaml'
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import { plugin } from '@ccms/api'
|
||||
import { getPluginConfigMetadata } from './utils'
|
||||
|
||||
export interface PluginConfigLoader {
|
||||
load(content: string): any;
|
||||
dump(variable: any): string;
|
||||
load(content: string): any
|
||||
dump(variable: any): string
|
||||
}
|
||||
|
||||
export class YamlPluginConfig implements PluginConfigLoader {
|
||||
load(content: string) {
|
||||
return yaml.safeLoad(content);
|
||||
return yaml.safeLoad(content)
|
||||
}
|
||||
dump(variable: any): string {
|
||||
return yaml.safeDump(variable, { skipInvalid: true });
|
||||
return yaml.safeDump(variable, { skipInvalid: true })
|
||||
}
|
||||
}
|
||||
|
||||
export class JsonPluginConfig implements PluginConfigLoader {
|
||||
load(content: string) {
|
||||
return JSON.parse(content);
|
||||
return JSON.parse(content)
|
||||
}
|
||||
dump(variable: any): string {
|
||||
return JSON.stringify(variable);
|
||||
return JSON.stringify(variable)
|
||||
}
|
||||
}
|
||||
|
||||
const configLoaderMap = new Map<string, PluginConfigLoader>();
|
||||
const configLoaderMap = new Map<string, PluginConfigLoader>()
|
||||
|
||||
export function getConfigLoader(format: string) {
|
||||
if (!configLoaderMap.has(format)) { throw new Error(`Unsupport config format ${format} !`) }
|
||||
return configLoaderMap.get(format);
|
||||
return configLoaderMap.get(format)
|
||||
}
|
||||
|
||||
function loadConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
try {
|
||||
let configFile = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, config.name + '.' + config.format)
|
||||
let configFactory = getConfigLoader(config.format)
|
||||
if (!fs.exists(configFile)) {
|
||||
base.save(configFile, configFactory.dump(plugin[config.variable]))
|
||||
console.i18n("ms.plugin.manager.config.save.default", { plugin: plugin.description.name, name: config.name, format: config.format })
|
||||
} else {
|
||||
Object.defineProperty(plugin, config.variable, { value: configFactory.load(base.read(configFile)) })
|
||||
plugin[config.variable].save = () => {
|
||||
let result = configFactory.dump(plugin[config.variable])
|
||||
base.save(configFile, result)
|
||||
console.debug(`[${plugin.description.name}] Save Config ${config.variable} to file ${configFile} result ${result}`)
|
||||
}
|
||||
console.debug(`[${plugin.description.name}] Load Config ${config.variable} from file ${configFile} result ${JSON.stringify(plugin[config.variable])}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.config.load.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function saveConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
try {
|
||||
let configFile = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, config.name + '.' + config.format)
|
||||
let configFactory = getConfigLoader(config.format)
|
||||
if (!config.readonly) { base.save(configFile, configFactory.dump(plugin[config.variable])) }
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.config.save.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function init() {
|
||||
@@ -35,6 +77,8 @@ function init() {
|
||||
let yaml = new YamlPluginConfig()
|
||||
configLoaderMap.set("yml", yaml)
|
||||
configLoaderMap.set("yaml", yaml)
|
||||
process.on('plugin.before.load', loadConfig)
|
||||
process.on('plugin.after.load', saveConfig)
|
||||
}
|
||||
|
||||
init()
|
||||
|
||||
@@ -8,10 +8,10 @@ import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata
|
||||
* MiaoScript plugin
|
||||
* @param metadata PluginMetadata
|
||||
*/
|
||||
export function plugin(metadata: pluginApi.PluginMetadata) {
|
||||
export function plugin(metadata: pluginApi.PluginMetadata | any) {
|
||||
return function (target: any) {
|
||||
metadata.target = target
|
||||
metadata.type = "ioc"
|
||||
if (!metadata.source) metadata = { souece: metadata }
|
||||
metadata = { name: target.name, version: '1.0.0', author: 'Unknow', target, type: 'ioc', ...metadata }
|
||||
decorate(injectable(), target)
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target)
|
||||
const previousMetadata: Map<string, pluginApi.PluginMetadata> = getPluginMetadatas()
|
||||
@@ -30,10 +30,12 @@ export function plugin(metadata: pluginApi.PluginMetadata) {
|
||||
export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key
|
||||
metadata.target = target
|
||||
metadata.executor = key
|
||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginCommandMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
metadata.alias?.forEach((name) => previousMetadata.set(name, metadata))
|
||||
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor)
|
||||
}
|
||||
}
|
||||
@@ -46,10 +48,12 @@ export function tab(metadata: interfaces.CommandMetadata = {}) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key)
|
||||
if (!metadata.name) { return }
|
||||
metadata.target = target
|
||||
metadata.executor = key
|
||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginTabCompleterMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
metadata.alias?.forEach((name) => previousMetadata.set(name, metadata))
|
||||
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor)
|
||||
}
|
||||
}
|
||||
@@ -61,9 +65,11 @@ export function tab(metadata: interfaces.CommandMetadata = {}) {
|
||||
export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key
|
||||
metadata.target = target
|
||||
metadata.executor = key
|
||||
const previousMetadata: interfaces.ListenerMetadata[] = getPluginListenerMetadata(target)
|
||||
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor)
|
||||
Reflect.defineMetadata(METADATA_KEY.listener, metadata, target[key])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,23 +85,16 @@ export function config(metadata: interfaces.ConfigMetadata = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
function stage(metadata: interfaces.ExecMetadata = {}, stage: string) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key
|
||||
metadata.executor = key
|
||||
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
|
||||
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor)
|
||||
function stage(stage: string) {
|
||||
return (metadata: interfaces.ExecMetadata = {}) => {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key
|
||||
metadata.executor = key
|
||||
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
|
||||
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function load(metadata: interfaces.ExecMetadata = {}) {
|
||||
return stage(metadata, 'load')
|
||||
}
|
||||
|
||||
export function enable(metadata: interfaces.ExecMetadata = {}) {
|
||||
return stage(metadata, 'enable')
|
||||
}
|
||||
|
||||
export function disable(metadata: interfaces.ExecMetadata = {}) {
|
||||
return stage(metadata, 'disable')
|
||||
}
|
||||
export const load = stage('load')
|
||||
export const enable = stage('enable')
|
||||
export const disable = stage('disable')
|
||||
|
||||
33
packages/plugin/src/event.ts
Normal file
33
packages/plugin/src/event.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { event, plugin, server } from '@ccms/api'
|
||||
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||
import { getPluginListenerMetadata } from './utils'
|
||||
|
||||
@provideSingleton(PluginEventManager)
|
||||
export class PluginEventManager {
|
||||
@inject(server.ServerChecker)
|
||||
private ServerChecker: server.ServerChecker
|
||||
@inject(event.Event)
|
||||
private EventManager: event.Event
|
||||
|
||||
constructor() {
|
||||
process.on('plugin.before.enable', (plugin: plugin.Plugin) => this.registryListener(plugin))
|
||||
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.unregistryListener(plugin))
|
||||
}
|
||||
|
||||
private registryListener(pluginInstance: plugin.Plugin) {
|
||||
let events = getPluginListenerMetadata(pluginInstance)
|
||||
for (const event of events) {
|
||||
// ignore space listener
|
||||
if (!this.ServerChecker.check(event.servers)) { continue }
|
||||
// here must bind this to pluginInstance
|
||||
let exec = event.target[event.executor]
|
||||
let execBinded = exec.bind(pluginInstance)
|
||||
execBinded.executor = event.executor
|
||||
exec.off = this.EventManager.listen(pluginInstance, event.name, execBinded, event.priority, event.ignoreCancel)
|
||||
}
|
||||
}
|
||||
|
||||
private unregistryListener(pluginInstance: plugin.Plugin) {
|
||||
this.EventManager.disable(pluginInstance)
|
||||
}
|
||||
}
|
||||
@@ -25,12 +25,20 @@ export namespace interfaces {
|
||||
public disable() { }
|
||||
}
|
||||
export interface ExecMetadata extends plugin.BaseMetadata {
|
||||
/**
|
||||
* 执行器所在对象 用于绑定this
|
||||
*/
|
||||
target?: any
|
||||
/**
|
||||
* 执行器
|
||||
*/
|
||||
executor?: string
|
||||
}
|
||||
export interface CommandMetadata extends ExecMetadata {
|
||||
/**
|
||||
* 命令别名
|
||||
*/
|
||||
alias?: string[]
|
||||
/**
|
||||
* 命令描述
|
||||
*/
|
||||
@@ -68,5 +76,4 @@ export namespace interfaces {
|
||||
*/
|
||||
readonly?: boolean
|
||||
}
|
||||
export type PluginLike = Plugin | string
|
||||
}
|
||||
|
||||
@@ -1,24 +1,27 @@
|
||||
import { plugin } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
import { provideSingletonNamed } from "@ccms/container"
|
||||
|
||||
@provideSingleton(plugin.PluginLoader)
|
||||
const LOADER_TYPE_NAME = 'basic'
|
||||
|
||||
@provideSingletonNamed(plugin.PluginLoader, LOADER_TYPE_NAME)
|
||||
export class BasicLoader implements plugin.PluginLoader {
|
||||
type: string = 'basic'
|
||||
type: string = LOADER_TYPE_NAME
|
||||
|
||||
private pluginRequireMap: Map<string, any>
|
||||
|
||||
constructor() {
|
||||
this.pluginRequireMap = new Map()
|
||||
}
|
||||
require(target: any, result: any) {
|
||||
this.pluginRequireMap.set(target.toString(), result)
|
||||
return result
|
||||
require(loadMetadata: plugin.PluginLoadMetadata) {
|
||||
let metadata = loadMetadata.instance?.description
|
||||
if (metadata?.type == this.type) {
|
||||
loadMetadata.metadata = metadata
|
||||
loadMetadata.loaded = true
|
||||
this.pluginRequireMap.set(metadata.source.toString(), loadMetadata.instance)
|
||||
}
|
||||
return loadMetadata
|
||||
}
|
||||
build(metadata: plugin.PluginMetadata) {
|
||||
return this.pluginRequireMap.get(metadata.source.toString())
|
||||
}
|
||||
load(plugin: plugin.Plugin): void { }
|
||||
enable(plugin: plugin.Plugin): void { }
|
||||
disable(plugin: plugin.Plugin): void { }
|
||||
reload(plugin: plugin.Plugin): void { }
|
||||
}
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { plugin, server } from "@ccms/api"
|
||||
import { inject, ContainerInstance, Container, provideSingleton } from "@ccms/container"
|
||||
import { inject, ContainerInstance, Container, provideSingletonNamed } from "@ccms/container"
|
||||
|
||||
import { interfaces } from "../interfaces"
|
||||
import { getPluginStageMetadata, getPluginSources } from "../utils"
|
||||
|
||||
@provideSingleton(plugin.PluginLoader)
|
||||
const LOADER_TYPE_NAME = 'ioc'
|
||||
|
||||
@provideSingletonNamed(plugin.PluginLoader, LOADER_TYPE_NAME)
|
||||
export class IocLoader implements plugin.PluginLoader {
|
||||
type: string = 'ioc'
|
||||
type: string = LOADER_TYPE_NAME
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
@inject(server.ServerType)
|
||||
private serverType: string
|
||||
@inject(server.ServerChecker)
|
||||
private serverChecker: server.ServerChecker
|
||||
|
||||
private pluginMetadataMap: Map<string, plugin.PluginMetadata>
|
||||
|
||||
@@ -18,12 +20,16 @@ export class IocLoader implements plugin.PluginLoader {
|
||||
this.pluginMetadataMap = getPluginSources()
|
||||
}
|
||||
|
||||
require(target: any, result: any) {
|
||||
return this.pluginMetadataMap.get(target.toString())
|
||||
require(loadMetadata: plugin.PluginLoadMetadata) {
|
||||
let metadata = this.pluginMetadataMap.get(loadMetadata.file.toString())
|
||||
if (metadata && metadata.type == this.type) {
|
||||
loadMetadata.metadata = metadata
|
||||
loadMetadata.loaded = true
|
||||
}
|
||||
return loadMetadata
|
||||
}
|
||||
|
||||
build(metadata: plugin.PluginMetadata) {
|
||||
if (!this.allowProcess(metadata.servers)) { return }
|
||||
let pluginInstance: plugin.Plugin
|
||||
try {
|
||||
this.bindPlugin(metadata)
|
||||
@@ -68,23 +74,10 @@ export class IocLoader implements plugin.PluginLoader {
|
||||
}
|
||||
}
|
||||
|
||||
private allowProcess(servers: string[]) {
|
||||
// Not set servers -> allow
|
||||
if (!servers || !servers.length) return true
|
||||
// include !type -> deny
|
||||
let denyServers = servers.filter(svr => svr.startsWith("!"))
|
||||
if (denyServers.length !== 0) {
|
||||
return !denyServers.includes(`!${this.serverType}`)
|
||||
} else {
|
||||
// only include -> allow
|
||||
return servers.includes(this.serverType)
|
||||
}
|
||||
}
|
||||
|
||||
private stage(pluginInstance: plugin.Plugin, stageName: string) {
|
||||
let stages = getPluginStageMetadata(pluginInstance, stageName)
|
||||
for (const stage of stages) {
|
||||
if (!this.allowProcess(stage.servers)) { continue }
|
||||
if (!this.serverChecker.check(stage.servers)) { continue }
|
||||
console.i18n("ms.plugin.manager.stage.exec", { plugin: pluginInstance.description.name, name: stage.executor, stage: stageName, servers: stage.servers })
|
||||
try {
|
||||
pluginInstance[stage.executor].apply(pluginInstance)
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import i18n from '@ccms/i18n'
|
||||
import { plugin, server, command, event } from '@ccms/api'
|
||||
import { plugin, server, event } from '@ccms/api'
|
||||
import { inject, provideSingleton, Container, ContainerInstance } from '@ccms/container'
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
import './config'
|
||||
import { interfaces } from './interfaces'
|
||||
import { getConfigLoader } from './config'
|
||||
import { getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
|
||||
import { PluginTaskManager } from './task'
|
||||
import { PluginEventManager } from './event'
|
||||
import { PluginCommandManager } from './command'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
|
||||
@@ -15,14 +16,19 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
private container: Container
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
@inject(plugin.PluginFolder)
|
||||
private pluginFolder: string
|
||||
@inject(server.ServerType)
|
||||
private serverType: string
|
||||
@inject(command.Command)
|
||||
private CommandManager: command.Command
|
||||
@inject(event.Event)
|
||||
private EventManager: event.Event
|
||||
@inject(server.ServerChecker)
|
||||
private serverChecker: server.ServerChecker
|
||||
|
||||
@inject(PluginTaskManager)
|
||||
private taskManager: PluginTaskManager
|
||||
@inject(PluginEventManager)
|
||||
private eventManager: PluginEventManager
|
||||
@inject(PluginCommandManager)
|
||||
private commandManager: PluginCommandManager
|
||||
|
||||
private initialized: boolean = false
|
||||
|
||||
@@ -38,6 +44,11 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
|
||||
this.instanceMap = new Map()
|
||||
this.metadataMap = new Map()
|
||||
|
||||
// ignore unused
|
||||
this.taskManager
|
||||
this.eventManager
|
||||
this.commandManager
|
||||
}
|
||||
|
||||
initialize() {
|
||||
@@ -56,6 +67,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
this.loaderMap.set(loader.type, loader)
|
||||
})
|
||||
this.initialized = true
|
||||
process.emit('plugin.initialize')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,53 +76,81 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
this.initialize()
|
||||
for (const [, scanner] of this.sacnnerMap) {
|
||||
try {
|
||||
scanner.scan(folder).forEach(file => {
|
||||
this.loadPlugin(file, scanner)
|
||||
scanner.scan(folder).forEach(loadMetadata => {
|
||||
try {
|
||||
this.loadPlugin(scanner.load(loadMetadata))
|
||||
} catch (error) {
|
||||
console.error(`plugin scanner ${scanner.type} load ${loadMetadata.file} occurred error ${error}`)
|
||||
console.ex(error)
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(`plugin scanner ${scanner.type} occurred error ${error}`)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
process.emit('plugin.scan', folder)
|
||||
}
|
||||
|
||||
build(): void {
|
||||
this.buildPlugins()
|
||||
process.emit('plugin.build')
|
||||
}
|
||||
|
||||
private logStage(plugin: plugin.Plugin, stage: string) {
|
||||
console.i18n("ms.plugin.manager.stage", { stage, plugin: plugin.description.name, version: plugin.description.version, author: plugin.description.author })
|
||||
}
|
||||
|
||||
private runPluginStage(plugin: plugin.Plugin, stage: string, ext: Function) {
|
||||
private runPluginStage(plugin: plugin.Plugin, stage: string) {
|
||||
if (!plugin) { throw new Error(`can't run runPluginStage ${stage} because plugin is ${plugin}`) }
|
||||
try {
|
||||
this.logStage(plugin, i18n.translate(`ms.plugin.manager.stage.${stage}`))
|
||||
ext()
|
||||
process.emit(`plugin.before.${stage}`, plugin)
|
||||
this.runCatch(plugin, stage)
|
||||
this.runCatch(plugin, `${this.serverType}${stage}`)
|
||||
plugin.description.loader[stage](plugin)
|
||||
plugin.description.loadMetadata.loader[stage]?.(plugin)
|
||||
process.emit(`plugin.after.${stage}`, plugin)
|
||||
} catch (ex) {
|
||||
console.i18n("ms.plugin.manager.stage.exec.error", { plugin: plugin.description.name, executor: stage, error: ex })
|
||||
if (global.debug) { console.ex(ex) }
|
||||
}
|
||||
}
|
||||
|
||||
private loadPlugin(file: string, scanner: plugin.PluginScanner) {
|
||||
private loadPlugin(loadMetadata: plugin.PluginLoadMetadata) {
|
||||
if (!loadMetadata) { throw new Error('loadMetadata can\'t be undefiend when loadPlugin!') }
|
||||
if (loadMetadata.loaded) { throw new Error(`Plugin file ${loadMetadata.file} is already loaded by ${loadMetadata.loader?.type}!`) }
|
||||
try {
|
||||
let requireInstance = scanner.load(file)
|
||||
for (const [, loader] of this.loaderMap) {
|
||||
let metadata = loader.require(file, requireInstance)
|
||||
if (metadata && metadata.source && metadata.name) {
|
||||
metadata.loader = loader
|
||||
this.metadataMap.set(metadata.name, metadata)
|
||||
return metadata
|
||||
}
|
||||
if (this.loaderRequirePlugin(loadMetadata, loader)?.loaded) return loadMetadata.metadata
|
||||
}
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: file, ex: error })
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: loadMetadata.file, ex: error })
|
||||
console.ex(error)
|
||||
}
|
||||
console.console(`§efile §b${file} §ccan't load metadata. §eskip load!`)
|
||||
console.console(`§6scanner: §b${loadMetadata.scanner.type} §ccan\'t load §6file §b${loadMetadata.file}. §eskip!`)
|
||||
}
|
||||
|
||||
private loaderRequirePlugin(loadMetadata: plugin.PluginLoadMetadata, loader: plugin.PluginLoader) {
|
||||
try {
|
||||
if (loader.require(loadMetadata).loaded) {
|
||||
loadMetadata.loader = loader
|
||||
let metadata = loadMetadata.metadata
|
||||
if (this.metadataMap.has(metadata.name) && this.instanceMap.has(metadata.name)) {
|
||||
let oldMetadata = this.metadataMap.get(metadata.name)
|
||||
throw new Error(`Plugin ${oldMetadata.name} is already load from ${oldMetadata.source}...`)
|
||||
}
|
||||
this.metadataMap.set(metadata.name, metadata)
|
||||
metadata.loadMetadata = loadMetadata
|
||||
}
|
||||
return loadMetadata
|
||||
} catch (error) {
|
||||
if (global.debug) {
|
||||
console.console(`§6Loader §b${loader.type} §6load §a${loadMetadata.file} §cerror. §4Err: §c${error}`)
|
||||
console.ex(error)
|
||||
} else {
|
||||
console.warn(`Loader ${loader.type} load ${loadMetadata.file} error. Err: ${error}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -118,46 +158,35 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
* @param file java.io.File
|
||||
*/
|
||||
loadFromFile(file: string, scanner = this.sacnnerMap.get('file')): plugin.Plugin {
|
||||
if (!file) { throw new Error('plugin file can\'t be null!') }
|
||||
if (!scanner) { throw new Error('plugin scanner can\'t be null!') }
|
||||
let metadata = this.loadPlugin(file, scanner)
|
||||
let plugin = metadata.loader.build(metadata)
|
||||
if (!file) { throw new Error('plugin file can\'t be undefiend!') }
|
||||
if (!scanner) { throw new Error('plugin scanner can\'t be undefiend!') }
|
||||
let metadata = this.loadPlugin(scanner.load(scanner.read(file)))
|
||||
let plugin = this.buildPlugin(metadata)
|
||||
this.load(plugin)
|
||||
this.enable(plugin)
|
||||
return plugin
|
||||
}
|
||||
|
||||
load(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => {
|
||||
this.runPluginStage(plugin, 'load', () => {
|
||||
this.loadConfig(plugin)
|
||||
})
|
||||
})
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => this.runPluginStage(plugin, 'load'))
|
||||
}
|
||||
|
||||
enable(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => {
|
||||
this.runPluginStage(plugin, 'enable', () => {
|
||||
this.registryCommand(plugin)
|
||||
this.registryListener(plugin)
|
||||
})
|
||||
})
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => this.runPluginStage(plugin, 'enable'))
|
||||
}
|
||||
|
||||
disable(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => {
|
||||
this.runPluginStage(plugin, 'disable', () => {
|
||||
this.saveConfig(plugin)
|
||||
this.unregistryCommand(plugin)
|
||||
this.unregistryListener(plugin)
|
||||
})
|
||||
this.runPluginStage(plugin, 'disable')
|
||||
this.metadataMap.delete(plugin.description.name)
|
||||
this.instanceMap.delete(plugin.description.name)
|
||||
})
|
||||
}
|
||||
|
||||
reload(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((pl: plugin.Plugin) => {
|
||||
this.disable(pl)
|
||||
this.loadFromFile(pl.description.source, pl.description.scanner)
|
||||
this.loadFromFile(pl.description.loadMetadata.file, pl.description.loadMetadata.scanner)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -179,107 +208,31 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
|
||||
private checkAndGet(name: string | plugin.Plugin | undefined | any): Map<string, plugin.Plugin> | plugin.Plugin[] {
|
||||
if (name === undefined) throw new Error(`checkAndGet Plugin can't be undefiend!`)
|
||||
if (name == this.instanceMap) { return this.instanceMap }
|
||||
if (typeof name == 'string' && this.instanceMap.has(name)) { return [this.instanceMap.get(name)] }
|
||||
if (name instanceof interfaces.Plugin) { return [name as plugin.Plugin] }
|
||||
if (name.description || name.description.name) { return [name as plugin.Plugin] }
|
||||
if (name.description?.name) { return [name as plugin.Plugin] }
|
||||
throw new Error(`Plugin ${JSON.stringify(name)} not exist!`)
|
||||
}
|
||||
|
||||
private allowProcess(servers: string[]) {
|
||||
// Not set servers -> allow
|
||||
if (!servers || !servers.length) return true
|
||||
// include !type -> deny
|
||||
let denyServers = servers.filter(svr => svr.startsWith("!"))
|
||||
if (denyServers.length !== 0) {
|
||||
return !denyServers.includes(`!${this.serverType}`)
|
||||
} else {
|
||||
// only include -> allow
|
||||
return servers.includes(this.serverType)
|
||||
}
|
||||
}
|
||||
|
||||
private buildPlugins() {
|
||||
for (const [, metadata] of this.metadataMap) {
|
||||
let pluginInstance: plugin.Plugin
|
||||
if (!this.loaderMap.has(metadata.type)) {
|
||||
console.error(`§4无法加载插件 §c${metadata.name} §4请检查 §c${metadata.type} §4加载器是否正常启用!`)
|
||||
continue
|
||||
}
|
||||
(pluginInstance = this.loaderMap.get(metadata.type).build(metadata)) && this.instanceMap.set(metadata.name, pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
private loadConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
this.metadataMap.forEach((metadata) => {
|
||||
try {
|
||||
let configFile = fs.concat(root, this.pluginFolder, plugin.description.name, config.name + '.' + config.format)
|
||||
let configFactory = getConfigLoader(config.format)
|
||||
if (!fs.exists(configFile)) {
|
||||
base.save(configFile, configFactory.dump(plugin[config.variable]))
|
||||
console.i18n("ms.plugin.manager.config.save.default", { plugin: plugin.description.name, name: config.name, format: config.format })
|
||||
} else {
|
||||
plugin[config.variable] = configFactory.load(base.read(configFile))
|
||||
plugin[config.variable].save = () => {
|
||||
let result = configFactory.dump(plugin[config.variable])
|
||||
base.save(configFile, result)
|
||||
console.debug(`[${plugin.description.name}] Save Config ${config.variable} to file ${configFile} result ${result}`)
|
||||
}
|
||||
console.debug(`[${plugin.description.name}] Load Config ${config.variable} from file ${configFile} result ${JSON.stringify(plugin[config.variable])}`)
|
||||
}
|
||||
this.buildPlugin(metadata)
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.config.load.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
|
||||
console.ex(error)
|
||||
console.console(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private saveConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
try {
|
||||
let configFile = fs.concat(root, this.pluginFolder, plugin.description.name, config.name + '.' + config.format)
|
||||
let configFactory = getConfigLoader(config.format)
|
||||
if (!config.readonly) { base.save(configFile, configFactory.dump(plugin[config.variable])) }
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.config.save.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private registryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||
for (const [_, cmd] of cmds) {
|
||||
let tab = tabs.get(cmd.name)
|
||||
if (!this.allowProcess(cmd.servers)) { continue }
|
||||
this.CommandManager.on(pluginInstance, cmd.name, {
|
||||
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
||||
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private registryListener(pluginInstance: plugin.Plugin) {
|
||||
let events = getPluginListenerMetadata(pluginInstance)
|
||||
for (const event of events) {
|
||||
// ignore space listener
|
||||
if (!this.allowProcess(event.servers)) { continue }
|
||||
// here must bind this to pluginInstance
|
||||
this.EventManager.listen(pluginInstance, event.name, pluginInstance[event.executor].bind(pluginInstance))
|
||||
}
|
||||
}
|
||||
|
||||
private unregistryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
cmds.forEach(cmd => {
|
||||
this.CommandManager.off(pluginInstance, cmd.name)
|
||||
})
|
||||
}
|
||||
|
||||
private unregistryListener(pluginInstance: plugin.Plugin) {
|
||||
this.EventManager.disable(pluginInstance)
|
||||
private buildPlugin(metadata: plugin.PluginMetadata) {
|
||||
if (!this.loaderMap.has(metadata.type)) { throw new Error(`§4无法加载插件 §c${metadata.name} §4请检查 §c${metadata.type} §4加载器是否正常启用!`) }
|
||||
if (this.instanceMap.has(metadata.name)) { throw new Error(`Plugin ${metadata.name} is already load from ${metadata.source}...`) }
|
||||
if (!this.serverChecker.check(metadata.servers)) { throw new Error(`§6插件 §b${metadata.name} §c服务器类型不兼容(${metadata.servers.join(',')}) §6忽略加载...`) }
|
||||
let pluginInstance = this.loaderMap.get(metadata.type).build(metadata)
|
||||
if (!pluginInstance) { throw new Error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`) }
|
||||
this.instanceMap.set(metadata.name, pluginInstance)
|
||||
return pluginInstance
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,19 +2,26 @@ import { plugin } from "@ccms/api"
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import { provideSingletonNamed } from "@ccms/container"
|
||||
|
||||
@provideSingletonNamed(plugin.PluginScanner, 'file')
|
||||
export class JSFileScanner implements plugin.PluginScanner {
|
||||
type: string = 'file'
|
||||
const SCANNER_TYPE_NAME = 'file'
|
||||
|
||||
scan(target: any): string[] {
|
||||
return this.scanFolder(fs.concat(root, target))
|
||||
@provideSingletonNamed(plugin.PluginScanner, SCANNER_TYPE_NAME)
|
||||
export class JSFileScanner implements plugin.PluginScanner {
|
||||
type: string = SCANNER_TYPE_NAME
|
||||
|
||||
scan(target: any): plugin.PluginLoadMetadata[] {
|
||||
return this.scanFolder(fs.concat(root, target)).map((file) => this.read(file))
|
||||
}
|
||||
|
||||
load(file: string) {
|
||||
if (typeof file === "string") { return }
|
||||
this.updatePlugin(file)
|
||||
read(file: any): plugin.PluginLoadMetadata {
|
||||
return { file, type: this.type, scanner: this, loaded: false }
|
||||
}
|
||||
|
||||
load(metadata: plugin.PluginLoadMetadata): plugin.PluginLoadMetadata {
|
||||
if (metadata.type !== this.type) { return }
|
||||
this.updatePlugin(metadata.file)
|
||||
//@ts-ignore
|
||||
return require(file.toString(), { cache: false })
|
||||
metadata.instance = require(metadata.file.toString(), { cache: false })
|
||||
return metadata
|
||||
}
|
||||
|
||||
private scanFolder(folder: any): string[] {
|
||||
@@ -39,7 +46,7 @@ export class JSFileScanner implements plugin.PluginScanner {
|
||||
}
|
||||
|
||||
private updatePlugin(file: any) {
|
||||
var update = fs.file(fs.file(file.parentFile, 'update'), file.name)
|
||||
var update = fs.file(fs.file(fs.file(file).parentFile, 'update'), file.name)
|
||||
if (update.exists()) {
|
||||
console.i18n("ms.plugin.manager.build.update", { name: file.name })
|
||||
fs.move(update, file, true)
|
||||
|
||||
16
packages/plugin/src/task.ts
Normal file
16
packages/plugin/src/task.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { plugin, task } from '@ccms/api'
|
||||
import { provideSingleton, inject } from '@ccms/container'
|
||||
|
||||
@provideSingleton(PluginTaskManager)
|
||||
export class PluginTaskManager {
|
||||
@inject(task.TaskManager)
|
||||
private taskManager: task.TaskManager
|
||||
|
||||
constructor() {
|
||||
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.cancelTask(plugin))
|
||||
}
|
||||
|
||||
private cancelTask(pluginInstance: plugin.Plugin) {
|
||||
this.taskManager.disable(pluginInstance)
|
||||
}
|
||||
}
|
||||
50
packages/plugins/docs/MiaoReward.md
Normal file
50
packages/plugins/docs/MiaoReward.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# MiaoReward
|
||||
|
||||
## 插件简介
|
||||
- 还在为服务器收入不足而倒闭烦恼嘛
|
||||
- 还在为肝帝不氪金而烦恼嘛
|
||||
- 快来接入 喵式奖励
|
||||
- 通过QQ小程序广告 增加服务器收入
|
||||
|
||||
## 插件展示
|
||||
- 插件帮助
|
||||
- 扫码绑定
|
||||
- 查看个人信息
|
||||
- 兑换排行
|
||||
- 玩家兑换公告
|
||||
- 配置兑换比例
|
||||
- 服务器信息查询
|
||||
|
||||
## 插件命令
|
||||
```
|
||||
>mrd
|
||||
[17:56:54 INFO]: [MS][MRD] ====== [广告系统] 帮助菜单 ======
|
||||
[17:56:54 INFO]: [MS][MRD] /mrd bind 绑定圈云盒子
|
||||
[17:56:54 INFO]: [MS][MRD] /mrd query 查询当前账户
|
||||
[17:56:54 INFO]: [MS][MRD] /mrd draw <兑换数量> 兑换点券
|
||||
[17:56:54 INFO]: [MS][MRD] 由于您是管理员 以为您展示额外命令
|
||||
[17:56:54 INFO]: [MS][MRD] /mrd bind server 绑定服务器
|
||||
[17:56:54 INFO]: [MS][MRD] /mrd ratio <兑换比例> 设置喵币/点券兑换比例
|
||||
[17:56:54 INFO]: [MS][MRD] /mrd statistic 近期收入统计
|
||||
[17:56:54 INFO]: [MS][MRD] /mrd rank <boardcast>(是否公告) 今日兑换排行
|
||||
[17:56:54 INFO]: [MS][MRD] /mrd server 当前服务器信息
|
||||
[17:56:54 INFO]: [MS][MRD] 兑换比例设置说明: 默认比例为 0.001 => 1000喵币 兑换 1点券
|
||||
[17:56:54 INFO]: [MS][MRD] 注意 设置比例后 玩家兑换点券数量不能少于 1点券
|
||||
[17:56:54 INFO]: [MS][MRD] 比如 设置了0.001 那就是 玩家至少 1000喵币 才能兑换!
|
||||
```
|
||||
|
||||
## 插件安装/配置
|
||||
|
||||
### 基础准备工作
|
||||
- 申请内测服务器账号
|
||||
- QQ搜索小程序 `圈云盒子` 并登录
|
||||
### 服务器准备工作
|
||||
- 先安装 `MiaoScript` [站内地址]()
|
||||
- 执行 `mpm install MiaoReward`
|
||||
### 绑定服务器
|
||||
- 执行 `/mrd bind server`
|
||||
- 使用QQ扫码
|
||||
- 选择需要绑定的服务器
|
||||
- 完成绑定
|
||||
- 执行 `/mrd server` 查看服务器信息
|
||||
- 如需绑定多台 可以直接复制绑定之后的 `MiaoScript/plugins/MiaoReward/config.yml` 文件到多台服务器上 然后 `/mrd reload` 重载插件
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ccms/plugins",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript plugins package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -20,13 +20,16 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/spring-data-redis": "^0.0.2",
|
||||
"@javatypes/spring-web": "^0.0.2",
|
||||
"@javatypes/tomcat": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0",
|
||||
"@ccms/plugin": "^0.8.0"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3",
|
||||
"@ccms/plugin": "^0.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/// <reference types="@ccms/types/dist/typings/bukkit" />
|
||||
/// <reference types="@ccms/types/dist/typings/sponge" />
|
||||
/// <reference types="@ccms/types/dist/typings/bungee" />
|
||||
/// <reference types="@ccms/types/dist/typings/nukkit" />
|
||||
/// <reference types="@javatypes/bungee-api" />
|
||||
/// <reference types="@javatypes/spigot-api" />
|
||||
/// <reference types="@javatypes/sponge-api" />
|
||||
|
||||
import { server } from '@ccms/api';
|
||||
import { inject } from '@ccms/container';
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
/// <reference types="@ccms/types/dist/typings/bukkit" />
|
||||
/// <reference types="@ccms/types/dist/typings/sponge" />
|
||||
/// <reference types="@ccms/types/dist/typings/bungee" />
|
||||
/// <reference types="@javatypes/bungee-api" />
|
||||
/// <reference types="@javatypes/spigot-api" />
|
||||
/// <reference types="@javatypes/sponge-api" />
|
||||
|
||||
import { server, plugin as pluginApi, channel, constants } from '@ccms/api'
|
||||
import { inject, optional } from '@ccms/container';
|
||||
import { server, plugin as pluginApi, channel, constants, chat } from '@ccms/api'
|
||||
import { inject, optional } from '@ccms/container'
|
||||
import { plugin, interfaces, cmd, listener, tab, config, enable } from '@ccms/plugin'
|
||||
import Tellraw from '@ccms/common/dist/tellraw'
|
||||
|
||||
const ByteArrayInputStream = Java.type("java.io.ByteArrayInputStream");
|
||||
const ByteArrayOutputStream = Java.type("java.io.ByteArrayOutputStream");
|
||||
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
|
||||
const GZIPInputStream = Java.type("java.util.zip.GZIPInputStream");
|
||||
const GZIPOutputStream = Java.type("java.util.zip.GZIPOutputStream");
|
||||
const ByteArrayInputStream = Java.type("java.io.ByteArrayInputStream")
|
||||
const ByteArrayOutputStream = Java.type("java.io.ByteArrayOutputStream")
|
||||
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets")
|
||||
const GZIPInputStream = Java.type("java.util.zip.GZIPInputStream")
|
||||
const GZIPOutputStream = Java.type("java.util.zip.GZIPOutputStream")
|
||||
const BiConsumer = Java.type('java.util.function.BiConsumer')
|
||||
const ByteArray = Java.type("byte[]")
|
||||
|
||||
@@ -22,31 +22,31 @@ class MiaoMessage {
|
||||
private static MAX_MESSAGE_LENGTH = 32000;
|
||||
|
||||
private static copy(input, output) {
|
||||
let buffer = new ByteArray(1024);
|
||||
let n: number;
|
||||
let buffer = new ByteArray(1024)
|
||||
let n: number
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, n);
|
||||
output.write(buffer, 0, n)
|
||||
}
|
||||
input.close();
|
||||
output.close();
|
||||
input.close()
|
||||
output.close()
|
||||
}
|
||||
public static encode(input: any): any {
|
||||
return new MiaoMessage(input).encode();
|
||||
return new MiaoMessage(input).encode()
|
||||
}
|
||||
public static decode(input: any): MiaoMessage {
|
||||
let baos = new ByteArrayOutputStream();
|
||||
MiaoMessage.copy(new GZIPInputStream(new ByteArrayInputStream(input)), baos);
|
||||
return new MiaoMessage(baos.toString(StandardCharsets.UTF_8.name()));
|
||||
let baos = new ByteArrayOutputStream()
|
||||
MiaoMessage.copy(new GZIPInputStream(new ByteArrayInputStream(input)), baos)
|
||||
return new MiaoMessage(baos.toString(StandardCharsets.UTF_8.name()))
|
||||
}
|
||||
|
||||
// private String json;
|
||||
constructor(public json: any) { }
|
||||
|
||||
public encode(): any {
|
||||
let baos = new ByteArrayOutputStream();
|
||||
MiaoMessage.copy(new ByteArrayInputStream(this.json.getBytes(StandardCharsets.UTF_8)), new GZIPOutputStream(baos));
|
||||
if (baos.size() > MiaoMessage.MAX_MESSAGE_LENGTH) { return null; }
|
||||
return baos.toByteArray();
|
||||
let baos = new ByteArrayOutputStream()
|
||||
MiaoMessage.copy(new ByteArrayInputStream(this.json.getBytes(StandardCharsets.UTF_8)), new GZIPOutputStream(baos))
|
||||
if (baos.size() > MiaoMessage.MAX_MESSAGE_LENGTH) { return null }
|
||||
return baos.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,10 +54,12 @@ class MiaoMessage {
|
||||
export class MiaoChat extends interfaces.Plugin {
|
||||
@inject(server.Server)
|
||||
private Server: server.Server
|
||||
@inject(chat.Chat)
|
||||
private chat: chat.Chat
|
||||
@inject(channel.Channel)
|
||||
@optional() private Channel: channel.Channel
|
||||
|
||||
private channelOff: { off: () => void };
|
||||
private channelOff: { off: () => void }
|
||||
|
||||
@config()
|
||||
private config = {
|
||||
@@ -129,34 +131,34 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
private chatFormats: any[];
|
||||
private styleFormats: any;
|
||||
private chatFormats: any[]
|
||||
private styleFormats: any
|
||||
// 用于匹配 '[xx]' 聊天格式
|
||||
private FORMAT_PATTERN = /[\[]([^\[\]]+)[\]]/ig;
|
||||
|
||||
private PlaceholderAPI: { setPlaceholders: (player: any, str: string) => string };
|
||||
private PlaceholderAPI: { setPlaceholders: (player: any, str: string) => string }
|
||||
|
||||
load() {
|
||||
this.chatFormats = Object.values(this.config.ChatFormats);
|
||||
this.chatFormats.sort(this.compare('index'));
|
||||
this.initFormat(this.chatFormats);
|
||||
this.styleFormats = this.config.StyleFormats;
|
||||
this.chatFormats = Object.values(this.config.ChatFormats)
|
||||
this.chatFormats.sort(this.compare('index'))
|
||||
this.initFormat(this.chatFormats)
|
||||
this.styleFormats = this.config.StyleFormats
|
||||
}
|
||||
|
||||
private compare(prop: string) {
|
||||
return function (obj1: { [x: string]: any; }, obj2: { [x: string]: any; }) {
|
||||
var val1 = obj1[prop];
|
||||
var val2 = obj2[prop];
|
||||
return function (obj1: { [x: string]: any }, obj2: { [x: string]: any }) {
|
||||
var val1 = obj1[prop]
|
||||
var val2 = obj2[prop]
|
||||
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
|
||||
val1 = Number(val1);
|
||||
val2 = Number(val2);
|
||||
val1 = Number(val1)
|
||||
val2 = Number(val2)
|
||||
}
|
||||
if (val1 < val2) {
|
||||
return -1;
|
||||
return -1
|
||||
} else if (val1 > val2) {
|
||||
return 1;
|
||||
return 1
|
||||
} else {
|
||||
return 0;
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -164,7 +166,7 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
enable() {
|
||||
this.PlaceholderAPI = {
|
||||
setPlaceholders: (player: any, string: string) => {
|
||||
return string;
|
||||
return string
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,7 +179,7 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
// 尝试加载 Bukkit 的 PlaceholderAPI
|
||||
try {
|
||||
//@ts-ignore
|
||||
this.PlaceholderAPI = base.getClass("me.clip.placeholderapi.PlaceholderAPI").static;
|
||||
this.PlaceholderAPI = base.getClass("me.clip.placeholderapi.PlaceholderAPI").static
|
||||
this.logger.log('[PAPI] Found Bukkit PlaceholderAPI Hooking...')
|
||||
} catch (ex) {
|
||||
this.logger.console("§cCan't found me.clip.placeholderapi.PlaceholderAPI variable will not be replaced! Err: " + ex)
|
||||
@@ -187,14 +189,14 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
spongeenable() {
|
||||
// 尝试加载 Sponge 的 PlaceholderAPI
|
||||
try {
|
||||
var spongePapi = this.Server.getService('me.rojo8399.placeholderapi.PlaceholderService');
|
||||
var s = org.spongepowered.api.text.serializer.TextSerializers.formattingCode('§');
|
||||
var spongePapi = this.Server.getService('me.rojo8399.placeholderapi.PlaceholderService')
|
||||
var s = org.spongepowered.api.text.serializer.TextSerializers.formattingCode('§')
|
||||
if (spongePapi) {
|
||||
this.PlaceholderAPI = {
|
||||
setPlaceholders: (player: any, string: string) => {
|
||||
return s.serialize(spongePapi.replacePlaceholders(string, player, player));
|
||||
return s.serialize(spongePapi.replacePlaceholders(string, player, player))
|
||||
}
|
||||
};
|
||||
}
|
||||
this.logger.log('[PAPI] Found Sponge PlaceholderAPI Hooking...')
|
||||
}
|
||||
} catch (ex) {
|
||||
@@ -213,7 +215,7 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
this.channelOff = this.Channel?.listen(this, MiaoMessage.CHANNEL, (data, event: net.md_5.bungee.api.event.PluginMessageEvent) => {
|
||||
let bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||
if (event.getTag() == MiaoMessage.CHANNEL) {
|
||||
let origin = event.getSender().getAddress();
|
||||
let origin = event.getSender().getAddress()
|
||||
bungee.getServers().forEach(new BiConsumer({
|
||||
accept: (s, server) => {
|
||||
if (server.getAddress() != origin && server.getPlayers().size() > 0) {
|
||||
@@ -227,13 +229,13 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
|
||||
@cmd({ servers: ["bungee"] })
|
||||
mct(sender: any, command: string, args: string[]) {
|
||||
this.logger.log(sender, command, args);
|
||||
this.logger.log(sender, command, args)
|
||||
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||
}
|
||||
|
||||
@cmd({ servers: ["!bungee"] })
|
||||
mchat(sender: any, command: string, args: string[]) {
|
||||
this.logger.log(sender, command, args);
|
||||
this.logger.log(sender, command, args)
|
||||
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||
}
|
||||
|
||||
@@ -243,102 +245,97 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
|
||||
@listener({ servers: ['bukkit'] })
|
||||
AsyncPlayerChatEvent(event: org.bukkit.event.player.AsyncPlayerChatEvent) {
|
||||
this.sendChat(event.getPlayer(), event.getMessage(), function () {
|
||||
event.setCancelled(true);
|
||||
});
|
||||
this.sendChat(event.getPlayer(), event.getMessage(), () => event.setCancelled(true))
|
||||
}
|
||||
|
||||
@listener({ servers: ['sponge'] })
|
||||
MessageChannelEvent$Chat(event: org.spongepowered.api.event.message.MessageChannelEvent.Chat) {
|
||||
//@ts-ignore
|
||||
var player = event.getCause().first(org.spongepowered.api.entity.living.player.Player.class).orElse(null);
|
||||
var player = event.getCause().first(org.spongepowered.api.entity.living.player.Player.class).orElse(null)
|
||||
if (player == null) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
var plain = event.getRawMessage().toPlain();
|
||||
var plain = event.getRawMessage().toPlain()
|
||||
if (plain.startsWith(Tellraw.duplicateChar)) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
this.sendChat(player, plain, function () {
|
||||
event.setMessageCancelled(true)
|
||||
});
|
||||
this.sendChat(player, plain, () => event.setMessageCancelled(true))
|
||||
}
|
||||
|
||||
initFormat(chatFormats: any[]) {
|
||||
chatFormats.forEach(chatFormat => {
|
||||
var chat_format_str = chatFormat.format;
|
||||
var temp = [];
|
||||
var r: any[];
|
||||
var chat_format_str = chatFormat.format
|
||||
var temp = []
|
||||
var r: any[]
|
||||
while (r = this.FORMAT_PATTERN.exec(chat_format_str)) {
|
||||
temp.push(r[1]);
|
||||
temp.push(r[1])
|
||||
}
|
||||
var format_list = [];
|
||||
var format_list = []
|
||||
temp.forEach(t => {
|
||||
var arr = chat_format_str.split('[' + t + ']', 2);
|
||||
var arr = chat_format_str.split('[' + t + ']', 2)
|
||||
if (arr[0]) {
|
||||
format_list.push(arr[0]);
|
||||
format_list.push(arr[0])
|
||||
}
|
||||
format_list.push(t);
|
||||
chat_format_str = arr[1];
|
||||
});
|
||||
format_list.push(t)
|
||||
chat_format_str = arr[1]
|
||||
})
|
||||
if (chat_format_str) {
|
||||
format_list.push(chat_format_str);
|
||||
format_list.push(chat_format_str)
|
||||
}
|
||||
chatFormat.format_list = format_list;
|
||||
chatFormat.format_list = format_list
|
||||
})
|
||||
}
|
||||
|
||||
sendChat(player: any, plain: string, callback: { (): void; }) {
|
||||
var chat_format = this.getChatFormat(player);
|
||||
sendChat(player: any, plain: string, callback: { (): void }) {
|
||||
var chat_format = this.getChatFormat(player)
|
||||
if (!chat_format) {
|
||||
console.debug('未获得用户', player.getName(), '的 ChatRule 跳过执行...');
|
||||
return;
|
||||
console.debug('未获得用户', player.getName(), '的 ChatRule 跳过执行...')
|
||||
return
|
||||
}
|
||||
callback();
|
||||
var tr = Tellraw.create();
|
||||
callback()
|
||||
var tr = Tellraw.create()
|
||||
chat_format.format_list.forEach((format) => {
|
||||
var style = this.styleFormats[format];
|
||||
var style = this.styleFormats[format]
|
||||
if (style) {
|
||||
tr.then(this.replace(player, style.text.replace(/&(\w)/g, '§$1')));
|
||||
tr.then(this.replace(player, style.text.replace(/&(\w)/g, '§$1')))
|
||||
if (style.hover) {
|
||||
tr.tip(this.replace(player, style.hover.join('\n')));
|
||||
tr.tip(this.replace(player, style.hover.join('\n')))
|
||||
}
|
||||
if (style.click && style.click.type && style.click.command) {
|
||||
var command = this.replace(player, style.click.command);
|
||||
var command = this.replace(player, style.click.command)
|
||||
switch (style.click.type.toUpperCase()) {
|
||||
case "COMMAND":
|
||||
tr.command(command);
|
||||
break;
|
||||
tr.command(command)
|
||||
break
|
||||
case "OPENURL":
|
||||
tr.link(command);
|
||||
break;
|
||||
tr.link(command)
|
||||
break
|
||||
case "SUGGEST":
|
||||
tr.suggest(command);
|
||||
break;
|
||||
tr.suggest(command)
|
||||
break
|
||||
default:
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tr.then(this.replace(player, format));
|
||||
tr.then(this.replace(player, format))
|
||||
}
|
||||
});
|
||||
})
|
||||
let json = tr.then(this.replace(player, plain)).json()
|
||||
this.sendChatAll(json)
|
||||
this.Channel?.send(player, MiaoMessage.CHANNEL, MiaoMessage.encode(json))
|
||||
}
|
||||
|
||||
sendChatAll(json: string) {
|
||||
this.Server.getOnlinePlayers().forEach(player => this.Server.sendJson(player, json))
|
||||
this.Server.getOnlinePlayers().forEach(player => this.chat.sendJson(player, json))
|
||||
}
|
||||
|
||||
getChatFormat(player: any) {
|
||||
for (var i in this.chatFormats) {
|
||||
var format = this.chatFormats[i];
|
||||
for (let format of this.chatFormats) {
|
||||
if (player.hasPermission(format.permission)) {
|
||||
return format;
|
||||
return format
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
replace(player: any, target: string) {
|
||||
|
||||
105
packages/plugins/src/MiaoCoin.ts
Normal file
105
packages/plugins/src/MiaoCoin.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { constants, task, server, channel } from "@ccms/api"
|
||||
import { JSPlugin, interfaces, Cmd, Tab, Listener, Config } from "@ccms/plugin"
|
||||
|
||||
import { QRCode, QRErrorCorrectLevel } from '@ccms/common/dist/qrcode'
|
||||
|
||||
import { inject, JSClass, optional } from '@ccms/container'
|
||||
import http from '@ccms/common/dist/http'
|
||||
import chat from '@ccms/bukkit/dist/enhance/chat'
|
||||
|
||||
const MapView = Java.type('org.bukkit.map.MapView')
|
||||
const Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
const MapRenderer = Java.type('org.bukkit.map.MapRenderer')
|
||||
const ItemStack = Java.type('org.bukkit.inventory.ItemStack')
|
||||
const Material = Java.type('org.bukkit.Material')
|
||||
|
||||
const BufferedImage = Java.type('java.awt.image.BufferedImage')
|
||||
const Graphics2D = Java.type('java.awt.Graphics2D')
|
||||
const Color = Java.type('java.awt.Color')
|
||||
const Image = Java.type('java.awt.Image')
|
||||
const Font = Java.type('java.awt.Font')
|
||||
const RenderingHints = Java.type('java.awt.RenderingHints')
|
||||
|
||||
class QRCodeRender {
|
||||
private _proxy
|
||||
constructor(image: any) {
|
||||
const ProxyAdapter = Java.extend(MapRenderer, {
|
||||
render: (_mapView, mapCanvas) => {
|
||||
mapCanvas.drawImage(0, 0, image)
|
||||
}
|
||||
})
|
||||
this._proxy = new ProxyAdapter()
|
||||
}
|
||||
getHandler() {
|
||||
return this._proxy
|
||||
}
|
||||
}
|
||||
|
||||
interface PlaceholderAPI {
|
||||
registerPlaceholderHook: (key: string, onPlaceholderRequest: (player, s) => string) => void
|
||||
setPlaceholders: (player: any, str: string) => string
|
||||
}
|
||||
|
||||
@JSPlugin({ version: '1.0.0', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||
export class MiaoCoin extends interfaces.Plugin {
|
||||
@inject(server.Server)
|
||||
private server: server.Server
|
||||
@inject(task.TaskManager)
|
||||
private taskManager: task.TaskManager
|
||||
|
||||
@JSClass('me.clip.placeholderapi.PlaceholderAPI')
|
||||
private PlaceholderAPI: PlaceholderAPI
|
||||
@JSClass('me.clip.placeholderapi.PlaceholderHook')
|
||||
private PlaceholderHook: any
|
||||
|
||||
@Config()
|
||||
private config = {
|
||||
MySQL: {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
enable() {
|
||||
if (!this.PlaceholderAPI) {
|
||||
console.console("§cCan't found me.clip.placeholderapi.PlaceholderAPI variable will not be replaced!")
|
||||
} else {
|
||||
this.PlaceholderAPI.registerPlaceholderHook("mcn", new this.PlaceholderHook({
|
||||
onPlaceholderRequest: (player: any, s: string) => {
|
||||
switch (s.toLowerCase()) {
|
||||
case "has":
|
||||
return ''
|
||||
case "add":
|
||||
return ''
|
||||
case "remove":
|
||||
return ''
|
||||
default:
|
||||
}
|
||||
return `未知的参数: ${s}`
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
disable() {
|
||||
// {"app":"com.tencent.autoreply","desc":"","view":"autoreply","ver":"0.0.0.1","prompt":"[动画表情]","meta":{"metadata":{"title":"点击蓝色字体有惊喜","buttons":[{"slot":1,"action_data":"我是傻逼","name":"点我","action":"notify"}],"type":"guest","token":"LAcV49xqyE57S17B8ZT6FU7odBveNMYJzux288tBD3c="}},"config":{"forward":1,"showSender":1}}
|
||||
}
|
||||
|
||||
@Cmd()
|
||||
mrd(sender: any, command: string, args: string[]) {
|
||||
let cmd = args[0] || 'help'
|
||||
let cmdKey = 'cmd' + cmd
|
||||
if (!this[cmdKey]) {
|
||||
console.sender(sender, '§4未知的子命令: §c' + cmd)
|
||||
console.sender(sender, `§6请执行 §b/${command} §ahelp §6查看帮助!`)
|
||||
return
|
||||
}
|
||||
args.shift()
|
||||
this.taskManager.create(() => this[cmdKey](sender, ...args)).async().submit()
|
||||
}
|
||||
|
||||
@Tab()
|
||||
tabmrd(sender: any, _command: any, args: string | any[]) {
|
||||
if (args.length === 1) return ['help', 'bind', 'show', 'query', 'draw', "ratio"]
|
||||
if (args.length === 2 && args[0] === "bind" && sender.isOp()) return ['server']
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@ccms/types/dist/typings/bukkit" />
|
||||
/// <reference types="@ccms/types/dist/typings/sponge" />
|
||||
/// <reference types="@ccms/types/dist/typings/bungee" />
|
||||
|
||||
import { plugin as pluginApi, server, task, constants } from '@ccms/api'
|
||||
import { plugin as pluginApi, server, task, constants, command } from '@ccms/api'
|
||||
import { plugin, interfaces, cmd, tab, enable, config, disable } from '@ccms/plugin'
|
||||
import { inject, ContainerInstance, Container } from '@ccms/container'
|
||||
import io, { Server as SocketIOServer, Socket as SocketIOSocket } from '@ccms/websocket'
|
||||
@@ -30,6 +27,8 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
private serverType: string
|
||||
@inject(server.Server)
|
||||
private server: server.Server
|
||||
@inject(command.Command)
|
||||
private command: command.Command
|
||||
@inject(task.TaskManager)
|
||||
private task: task.TaskManager
|
||||
@inject(pluginApi.PluginManager)
|
||||
@@ -251,7 +250,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
client.emit('log', `§6命令: §b${cmd} §a执行成功!`)
|
||||
})
|
||||
client.on('tabComplate', (input, index, callback) => {
|
||||
callback && callback(this.server.tabComplete(this.server.getConsoleSender(), input, index))
|
||||
callback?.(this.command.tabComplete(this.server.getConsoleSender(), input, index))
|
||||
})
|
||||
client.on('exec', (code) => {
|
||||
try {
|
||||
|
||||
87
packages/plugins/src/MiaoGUI.ts
Normal file
87
packages/plugins/src/MiaoGUI.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { constants, channel, server } from "@ccms/api"
|
||||
import { JSPlugin, interfaces, Cmd, Tab } from "@ccms/plugin"
|
||||
import { inject, optional } from '@ccms/container'
|
||||
|
||||
const StandardCharsets = Java.type('java.nio.charset.StandardCharsets')
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
|
||||
@JSPlugin({ author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||
export class MiaoGUI extends interfaces.Plugin {
|
||||
@inject(server.Server)
|
||||
private server: server.Server
|
||||
@inject(channel.Channel)
|
||||
@optional()
|
||||
private channel: channel.Channel
|
||||
|
||||
private CHANNEL_NAME = `${MiaoGUI.name}:NORMAL`.toLowerCase();
|
||||
private channelOff: { off: () => void }
|
||||
|
||||
enable() {
|
||||
this.channelOff = this.channel?.listen(this, this.CHANNEL_NAME, (data) => {
|
||||
this.logger.info('MiaoGUI', new JavaString(data))
|
||||
})
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.channelOff?.off()
|
||||
}
|
||||
|
||||
@Cmd()
|
||||
mgui(sender: any, command: string, args: string[]) {
|
||||
let cmd = args[0] || 'help'
|
||||
let cmdKey = 'cmd' + cmd
|
||||
if (!this[cmdKey]) {
|
||||
console.sender(sender, '§4未知的子命令: §c' + cmd)
|
||||
console.sender(sender, `§6请执行 §b/${command} §ahelp §6查看帮助!`)
|
||||
return
|
||||
}
|
||||
args.shift()
|
||||
this[cmdKey](sender, ...args)
|
||||
}
|
||||
|
||||
cmdhhelp(sender: any) {
|
||||
this.logger.sender(sender, '')
|
||||
}
|
||||
|
||||
cmdrun(sender: any, ...args: string[]) {
|
||||
this.send(sender, "run", { cmd: args.join(' ') })
|
||||
}
|
||||
|
||||
cmdconfig(sender: org.bukkit.entity.Player) {
|
||||
this.send(sender, "config")
|
||||
}
|
||||
|
||||
cmdopen(sender: any, name: string) {
|
||||
this.send(sender, "open", { name })
|
||||
}
|
||||
|
||||
cmdopenfor(sender: any, target: string, name: string) {
|
||||
let player = this.server.getPlayer(target)
|
||||
if (!player) { return this.logger.sender(sender, `§c玩家 ${target} 不在线或不存在!`) }
|
||||
this.send(player, "open", { name })
|
||||
}
|
||||
|
||||
cmdadd(sender: any, type: string, ...param: string[]) {
|
||||
if (!type) return this.logger.sender(sender, '§c组件类型不得为空!')
|
||||
this.send(sender, "add", { type, param })
|
||||
}
|
||||
|
||||
cmdclear(sender: org.bukkit.entity.Player) {
|
||||
this.send(sender, "clear")
|
||||
}
|
||||
|
||||
@Tab()
|
||||
tabmgui(args: string[]) {
|
||||
if (args.length == 1) return ['open', 'openfor', 'config', 'add', 'clear']
|
||||
if (args.length == 2) {
|
||||
switch (args[0]) {
|
||||
case "add":
|
||||
return ['text', 'image', 'broadcast']
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private send(target: any, type: string, data: any = {}) {
|
||||
this.channel?.send(target, this.CHANNEL_NAME, new JavaString(JSON.stringify({ type, data })).getBytes(StandardCharsets.UTF_8))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/// <reference types="@ccms/types" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
|
||||
import { task, server } from "@ccms/api";
|
||||
import { inject } from "@ccms/container";
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
/// <reference types="@ccms/types" />
|
||||
|
||||
import { task, server, constants } from "@ccms/api";
|
||||
import { inject } from "@ccms/container";
|
||||
import { plugin, interfaces, cmd } from "@ccms/plugin";
|
||||
|
||||
758
packages/plugins/src/MiaoReward.ts
Normal file
758
packages/plugins/src/MiaoReward.ts
Normal file
@@ -0,0 +1,758 @@
|
||||
import { constants, task, server, channel, chat } from "@ccms/api"
|
||||
import { JSPlugin, interfaces, Cmd, Tab, Listener, Config } from "@ccms/plugin"
|
||||
|
||||
import { QRCode, QRErrorCorrectLevel } from '@ccms/common/dist/qrcode'
|
||||
|
||||
import { Autowired, JSClass, optional, inject } from '@ccms/container'
|
||||
import http from '@ccms/common/dist/http'
|
||||
|
||||
let MapView
|
||||
let Bukkit
|
||||
let MapRenderer
|
||||
let ItemStack
|
||||
let Material
|
||||
|
||||
try {
|
||||
MapView = Java.type('org.bukkit.map.MapView')
|
||||
Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
MapRenderer = Java.type('org.bukkit.map.MapRenderer')
|
||||
ItemStack = Java.type('org.bukkit.inventory.ItemStack')
|
||||
Material = Java.type('org.bukkit.Material')
|
||||
} catch (error) {
|
||||
}
|
||||
|
||||
const BufferedImage = Java.type('java.awt.image.BufferedImage')
|
||||
const Color = Java.type('java.awt.Color')
|
||||
|
||||
class QRCodeRender {
|
||||
private _proxy
|
||||
private image
|
||||
private rendered = false
|
||||
constructor() {
|
||||
const MapRendererAdapter = Java.extend(MapRenderer, {
|
||||
render: (_mapView, mapCanvas, _player) => {
|
||||
if (this.rendered) return
|
||||
if (this.image) {
|
||||
mapCanvas.drawImage(0, 0, this.image)
|
||||
}
|
||||
this.rendered = true
|
||||
}
|
||||
})
|
||||
this._proxy = new MapRendererAdapter()
|
||||
}
|
||||
setImage(image) {
|
||||
this.image = image
|
||||
this.rendered = false
|
||||
}
|
||||
getHandler() {
|
||||
return this._proxy
|
||||
}
|
||||
}
|
||||
|
||||
interface PlaceholderAPI {
|
||||
registerPlaceholderHook: (key: string, onPlaceholderRequest: (player, s) => string) => void
|
||||
setPlaceholders: (player: any, str: string) => string
|
||||
}
|
||||
|
||||
@JSPlugin({ prefix: 'MRD', version: '1.2.3', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||
export class MiaoReward extends interfaces.Plugin {
|
||||
private serverInfo: any
|
||||
private cacheBindUuid = ''
|
||||
private zeroMapView = undefined
|
||||
private zeroMapRender: QRCodeRender = undefined
|
||||
private isBinding = false
|
||||
private bindingUser = 'unknow'
|
||||
private bindingTask = undefined
|
||||
private bindingLeftTime = 45
|
||||
private bindingNotify = new java.util.HashSet<org.bukkit.entity.Player>()
|
||||
private drawCooldown = new Map<string, number>()
|
||||
|
||||
@Autowired()
|
||||
private chat: chat.Chat
|
||||
@Autowired()
|
||||
private server: server.Server
|
||||
@Autowired()
|
||||
private taskManager: task.TaskManager
|
||||
@Autowired()
|
||||
private channel: channel.Channel
|
||||
@Autowired()
|
||||
private bungee: channel.proxy.BungeeCord
|
||||
|
||||
@Config()
|
||||
private config = {
|
||||
prefix: '§6[§b广告系统§6]§r',
|
||||
serverId: '',
|
||||
serverToken: '',
|
||||
drawCommand: 'p give %player_name% %amount%',
|
||||
drawCooldown: 300
|
||||
}
|
||||
|
||||
@JSClass('me.clip.placeholderapi.PlaceholderAPI')
|
||||
private PlaceholderAPI: PlaceholderAPI
|
||||
@JSClass('me.clip.placeholderapi.PlaceholderHook')
|
||||
private PlaceholderHook: any
|
||||
|
||||
private isBungeeCord = undefined
|
||||
private channelOff: { off: () => void }
|
||||
|
||||
load() {
|
||||
this.config.prefix = this.config.prefix || '§6[§b广告系统§6]§r'
|
||||
this.config.drawCommand = this.config.drawCommand || 'p give %player_name% %amount%'
|
||||
this.config.drawCooldown = this.config.drawCooldown || 300
|
||||
this.updateServerInfo()
|
||||
}
|
||||
|
||||
private updateServerInfo(player?: any) {
|
||||
this.taskManager.create(() => {
|
||||
if (this.config.serverId) {
|
||||
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken
|
||||
})
|
||||
if (result.code == 200) {
|
||||
this.serverInfo = result.data
|
||||
if (player) this.bungee.for(player).forward("ALL", "MiaoReward", { type: "updateServerInfo", data: result.data }).send()
|
||||
}
|
||||
}
|
||||
}).async().submit()
|
||||
}
|
||||
|
||||
@JSClass('com.google.common.io.ByteStreams')
|
||||
private ByteStreams: any
|
||||
|
||||
enable() {
|
||||
this.initPlaceholderAPI()
|
||||
this.initBungeeCord()
|
||||
this.initZeroMap()
|
||||
}
|
||||
|
||||
private initBungeeCord() {
|
||||
this.channelOff = this.channel?.listen(this, 'BungeeCord', (data) => {
|
||||
if (!this.isBungeeCord) {
|
||||
this.isBungeeCord = true
|
||||
this.PlayerJoinEvent['off']()
|
||||
}
|
||||
let input = this.ByteStreams.newDataInput(data)
|
||||
let subChannel = input.readUTF()
|
||||
switch (subChannel) {
|
||||
case "GetServer":
|
||||
this.isBungeeCord = true
|
||||
let serverName = input.readUTF()
|
||||
break
|
||||
case "MiaoReward":
|
||||
this.readForward(input)
|
||||
break
|
||||
}
|
||||
})
|
||||
let players = this.server.getOnlinePlayers()
|
||||
if (players.length) this.bungeeCordDetect(players[0])
|
||||
}
|
||||
|
||||
cmdrun(sender: any, ...args: any[]) {
|
||||
try {
|
||||
let tfunc = new Function(`return '§a返回结果: §r'+ eval(${JSON.stringify(args.join(' '))});`)
|
||||
this.logger.sender(sender, tfunc.apply(this) + '')
|
||||
} catch (ex) {
|
||||
this.logger.sender(sender, this.logger.stack(ex))
|
||||
}
|
||||
}
|
||||
|
||||
private readForward(input) {
|
||||
let message = JSON.parse(input.readUTF())
|
||||
console.log(message)
|
||||
switch (message.type) {
|
||||
case "updateServerInfo":
|
||||
this.serverInfo = message.data
|
||||
console.console(this.config.prefix, '§6兑换比例已更新为:§a', message.data.ratio)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private initPlaceholderAPI() {
|
||||
if (!this.PlaceholderAPI) {
|
||||
console.console("§cCan't found me.clip.placeholderapi.PlaceholderAPI variable will not be replaced!")
|
||||
} else {
|
||||
this.PlaceholderAPI.registerPlaceholderHook("mrd", new this.PlaceholderHook({
|
||||
onPlaceholderRequest: (player: any, s: string) => {
|
||||
switch (s.toLowerCase()) {
|
||||
case "server":
|
||||
case "bserver":
|
||||
default:
|
||||
}
|
||||
return "未知的参数"
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
private initZeroMap() {
|
||||
this.taskManager.create(() => {
|
||||
this.zeroMapRender = new QRCodeRender()
|
||||
this.zeroMapView = Bukkit.getMap(0) || Bukkit.createMap(Bukkit.getWorlds()[0])
|
||||
this.zeroMapView.setScale(MapView.Scale.FARTHEST)
|
||||
this.zeroMapView.getRenderers().forEach(r => this.zeroMapView.removeRenderer(r))
|
||||
this.zeroMapView.addRenderer(this.zeroMapRender.getHandler())
|
||||
}).submit()
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.server.getOnlinePlayers().forEach(p => this.checkAndClear(p))
|
||||
this.channelOff?.off()
|
||||
}
|
||||
|
||||
@Cmd()
|
||||
mrd(sender: any, command: string, args: string[]) {
|
||||
let cmd = args[0] || 'help'
|
||||
let cmdKey = 'cmd' + cmd
|
||||
if (!this[cmdKey]) {
|
||||
console.sender(sender, '§4未知的子命令: §c' + cmd)
|
||||
console.sender(sender, `§6请执行 §b/${command} §ahelp §6查看帮助!`)
|
||||
return
|
||||
}
|
||||
args.shift()
|
||||
this.taskManager.create(() => this[cmdKey](sender, ...args)).async().submit()
|
||||
}
|
||||
|
||||
private scanAuth(sender: org.bukkit.entity.Player, scanType: string, scanObj: { title: string, content: string }, success: (token: string, user: any) => void, cancel?: () => void) {
|
||||
this.chat.sendTitle(sender, this.config.prefix, '§a正在获取授权二维码...')
|
||||
this.logger.sender(sender, '§a正在获取授权二维码...')
|
||||
let scan = this.httpPost('https://reward.yumc.pw/auth/scan', { ...scanObj, type: scanType })
|
||||
if (scan.code == 200) {
|
||||
let sync = { scaned: false }
|
||||
this.taskManager.create(() => {
|
||||
let result = this.httpPost('https://reward.yumc.pw/auth/scanCheck', {
|
||||
token: scan.data.token,
|
||||
type: scanType,
|
||||
status: 'noscan'
|
||||
})
|
||||
sync.scaned = true
|
||||
if (result.code == 200 && result.data.status == "scaned") {
|
||||
this.chat.sendTitle(sender, "§3已扫码", "§a请在手机上确认")
|
||||
let result = this.httpPost('https://reward.yumc.pw/auth/scanCheck', {
|
||||
token: scan.data.token,
|
||||
type: scanType,
|
||||
status: 'scaned'
|
||||
})
|
||||
if (result.code == 200) {
|
||||
if (result.data.status == "confirm") {
|
||||
this.chat.sendTitle(sender, '§3扫码完成')
|
||||
success(scan.data.token, result.data.user)
|
||||
} else if (result.data.status == "cancel") {
|
||||
this.chat.sendTitle(sender, '§c已取消授权')
|
||||
cancel?.()
|
||||
} else {
|
||||
this.chat.sendTitle(sender, "§c未知的结果", result.data.status)
|
||||
}
|
||||
} else {
|
||||
this.chat.sendTitle(sender, "§4扫码异常", result.msg)
|
||||
}
|
||||
}
|
||||
sync.scaned = true
|
||||
}).async().submit()
|
||||
this.setItemAndTp(sender, scan.data.url, sync)
|
||||
this.chat.sendTitle(sender, '')
|
||||
} else {
|
||||
this.logger.sender(sender, '§4授权二维码获取失败!')
|
||||
}
|
||||
}
|
||||
|
||||
private bindCheck(sender: org.bukkit.entity.Player, cooldown: number) {
|
||||
if (this.isBinding) {
|
||||
let bindUser = Bukkit.getPlayerExact(this.bindingUser)
|
||||
if (bindUser && bindUser.isOnline() && this.isQrCodeItem(bindUser.getItemInHand())[0]) {
|
||||
this.bindingNotify.add(sender)
|
||||
this.logger.sender(sender, [
|
||||
"§c当前 §a" + this.bindingUser + " §c玩家正在扫码",
|
||||
"§6请等待 §e" + this.bindingLeftTime + "秒 §6后重试...",
|
||||
"§a玩家操作完成后将会通知您继续操作..."
|
||||
])
|
||||
return true
|
||||
}
|
||||
}
|
||||
if (this.drawCooldown.has(sender.getName()) && !sender.isOp()) {
|
||||
let leftTime = cooldown - (Date.now() - this.drawCooldown.get(sender.getName())) / 1000
|
||||
if (leftTime > 0) {
|
||||
this.logger.sender(sender, `§c扫码功能冷却中 剩余 ${leftTime} 秒!`)
|
||||
return true
|
||||
}
|
||||
}
|
||||
this.drawCooldown.set(sender.getName(), Date.now())
|
||||
this.isBinding = true
|
||||
this.bindingUser = sender.getName()
|
||||
this.bindingNotify.clear()
|
||||
return false
|
||||
}
|
||||
|
||||
cmdbind(sender: org.bukkit.entity.Player, server: boolean) {
|
||||
if (this.bindCheck(sender, 60)) return
|
||||
if (sender.getItemInHand()?.getType() !== Material.AIR) { return this.logger.sender(sender, "§c请空手执行此命令!") }
|
||||
if (server) {
|
||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4您没有配置服务器的权限!') }
|
||||
this.bindServer(sender)
|
||||
} else {
|
||||
if (!this.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||
this.bindUser(sender)
|
||||
}
|
||||
}
|
||||
|
||||
cmddraw(sender: org.bukkit.entity.Player, amount: number) {
|
||||
amount = Number(amount)
|
||||
if (!Number.isInteger(amount)) {
|
||||
return this.logger.sender(sender, '§4金额必须是数字!')
|
||||
}
|
||||
if (amount % 100 !== 0) {
|
||||
return this.logger.sender(sender, '§4金额必须是100倍数!')
|
||||
}
|
||||
if (this.bindCheck(sender, this.config.drawCooldown)) { return }
|
||||
this.scanAuth(sender,
|
||||
'draw', {
|
||||
title: '兑换授权',
|
||||
content: [
|
||||
"是否授权 " + this.serverInfo.name + " 兑换喵币",
|
||||
"兑换玩家: " + sender.getName(),
|
||||
"兑换数量: " + amount,
|
||||
"兑换比例: " + parseFloat(this.serverInfo.ratio),
|
||||
"预计到帐: " + (amount * this.serverInfo.ratio).toFixed(0),
|
||||
"注意: 数据可能更新不及时 请以实际到账金额为准!"
|
||||
].join('\n')
|
||||
}, (token: string) => {
|
||||
this.drawCoin(sender, amount, token)
|
||||
})
|
||||
}
|
||||
|
||||
private drawCoin(sender: org.bukkit.entity.Player, amount: number, token: string) {
|
||||
if (!token) return
|
||||
let draw = this.httpPost('https://reward.yumc.pw/server/draw', {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken,
|
||||
uuid: sender.getUniqueId().toString(),
|
||||
username: sender.getName(),
|
||||
amount,
|
||||
userToken: token
|
||||
})
|
||||
if (draw.code !== 200) {
|
||||
return this.sendError(sender, `§4兑换异常 §6服务器返回: §c${draw.msg}`)
|
||||
}
|
||||
let drawAmount = draw.data
|
||||
if (!drawAmount) {
|
||||
return this.sendError(sender, '§c服务器返回金额 ' + draw.data + ' 可能存在异常')
|
||||
}
|
||||
this.taskManager.create(() => {
|
||||
let command = this.config.drawCommand.replace('%player_name%', sender.getName()).replace('%amount%', draw.data)
|
||||
if (!this.server.dispatchConsoleCommand(command)) {
|
||||
return this.sendError(sender, '§6执行命令 §3/' + command + ' §c可能存在异常')
|
||||
}
|
||||
this.logger.sender(sender, draw.msg.split('\n'))
|
||||
this.sendBroadcast(sender, `${this.config.prefix}§6玩家 §b${sender.getName()} §6成功将 §a${amount}喵币 §6兑换成 §c${draw.data}点券!`)
|
||||
this.sendBroadcast(sender, `${this.config.prefix}§c/mrd help §b查看广告系统帮助 §6快来一起看广告赚点券吧!`)
|
||||
}).submit()
|
||||
}
|
||||
|
||||
private sendError(sender, error) {
|
||||
return this.logger.sender(sender, [
|
||||
`§c========== ${this.config.prefix}§4兑换异常 §c==========`,
|
||||
error,
|
||||
`§6异常账号: §b${sender.getName()}`,
|
||||
`§6异常时间: §a${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,
|
||||
`§c如果喵币被扣除且未得到奖励 请截图发往QQ群!`,
|
||||
`§c========== ${this.config.prefix}§4兑换异常 §c==========`,
|
||||
])
|
||||
}
|
||||
|
||||
cmdrank(sender: any, boardcast: boolean) {
|
||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
||||
let result = this.httpPost(`https://reward.yumc.pw/server/rank`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken
|
||||
})
|
||||
if (result.code !== 200) {
|
||||
return this.logger.sender(sender, `§c今日未查询到数据!`)
|
||||
}
|
||||
let ranks = [
|
||||
`§6====== ${this.config.prefix} §a喵币兑换排行 §6======`,
|
||||
...result.data.map((e, i) => `§6${i + 1}. §a${e.username} §6兑换 §3${e.count} §6次 §c${e.amount} §6喵币`),
|
||||
`§6====== ${this.config.prefix} §a喵币兑换排行 §6======`,
|
||||
]
|
||||
if (boardcast) {
|
||||
ranks.forEach(l => this.sendBroadcast(sender, l))
|
||||
} else {
|
||||
this.logger.sender(sender, ranks)
|
||||
}
|
||||
}
|
||||
|
||||
cmdserver(sender: any) {
|
||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
||||
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken
|
||||
})
|
||||
if (result.code !== 200) {
|
||||
return this.logger.sender(sender, `§4操作异常 §6服务器返回: §c${result.msg}`)
|
||||
}
|
||||
this.logger.sender(sender, [
|
||||
`§6====== ${this.config.prefix} §a服务器信息 §6======`,
|
||||
`§6服务器: §a${result.data.name}`,
|
||||
`§6喵币余额: §b${result.data.score} §6喵币`,
|
||||
`§6喵币比例: §b${result.data.ratio}`,
|
||||
`§6今日收入: §b${result.data.today} §6喵币`,
|
||||
`§6====== ${this.config.prefix} §a服务器信息 §6======`,
|
||||
])
|
||||
}
|
||||
|
||||
cmdratio(sender: any, ratioStr: string, confirm: string) {
|
||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
||||
let [ratio, mbr, msg] = this.ratio2string(ratioStr)
|
||||
if (!confirm) {
|
||||
return this.logger.sender(sender, [
|
||||
'§4警告: 您正在设置服务器喵币/点券兑换比例 设置后将实时生效!',
|
||||
`§6您设置的兑换比例为 ` + msg,
|
||||
`§6玩家至少需要 §a${mbr}喵币 §6才可以兑换点券!`,
|
||||
`§6请执行 §b/mrd ratio §c${ratio} §econfirm §c确认修改!`
|
||||
])
|
||||
}
|
||||
if (confirm != 'confirm') return this.logger.sender(sender, `§6请执行 §b/mrd ratio §c${ratio} §econfirm §c确认修改!`)
|
||||
let result = this.httpPost(`https://reward.yumc.pw/server/ratio`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken,
|
||||
ratio
|
||||
})
|
||||
if (result.code !== 200) {
|
||||
return this.logger.sender(sender, `§4操作异常 §6服务器返回: §c${result.msg}`)
|
||||
}
|
||||
this.logger.sender(sender, `§a操作成功 §6服务器返回: §a${result.msg}`)
|
||||
this.updateServerInfo(sender)
|
||||
this.sendBroadcast(sender, `${this.config.prefix} §6当前兑换比例已调整为 ` + msg)
|
||||
}
|
||||
|
||||
private ratio2string(ratio) {
|
||||
ratio = parseFloat(ratio)
|
||||
if (ratio > 1) {
|
||||
return [ratio, 1, `§c${ratio} §6就是 §a1喵币 §6=> §c${ratio}点券!`]
|
||||
}
|
||||
let mbr = Math.round(1 / ratio * 10000) / 10000
|
||||
return [ratio, mbr, `§c${ratio} §6就是 §a${mbr}喵币 §6=> §c1点券!`]
|
||||
}
|
||||
|
||||
private sendBroadcast(player, message) {
|
||||
if (!this.isBungeeCord) { return org.bukkit.Bukkit.broadcastMessage(message) }
|
||||
this.bungee.for(player).broadcast(message).send()
|
||||
}
|
||||
|
||||
private bindServer(sender: org.bukkit.entity.Player) {
|
||||
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
||||
let scanObj = http.get(`https://reward.yumc.pw/server/scan`)
|
||||
if (scanObj.code !== 200) {
|
||||
return this.logger.sender(sender, '§c获取服务器绑定码失败! Error: ' + scanObj.msg)
|
||||
}
|
||||
this.cacheBindUuid = scanObj.data.uuid
|
||||
let sync = { scaned: false }
|
||||
this.taskManager.create(() => {
|
||||
let check = this.httpPost(`https://reward.yumc.pw/server/check`, {
|
||||
token: this.cacheBindUuid,
|
||||
sync: true
|
||||
})
|
||||
if (check.code == 200) {
|
||||
this.config.serverId = check.data.serverId
|
||||
this.config.serverToken = check.data.serverToken
|
||||
// @ts-ignore
|
||||
this.config.save()
|
||||
this.logger.sender(sender, '§a已成功绑定服务器: §b' + check.data.serverName)
|
||||
}
|
||||
sync.scaned = true
|
||||
}).async().submit()
|
||||
this.setItemAndTp(sender, scanObj.data.url, sync)
|
||||
}
|
||||
|
||||
private bindUser(sender: org.bukkit.entity.Player) {
|
||||
if (!this.config.serverId || !this.config.serverToken) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
||||
let check = this.httpPost(`https://reward.yumc.pw/server/query`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken
|
||||
})
|
||||
if (check.code !== 200) {
|
||||
return this.logger.sender(sender, '§4获取绑定参数异常! §cError: ' + check.msg)
|
||||
}
|
||||
let queryUser = this.queryUser(sender)
|
||||
if (queryUser.code == 200) {
|
||||
return this.logger.sender(sender, ['§4当前用户已绑定! §c如需解绑 请联系腐竹!', '§b如需看广告请进QQ群 §a点击聊天框上的圈云盒子!'])
|
||||
}
|
||||
let bindUrl = 'https://m.q.qq.com/a/p/1110360279?s=' + encodeURIComponent(`pages/my/index?bindType=user&serverId=${this.config.serverId}&uuid=${sender.getUniqueId().toString()}&username=${sender.getName()}`)
|
||||
let sync = { scaned: false, timeout: false }
|
||||
this.taskManager.create(() => {
|
||||
let queryUser = this.queryUser(sender, true)
|
||||
if (queryUser.code == 200) {
|
||||
this.sendResult(sender, '绑定成功', queryUser.data)
|
||||
sync.scaned = true
|
||||
}
|
||||
}).async().submit()
|
||||
this.setItemAndTp(sender, bindUrl, sync)
|
||||
}
|
||||
|
||||
private setItemAndTp(sender: org.bukkit.entity.Player, content: string, sync: { scaned: boolean }) {
|
||||
this.taskManager.create(() => {
|
||||
this.bindingLeftTime = 30
|
||||
this.bindingTask = this.taskManager.create(() => {
|
||||
try {
|
||||
if (sync.scaned || !sender.isOnline() || !this.isHoldQrCodeItem(sender) || --this.bindingLeftTime < 0) {
|
||||
if (this.bindingLeftTime < 0) {
|
||||
this.logger.sender(sender, '§c二维码已过期 请重新获取!')
|
||||
}
|
||||
this.cancelTask(sender)
|
||||
return
|
||||
}
|
||||
this.chat.sendActionBar(sender, `§c§l手机QQ扫描二维码 剩余 ${this.bindingLeftTime} 秒...`)
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
}).async().later(20).timer(20).submit()
|
||||
sender.setItemInHand(this.createQrCodeMapItem(content))
|
||||
let temp = sender.getLocation()
|
||||
temp.setPitch(90)
|
||||
sender.teleport(temp)
|
||||
}).submit()
|
||||
}
|
||||
|
||||
private queryUser(sender: org.bukkit.entity.Player, sync = false) {
|
||||
return this.httpPost(`https://reward.yumc.pw/server/queryUser`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken,
|
||||
uuid: sender.getUniqueId().toString(),
|
||||
username: sender.getName(),
|
||||
sync
|
||||
})
|
||||
}
|
||||
|
||||
cmdquery(sender: org.bukkit.entity.Player) {
|
||||
let check = this.queryUser(sender)
|
||||
if (check.code !== 200) {
|
||||
return this.logger.sender(sender, '§4查询异常! §cError: ' + check.msg)
|
||||
}
|
||||
this.sendResult(sender, '查询结果', check.data)
|
||||
}
|
||||
|
||||
private sendResult(sender: any, title: string, data: any) {
|
||||
this.logger.sender(sender, [
|
||||
`§6====== ${this.config.prefix} §a${title} §6======`,
|
||||
`§6用 户 名: §a${sender.getName()}`,
|
||||
`§6U U I D: §b${sender.getUniqueId().toString()}`,
|
||||
`§6喵 币: §b${data.balance}`,
|
||||
`§6签 到: §b${data.sign}`,
|
||||
`§6视频广告: §b${data.video}`,
|
||||
`§6盒子广告: §b${data.box}`,
|
||||
'§6==========================='
|
||||
])
|
||||
}
|
||||
|
||||
private httpPost(url, data) {
|
||||
let startTime = Date.now()
|
||||
let result = http.post(url, data)
|
||||
console.debug(`
|
||||
====== HTTP POST ======
|
||||
REQUEST URL : ${url}
|
||||
REQUEST DATA: ${JSON.stringify(data)}
|
||||
RESPONSE : ${JSON.stringify(result)}
|
||||
CAST TIME : ${Date.now() - startTime}`)
|
||||
return result
|
||||
}
|
||||
|
||||
// var server = container.get(api.server.Server)
|
||||
// var console = server.getDedicatedServer()
|
||||
// var mainWorld = reflect.on(console).get('field_71305_c').get()[0]
|
||||
// 设置新的Data
|
||||
// mapdata = new MapData(s);
|
||||
// mapdata.field_76197_d = (byte)3;
|
||||
// mapdata.func_176054_a((double)worldIn.func_72912_H().func_76079_c(), (double)worldIn.func_72912_H().func_76074_e(), (int)mapdata.field_76197_d);
|
||||
// mapdata.field_76200_c = ((WorldServer)worldIn).dimension;
|
||||
// mapdata.func_76185_a();
|
||||
// worldMain.func_72823_a(s, (WorldSavedData)mapdata);
|
||||
// s = "map_" + stack.getMetadata();
|
||||
// mapdata = new MapData(s);
|
||||
// mapdata.scale = 3;
|
||||
// mapdata.calculateMapCenter((double)worldIn.getWorldInfo().getSpawnX(), (double)worldIn.getWorldInfo().getSpawnZ(), mapdata.scale);
|
||||
// // mapdata.dimension = worldIn.provider.getDimension();
|
||||
// mapdata.dimension = ((WorldServer) worldIn).dimension; // CraftBukkit - fixes Bukkit multiworld maps
|
||||
// mapdata.markDirty();
|
||||
// worldMain.setData(s, mapdata);
|
||||
// var mapStorage = mainWorld.field_72988_C
|
||||
|
||||
// var loadedDataMap = reflect.on(mapStorage).get('field_75749_b').get()
|
||||
// var loadedDataList = reflect.on(mapStorage).get('field_75750_c').get()
|
||||
// var idCounts = reflect.on(mapStorage).get('field_75748_d').get()
|
||||
|
||||
// @Override
|
||||
// public CraftMapView createMap(World world) {
|
||||
// Validate.notNull((Object)world, (String)"World cannot be null", (Object[])new Object[0]);
|
||||
// net.minecraft.item.ItemStack stack = new net.minecraft.item.ItemStack((Item)Items.field_151148_bJ, 1, -1);
|
||||
// MapData worldmap = Items.field_151098_aY.func_77873_a(stack, (net.minecraft.world.World)((CraftWorld)world).getHandle());
|
||||
// return worldmap.mapView;
|
||||
// }
|
||||
//net.minecraft.item.ItemMap
|
||||
// @Override
|
||||
// public CraftMapView createMap(World world) {
|
||||
// Validate.notNull(world, "World cannot be null");
|
||||
|
||||
// net.minecraft.item.ItemStack stack = new net.minecraft.item.ItemStack(Items.MAP, 1, -1, true); // CatServer
|
||||
// MapData worldmap = Items.FILLED_MAP.getMapData(stack, ((CraftWorld) world).getHandle());
|
||||
// return worldmap.mapView;
|
||||
// }
|
||||
|
||||
private createQrCodeMapItem(content: string) {
|
||||
let item: org.bukkit.inventory.ItemStack
|
||||
item = new ItemStack(Material.FILLED_MAP || Material.MAP)
|
||||
let meta = <org.bukkit.inventory.meta.MapMeta>item.getItemMeta()
|
||||
if (meta.setMapId) {
|
||||
meta.setMapId(this.zeroMapView.getId())
|
||||
} else {
|
||||
item.setDurability(this.zeroMapView.getId())
|
||||
}
|
||||
meta.setDisplayName('§c请使用手机QQ扫描二维码!')
|
||||
meta.setLore(["QRCODE"])
|
||||
item.setItemMeta(meta)
|
||||
this.zeroMapRender.setImage(this.createQrcode(content))
|
||||
return item
|
||||
}
|
||||
|
||||
private createQrcode(content: string) {
|
||||
let bufferedImage = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB)
|
||||
let graphics2D = bufferedImage.getGraphics()
|
||||
graphics2D.setPaint(Color.WHITE)
|
||||
graphics2D.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight())
|
||||
let qrcode = this.js2qr(content)
|
||||
let startPoint = Math.round((bufferedImage.getWidth() - qrcode.getWidth()) / 2)
|
||||
graphics2D.drawImage(qrcode, startPoint, startPoint, null)
|
||||
// let font = new Font("DejaVuSans", Font.PLAIN, 10)
|
||||
// graphics2D.setFont(font)
|
||||
// let fm = graphics2D.getFontMetrics(font)
|
||||
// let text = "Use QQ Scan Bind!"
|
||||
// let textWidth = fm.stringWidth(text)
|
||||
// let widthX = (128 - textWidth) / 2
|
||||
// graphics2D.setColor(Color.BLACK)
|
||||
// graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB)
|
||||
// graphics2D['drawString(java.lang.String, int, int)'](text, Math.round(widthX), 122)
|
||||
graphics2D.dispose()
|
||||
return bufferedImage
|
||||
}
|
||||
|
||||
private js2qr(contents: string) {
|
||||
let qrcode = new QRCode(14, QRErrorCorrectLevel.H)
|
||||
qrcode.addData(contents)
|
||||
qrcode.make()
|
||||
let length = qrcode.getModuleCount()
|
||||
let image: java.awt.image.BufferedImage = new BufferedImage(length, length, BufferedImage.TYPE_INT_RGB)
|
||||
for (let x = 0; x < length; x++) {
|
||||
for (let y = 0; y < length; y++) {
|
||||
image.setRGB(x, y, qrcode.isDark(x, y) ? 0xFF000000 : 0xFFFFFFFF)
|
||||
}
|
||||
}
|
||||
return image
|
||||
}
|
||||
|
||||
private bungeeCordDetect(player) {
|
||||
if (this.isBungeeCord === undefined && player) {
|
||||
this.bungee.for(player).getServer().send()
|
||||
}
|
||||
}
|
||||
|
||||
@Listener()
|
||||
PlayerJoinEvent(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||
this.bungeeCordDetect(event.getPlayer())
|
||||
}
|
||||
|
||||
@Listener()
|
||||
PlayerDropItemEvent(event: org.bukkit.event.player.PlayerDropItemEvent) {
|
||||
let [cancelled, id] = this.isQrCodeItem(event.getItemDrop().getItemStack())
|
||||
if (id != null && id != undefined && cancelled) {
|
||||
event.getItemDrop().remove()
|
||||
}
|
||||
}
|
||||
|
||||
@Listener()
|
||||
PlayerItemHeldEvent(event: org.bukkit.event.player.PlayerItemHeldEvent) {
|
||||
let inv = event.getPlayer().getInventory()
|
||||
let [cancelled, id] = this.isQrCodeItem(inv.getItem(event.getPreviousSlot() as any))
|
||||
if (id != null && id != undefined && cancelled) {
|
||||
inv.setItem(event.getPreviousSlot(), null)
|
||||
}
|
||||
}
|
||||
|
||||
@Listener()
|
||||
InventoryClickEvent(event: org.bukkit.event.inventory.InventoryClickEvent) {
|
||||
let item = event.getCurrentItem()
|
||||
let [cancelled, id] = this.isQrCodeItem(item)
|
||||
if (id != null && id != undefined && cancelled) {
|
||||
event.getInventory().setItem(event.getSlot(), null)
|
||||
event.setCancelled(true)
|
||||
}
|
||||
}
|
||||
|
||||
@Listener()
|
||||
PlayerQuitEvent(event: org.bukkit.event.player.PlayerQuitEvent) {
|
||||
this.checkAndClear(event.getPlayer())
|
||||
}
|
||||
|
||||
private cancelTask(player) {
|
||||
if (!this.isBinding) return
|
||||
this.isBinding = false
|
||||
this.bindingTask.cancel()
|
||||
this.bindingTask = undefined
|
||||
this.bindingUser = 'unknow'
|
||||
this.checkAndClear(player)
|
||||
this.chat.sendActionBar(player, "")
|
||||
this.zeroMapRender.setImage(undefined)
|
||||
//@ts-ignore
|
||||
this.bindingNotify.forEach(p => {
|
||||
if (p.isOnline()) {
|
||||
this.logger.sender(p, `§6用户 §a${player.getName()} §6扫码已完成 §a您可以继续操作!`)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private isHoldQrCodeItem(player: org.bukkit.entity.Player) {
|
||||
return this.isQrCodeItem(player.getItemInHand())[0]
|
||||
}
|
||||
|
||||
private checkAndClear(player: org.bukkit.entity.Player) {
|
||||
if (this.isHoldQrCodeItem(player)) {
|
||||
player.setItemInHand(null)
|
||||
}
|
||||
}
|
||||
|
||||
private isQrCodeItem(item: org.bukkit.inventory.ItemStack): [boolean, number?] {
|
||||
if (!item) { return [false] }
|
||||
if ((item?.getType() == Material.MAP || item?.getType() == Material.FILLED_MAP) && item.hasItemMeta()) {
|
||||
let meta = item.getItemMeta()
|
||||
return [!!(Java.from(meta.getLore()).indexOf('QRCODE') != -1), item.getDurability()]
|
||||
}
|
||||
return [false]
|
||||
}
|
||||
|
||||
cmdhelp(sender: any) {
|
||||
let help = [
|
||||
`§6====== ${this.config.prefix} §a帮助菜单 §6======`,
|
||||
`§6/mrd bind §a绑定圈云盒子`,
|
||||
`§6/mrd query §a查询当前账户`,
|
||||
`§6/mrd draw §e<兑换数量> §a兑换点券`
|
||||
]
|
||||
if (sender.isOp()) {
|
||||
help = help.concat([
|
||||
`§c由于您是管理员 以为您展示额外命令`,
|
||||
`§6/mrd bind server §a绑定服务器`,
|
||||
`§6/mrd ratio §e<兑换比例> §a设置喵币/点券兑换比例`,
|
||||
`§6/mrd statistic §3近期收入统计`,
|
||||
`§6/mrd rank <boardcast>(是否公告) §2今日兑换排行`,
|
||||
`§6/mrd server §c当前服务器信息`,
|
||||
`§6兑换比例设置说明: §b默认比例为 0.001 §6=> §a1000喵币 §6兑换 §c1点券`,
|
||||
`§c注意 设置比例后 玩家兑换点券数量不能少于 1点券`,
|
||||
`§c比如 设置了0.001 那就是 玩家至少 1000喵币 才能兑换!`
|
||||
])
|
||||
}
|
||||
this.logger.sender(sender, help)
|
||||
}
|
||||
|
||||
@Tab()
|
||||
tabmrd(sender: any, _command: any, args: string | any[]) {
|
||||
if (args.length === 1) return ['help', 'bind', 'show', 'statistic', 'query', 'draw', 'ratio', 'rank', 'server']
|
||||
if (args.length === 2 && args[0] === "bind" && sender.isOp()) return ['server']
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { plugin as pluginApi, task, server } from '@ccms/api'
|
||||
import { plugin as pluginApi, task, server, plugin, channel, constants } from '@ccms/api'
|
||||
|
||||
import { Translate } from '@ccms/i18n'
|
||||
import { inject, DefaultContainer as container } from '@ccms/container'
|
||||
import { interfaces, plugin, cmd, tab } from '@ccms/plugin'
|
||||
import { inject, DefaultContainer as container, optional, JSClass } from '@ccms/container'
|
||||
import { interfaces, JSPlugin, Cmd, Tab, enable, Listener, disable } from '@ccms/plugin'
|
||||
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
@@ -25,25 +25,30 @@ let help = [
|
||||
let langMap = {
|
||||
'main.command.not.exists': '§4未知的子命令: §c{command}',
|
||||
'main.command.help.tip': '§6请执行 §b/{command} §ahelp §6查看帮助!',
|
||||
'main.command.no.permission': '§c你没有此命令的权限!',
|
||||
'list.install.header': '§6当前 §bMiaoScript §6已安装下列插件:',
|
||||
'list.install.body': '§6插件名称: §b{name} §6版本: §a{version} §6作者: §3{author}',
|
||||
'list.install.body': '§6插件名称: §b{name} §6版本: §a{version}\n§6作者: §3{author} §6来源: §c{from}',
|
||||
'list.header': '§6当前 §bMiaoScriptPackageCenter §6中存在下列插件:',
|
||||
'list.body': '§6插件名称: §b{name} §6版本: §a{version} §6作者: §3{author} §6更新时间: §9{updated_at}',
|
||||
'list.body': '§6插件名称: §b{name} §6版本: §a{version}\n§6作者: §3{author} §6更新时间: §9{updated_at}',
|
||||
'plugin.not.exists': '§6插件 §b{name} §c不存在!',
|
||||
'plugin.unload.finish': '§6插件 §b{name} §a已卸载!',
|
||||
'plugin.reload.finish': '§6插件 §b{name} §a重载完成!',
|
||||
'plugin.unload.start': '§c开始卸载 §6插件 §b{name} §6版本 §3{version}!',
|
||||
'plugin.unload.finish': '§6插件 §b{name} §6版本 §3{version} §a已卸载!',
|
||||
'plugin.reload.start': '§a开始重载 §6插件 §b{name} §6版本 §3{version}!',
|
||||
'plugin.reload.finish': '§6插件 §b{name} §6版本 §3{version} §a重载完成!',
|
||||
'plugin.name.empty': '§c请输入插件名称!',
|
||||
'cloud.update.finish': '§6成功从 §aMiaoScriptPackageCenter §6获取到 §a{length} §6个插件!',
|
||||
'cloud.not.exists': '§6当前 §aMiaoScriptPackageCenter §c不存在 §a{name} §c插件!',
|
||||
'download.start': '§6开始下载插件: §b{name}',
|
||||
'cloud.update.exists': '§6插件 §b{name} §a发现新版本 §3{new_version} §6当前版本 §3{old_version}!',
|
||||
'download.start': '§6开始下载插件: §b{name} §6版本 §3{version}',
|
||||
'download.url': '§6插件下载地址: §b{url}',
|
||||
'download.finish': '§6插件 §b{name} §a下载完毕 开始加载 ...',
|
||||
'install.finish': '§6插件 §b{name} §a安装成功!',
|
||||
'update.finish': '§6插件 §b{name} §a更新成功!',
|
||||
'upgrade.confirm': '§6您正在尝试升级 §bMiaoScript §c核心 §6请执行 §b/mpm §aupgrade §cconfirm §6确认执行!',
|
||||
'download.finish': '§6插件 §b{name} §6版本 §3{version} §a下载完毕 开始加载 ...',
|
||||
'install.finish': '§6插件 §b{name} §6版本 §3{version} §a安装成功!',
|
||||
'update.finish': '§6插件 §b{name} §6版本 §3{version} §a更新成功!',
|
||||
'upgrade.confirm': '§6您正在尝试更新 §bMiaoScript §c核心 §6请执行 §b/mpm §aupgrade §cconfirm §6确认执行!',
|
||||
'upgrade.failed': '§6尝试热更新 §bMiaoScript §c核心 §4失败! §6请重启服务器完成更新...',
|
||||
'deploy.token.not.exists': '§4请先配置发布Token!',
|
||||
'deploy.success': '§6插件 §b{name} §a发布成功! §6服务器返回: §a{msg}',
|
||||
'deploy.fail': '§6插件 §b{name} §c发布失败! §6服务器返回: §c{msg}',
|
||||
'deploy.success': '§6插件 §b{name} §6版本 §3{version} §a发布成功! §6服务器返回: §a{msg}',
|
||||
'deploy.fail': '§6插件 §b{name} §6版本 §3{version} §c发布失败! §6服务器返回: §c{msg}',
|
||||
'run.script': '§b运行脚本:§r {script}',
|
||||
'run.result': '§a返回结果:§r {result}',
|
||||
'run.noresult': '§4没有返回结果!',
|
||||
@@ -51,9 +56,28 @@ let langMap = {
|
||||
|
||||
let fallbackMap = langMap
|
||||
|
||||
@plugin({ name: 'MiaoScriptPackageManager', prefix: 'PM', version: '1.0.1', author: 'MiaoWoo', source: __filename })
|
||||
class FakeSender {
|
||||
private _proxy
|
||||
private name: string
|
||||
private plugin: MiaoScriptPackageManager
|
||||
constructor(name: string, plugin: MiaoScriptPackageManager, superclass: any) {
|
||||
this.name = name
|
||||
this.plugin = plugin
|
||||
let FakeSenderAdapter = Java.extend(superclass, {
|
||||
getName: () => this.name,
|
||||
isOp: () => true,
|
||||
sendMessage: (message) => this.plugin.sendBungeeCordMessage(this.name, `§6[§3BPM§6][§a${this.plugin.serverName}§6] ${message}`)
|
||||
})
|
||||
this._proxy = new FakeSenderAdapter()
|
||||
}
|
||||
getHandler() {
|
||||
return this._proxy
|
||||
}
|
||||
}
|
||||
|
||||
@JSPlugin({ prefix: 'PM', version: '1.3.0', author: 'MiaoWoo', source: __filename })
|
||||
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
@inject(pluginApi.PluginManager)
|
||||
@inject(plugin.PluginManager)
|
||||
private pluginManager: pluginApi.PluginManager
|
||||
@inject(task.TaskManager)
|
||||
private taskManager: task.TaskManager
|
||||
@@ -63,11 +87,23 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
private server: server.Server
|
||||
@inject(pluginApi.PluginFolder)
|
||||
private pluginFolder: string
|
||||
@inject(channel.Channel)
|
||||
@optional() private channel: channel.Channel
|
||||
|
||||
@JSClass('java.io.ByteArrayOutputStream')
|
||||
private ByteArrayOutputStream: any
|
||||
@JSClass('java.io.DataOutputStream')
|
||||
private DataOutputStream: any
|
||||
@JSClass('com.google.common.io.ByteStreams')
|
||||
private ByteStreams: any
|
||||
|
||||
private packageCache: any[] = [];
|
||||
private packageNameCache: string[] = [];
|
||||
|
||||
private isBungeeCord = false
|
||||
public serverName: string
|
||||
private translate: Translate
|
||||
private channelOff: { off: () => void }
|
||||
|
||||
load() {
|
||||
this.translate = new Translate({
|
||||
@@ -77,13 +113,122 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
this.updateRepo(this.server.getConsoleSender())
|
||||
}
|
||||
|
||||
@cmd()
|
||||
@enable({ servers: [constants.ServerType.Bukkit, constants.ServerType.Sponge] })
|
||||
serverEnbale() {
|
||||
this.channelOff = this.channel?.listen(this, 'BungeeCord', (data) => {
|
||||
let input = this.ByteStreams.newDataInput(data)
|
||||
let subChannel = input.readUTF()
|
||||
switch (subChannel) {
|
||||
case "GetServer":
|
||||
this.isBungeeCord = true
|
||||
this.serverName = input.readUTF()
|
||||
break
|
||||
case "MiaoScriptPackageManager":
|
||||
this.readForward(input)
|
||||
break
|
||||
}
|
||||
})
|
||||
let players = this.server.getOnlinePlayers()
|
||||
if (players.length) this.bungeeCordDetect(players[0])
|
||||
}
|
||||
|
||||
@disable({ servers: [constants.ServerType.Bukkit, constants.ServerType.Sponge] })
|
||||
serverDisable() {
|
||||
this.channelOff?.off()
|
||||
}
|
||||
|
||||
private bungeeCordDetect(player) {
|
||||
if (player) {
|
||||
let byteArray = new this.ByteArrayOutputStream()
|
||||
let out = new this.DataOutputStream(byteArray)
|
||||
out.writeUTF("GetServer")
|
||||
this.channel.send(player, "BungeeCord", byteArray.toByteArray())
|
||||
}
|
||||
}
|
||||
private bungeeCordForward(player, command) {
|
||||
if (player) {
|
||||
let byteArray = new this.ByteArrayOutputStream()
|
||||
let out = new this.DataOutputStream(byteArray)
|
||||
out.writeUTF("Forward")
|
||||
out.writeUTF("ALL")
|
||||
out.writeUTF("MiaoScriptPackageManager")
|
||||
out.writeUTF(JSON.stringify(command))
|
||||
this.channel.send(player, "BungeeCord", byteArray.toByteArray())
|
||||
}
|
||||
}
|
||||
private readForward(input) {
|
||||
let message = JSON.parse(input.readUTF())
|
||||
let fakeSender = this.getProxySender(message.sender)
|
||||
this.taskManager.create(() => this.main(fakeSender, message.command, message.args)).async().submit()
|
||||
this.logger.sender(fakeSender, `§6命令 §b/mpm ${message.args?.join?.(' ')} §a执行成功!`)
|
||||
}
|
||||
|
||||
private getProxySender(name: string) {
|
||||
switch (this.serverType) {
|
||||
case constants.ServerType.Bukkit:
|
||||
return new FakeSender(name, this, Java.type('org.bukkit.command.CommandSender')).getHandler()
|
||||
case constants.ServerType.Sponge:
|
||||
return new FakeSender(name, this, Java.type('org.spongepowered.api.command.CommandSource')).getHandler()
|
||||
default:
|
||||
return this.server.getConsoleSender()
|
||||
}
|
||||
}
|
||||
|
||||
@Listener({ servers: [constants.ServerType.Bukkit] })
|
||||
PlayerJoinEvent(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||
this.bungeeCordDetect(event.getPlayer())
|
||||
if (event.getPlayer().isOp()) {
|
||||
this.updateRepo(event.getPlayer())
|
||||
}
|
||||
}
|
||||
|
||||
@Listener({ servers: [constants.ServerType.Sponge] })
|
||||
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
||||
this.bungeeCordDetect(event.getTargetEntity())
|
||||
if (event.getTargetEntity().hasPermission('ms.mpm.admin')) {
|
||||
this.updateRepo(event.getTargetEntity())
|
||||
}
|
||||
}
|
||||
|
||||
sendBungeeCordMessage(sender, message) {
|
||||
let players = this.server.getOnlinePlayers()
|
||||
if (players.length) {
|
||||
let byteArray = new this.ByteArrayOutputStream()
|
||||
let out = new this.DataOutputStream(byteArray)
|
||||
out.writeUTF("Message")
|
||||
out.writeUTF(sender)
|
||||
out.writeUTF(message)
|
||||
this.channel.send(players[0], "BungeeCord", byteArray.toByteArray())
|
||||
}
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.channelOff?.off()
|
||||
}
|
||||
|
||||
@Cmd({ servers: [`!${constants.ServerType.Bungee}`] })
|
||||
bmpm(sender: any, command: string, args: string[]) {
|
||||
if (!sender?.isOp()) { return this.i18n(sender, 'main.command.no.permission') }
|
||||
if (!this.isBungeeCord) return this.logger.sender(sender, '§c当前服务器尚未检测到BungeeCord链接...')
|
||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit()
|
||||
this.bungeeCordForward(sender, { sender: sender.getName(), command, args })
|
||||
this.logger.sender(sender, `§6[§3BPM§6][§a${this.serverName}§6] §6命令 §b/mpm ${args.join?.(' ')} §a发布成功!`)
|
||||
}
|
||||
|
||||
@Cmd({ servers: [constants.ServerType.Bungee] })
|
||||
mpmanager(sender: any, command: string, args: string[]) {
|
||||
if (!sender?.isOp()) { return this.i18n(sender, 'main.command.no.permission') }
|
||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit()
|
||||
}
|
||||
|
||||
@Cmd({ servers: [`!${constants.ServerType.Bungee}`] })
|
||||
mpm(sender: any, command: string, args: string[]) {
|
||||
if (!sender?.isOp()) { return this.i18n(sender, 'main.command.no.permission') }
|
||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit()
|
||||
}
|
||||
|
||||
i18n(sender: any, name: string, params?: any) {
|
||||
this.logger.sender(sender, this.translate.translate(name, params))
|
||||
this.logger.sender(sender, this.translate.translate(name, params).split('\n'))
|
||||
}
|
||||
|
||||
main(sender: any, command: string, args: string[]) {
|
||||
@@ -101,6 +246,12 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
this.logger.sender(sender, help)
|
||||
}
|
||||
|
||||
cmdinfo(sender: any) {
|
||||
this.logger.sender(sender, [
|
||||
|
||||
])
|
||||
}
|
||||
|
||||
cmdload(sender: any, name: string) {
|
||||
let pluginFile = fs.concat(__dirname + '', name)
|
||||
if (!fs.exists(pluginFile)) {
|
||||
@@ -114,7 +265,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
if (type == "i" || type == "install") {
|
||||
this.i18n(sender, 'list.install.header')
|
||||
this.pluginManager.getPlugins().forEach((plugin) => {
|
||||
this.i18n(sender, 'list.install.body', plugin.description)
|
||||
this.i18n(sender, 'list.install.body', { ...plugin.description, from: plugin.description.loadMetadata.type })
|
||||
})
|
||||
} else {
|
||||
this.i18n(sender, 'list.header')
|
||||
@@ -126,7 +277,14 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
|
||||
cmdinstall(sender: any, name: string) {
|
||||
if (!name) { return this.i18n(sender, 'plugin.name.empty') }
|
||||
this.download(sender, name)
|
||||
if (this.pluginManager.getPlugins().has(name)) {
|
||||
|
||||
return
|
||||
}
|
||||
this.download(sender, name, false, () => {
|
||||
let plugin = this.pluginManager.loadFromFile(fs.concat(root, this.pluginFolder, name + '.js'))
|
||||
this.i18n(sender, 'install.finish', { name, version: plugin.description.version })
|
||||
})
|
||||
}
|
||||
|
||||
cmdupdate(sender: any, name: string) {
|
||||
@@ -137,33 +295,51 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
cmdupgrade(sender: any, name: string) {
|
||||
if (!name) { return this.i18n(sender, 'upgrade.confirm') }
|
||||
if (name == "comfirm") {
|
||||
let enginePath = fs.path(fs.file(fs.concat(root, 'node_modules', '@ccms')))
|
||||
cmdupgrade(sender: any, name: string, confirm: boolean) {
|
||||
if (name == "system") {
|
||||
if (!confirm) { return this.i18n(sender, 'upgrade.confirm') }
|
||||
let enginePath = fs.path(fs.file(root, 'node_modules'))
|
||||
if (enginePath.startsWith(root)) {
|
||||
base.delete(enginePath)
|
||||
this.cmdrestart(sender)
|
||||
try {
|
||||
base.delete(enginePath)
|
||||
this.cmdrestart(sender)
|
||||
} catch (ex) {
|
||||
if (global.debug) {
|
||||
console.ex(ex)
|
||||
}
|
||||
if (fs.exists(enginePath)) {
|
||||
this.i18n(sender, 'upgrade.failed')
|
||||
fs.create(fs.file(root, 'upgrade'))
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (this.checkPlugin(sender, name)) {
|
||||
this.update(sender, name)
|
||||
this.pluginManager.reload(name)
|
||||
this.update(sender, name, () => this.reload(sender, name))
|
||||
}
|
||||
}
|
||||
|
||||
cmdunload(sender: any, name: string) {
|
||||
if (this.checkPlugin(sender, name)) {
|
||||
this.pluginManager.disable(name)
|
||||
this.i18n(sender, 'plugin.unload.finish', { name })
|
||||
let plugin = this.pluginManager.getPlugins().get(name)
|
||||
this.i18n(sender, 'plugin.unload.start', { name, version: plugin.description.version })
|
||||
this.pluginManager.disable(plugin)
|
||||
this.i18n(sender, 'plugin.unload.finish', { name, version: plugin.description.version })
|
||||
}
|
||||
}
|
||||
|
||||
cmdreload(sender: any, name: string) {
|
||||
name = name || this.description.name
|
||||
this.reload(sender, name)
|
||||
}
|
||||
|
||||
private reload(sender: any, name: string) {
|
||||
if (this.checkPlugin(sender, name)) {
|
||||
this.pluginManager.reload(name)
|
||||
this.i18n(sender, 'plugin.reload.finish', { name })
|
||||
let plugin = this.pluginManager.getPlugins().get(name)
|
||||
this.i18n(sender, 'plugin.reload.start', { name, version: plugin.description.version })
|
||||
this.pluginManager.reload(plugin)
|
||||
this.i18n(sender, 'plugin.reload.finish', { name, version: this.pluginManager.getPlugins().get(name).description.version })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,20 +417,23 @@ return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
||||
name,
|
||||
author: plugin.description.author,
|
||||
version: plugin.description.version,
|
||||
source: base.read(plugin.description.source.toString())
|
||||
source: base.read((plugin.description.source || plugin.description.loadMetadata.file).toString())
|
||||
})
|
||||
this.i18n(sender, result.code == 200 ? 'deploy.success' : 'deploy.fail', { name, msg: result.msg })
|
||||
}
|
||||
}).async().submit()
|
||||
}
|
||||
|
||||
update(sender: any, name: string) {
|
||||
private update(sender: any, name: string, callback?: () => void) {
|
||||
if (this.checkCloudPlugin(sender, name)) {
|
||||
this.download(sender, name, true)
|
||||
this.download(sender, name, true, () => {
|
||||
this.i18n(sender, 'update.finish', { name, version: this.packageCache[name].version })
|
||||
callback?.()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@tab()
|
||||
@Tab({ alias: ['bmpm'] })
|
||||
tabmpm(sender: any, command: any, args: string | any[]) {
|
||||
if (args.length === 1) { return ['list', 'install', 'update', 'upgrade', 'reload', 'restart', 'run', 'help', 'create', 'deploy'] }
|
||||
if (args.length > 1) {
|
||||
@@ -263,8 +442,11 @@ return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
||||
return ["install", "cloud"]
|
||||
case "install":
|
||||
return this.packageNameCache
|
||||
case "update":
|
||||
case "upgrade":
|
||||
if (args.length == 2) return ["system", ...this.pluginManager.getPlugins().keys()]
|
||||
if (args.length == 3 && args[1] == "system") return ["confirm"]
|
||||
return []
|
||||
case "update":
|
||||
case "load":
|
||||
case "unload":
|
||||
case "reload":
|
||||
@@ -280,22 +462,25 @@ return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
||||
for (const pl of result.data) { this.packageCache[pl.name] = pl }
|
||||
this.packageNameCache = Object.keys(this.packageCache)
|
||||
this.i18n(sender, 'cloud.update.finish', { length: this.packageNameCache.length })
|
||||
this.pluginManager.getPlugins().forEach(p => {
|
||||
let cloudPlugin = this.packageCache[p.description.name]
|
||||
//§6插件名称: §b{name}\n§6版本: §a{version}\n§6作者: §3{author}\§6更新时间: §9{updated_at}
|
||||
if (cloudPlugin && cloudPlugin.version != p.description.version) {
|
||||
this.i18n(sender, 'cloud.update.exists', { name: p.description.name, new_version: cloudPlugin.version, old_version: p.description.version })
|
||||
}
|
||||
})
|
||||
}).async().submit()
|
||||
}
|
||||
|
||||
download(sender: any, name: string, update: boolean = false) {
|
||||
download(sender: any, name: string, update: boolean, callback?: () => void) {
|
||||
this.taskManager.create(() => {
|
||||
this.i18n(sender, 'download.start', { name })
|
||||
this.i18n(sender, 'download.url', { url: this.packageCache[name].url })
|
||||
let pluginPkg = this.packageCache[name]
|
||||
this.i18n(sender, 'download.start', { name, version: pluginPkg.version })
|
||||
this.i18n(sender, 'download.url', { url: pluginPkg.url })
|
||||
let pluginFile = update ? fs.concat(root, this.pluginFolder, 'update', name + '.js') : fs.concat(root, this.pluginFolder, name + '.js')
|
||||
http.download(this.packageCache[name].url, pluginFile)
|
||||
this.i18n(sender, 'download.finish', { name })
|
||||
if (!update) {
|
||||
this.pluginManager.loadFromFile(fs.file(pluginFile))
|
||||
this.i18n(sender, 'install.finish', { name })
|
||||
} else {
|
||||
this.i18n(sender, 'update.finish', { name })
|
||||
}
|
||||
http.download(pluginPkg.url, pluginFile)
|
||||
this.i18n(sender, 'download.finish', { name, version: pluginPkg.version })
|
||||
callback?.()
|
||||
}).async().submit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,15 +2,50 @@
|
||||
/// <reference types="@javatypes/spring-web" />
|
||||
|
||||
import { constants, database, plugin, web } from "@ccms/api"
|
||||
import { inject, ContainerInstance, Container, JSClass } from "@ccms/container"
|
||||
import { inject, ContainerInstance, Container, JSClass, postConstruct } from "@ccms/container"
|
||||
import { JSPlugin, interfaces, cmd } from "@ccms/plugin"
|
||||
import { DataBase, DataBaseManager } from '@ccms/database'
|
||||
import { Server, Context, RequestHandler } from '@ccms/web'
|
||||
import { Server, Context, RequestHandler, Controllers, Controller, Get, Post, Param, Body } from '@ccms/web'
|
||||
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
|
||||
@JSPlugin({ name: 'MiaoSpring', prefix: 'MSpring', version: '1.0.1', author: 'MiaoWoo', servers: [constants.ServerType.Spring], source: __filename })
|
||||
@Controller()
|
||||
class PluginController {
|
||||
@inject(plugin.PluginManager)
|
||||
private pluginManager: plugin.PluginManager
|
||||
@inject(database.DataBaseManager)
|
||||
private databaseManager: DataBaseManager
|
||||
|
||||
private mainDB: DataBase
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
this.mainDB = this.databaseManager.getMainDatabase()
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(@Param('install') install: boolean) {
|
||||
if (install) {
|
||||
return { status: 200, data: [...this.pluginManager.getPlugins().values()].map((plugin) => plugin.description), msg: '插件列表获取成功!' }
|
||||
} else {
|
||||
return { status: 200, data: this.mainDB.query<Plugin>("SELECT name FROM plugins WHERE deleted = 0") }
|
||||
}
|
||||
}
|
||||
@Post()
|
||||
deploy(@Body() info: Plugin) {
|
||||
let plugin = this.mainDB.query<Plugin>("SELECT name FROM plugins WHERE name = ?", info.name)
|
||||
if (plugin.length == 0) {
|
||||
this.mainDB.update("INSERT INTO `plugins`(`name`, `source`) VALUES (?, ?)", info.name, info.source)
|
||||
return { status: 200, msg: `插件 ${info.name} 新增成功!` }
|
||||
} else {
|
||||
this.mainDB.update("UPDATE `plugins` SET `source` = ? WHERE id = ?", info.source, plugin[0].id)
|
||||
return { status: 200, msg: `插件 ${info.name} 更新成功!` }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JSPlugin({ author: 'MiaoWoo', servers: [constants.ServerType.Spring], source: __filename })
|
||||
export class MiaoSpring extends interfaces.Plugin {
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
@@ -40,6 +75,7 @@ export class MiaoSpring extends interfaces.Plugin {
|
||||
this.mappings = new Set()
|
||||
}
|
||||
|
||||
@Controllers(PluginController)
|
||||
enable() {
|
||||
this.registryDefault()
|
||||
this.registryPages()
|
||||
@@ -65,7 +101,7 @@ export class MiaoSpring extends interfaces.Plugin {
|
||||
this.webServer.registryInterceptor({
|
||||
name: 'StaticHandle',
|
||||
preHandle: (ctx: Context) => {
|
||||
let type = ctx.header['Accept'] || ''
|
||||
let type = ctx.headers['Accept'] || ''
|
||||
if (type == '*/*' || type.includes('text/css') || type.includes('text/html')) {
|
||||
let filePath = fs.concat(root, 'wwwroot', (ctx.request.getRequestURI() == '/' ? 'index.html' : ctx.request.getRequestURI()))
|
||||
let fileType = 'text/html;charset=utf-8'
|
||||
@@ -73,33 +109,25 @@ export class MiaoSpring extends interfaces.Plugin {
|
||||
if (fs.exists(filePath)) {
|
||||
if (filePath.endsWith('.js')) { fileType = 'application/javascript' }
|
||||
if (filePath.endsWith('.css')) { fileType = 'text/css' }
|
||||
// @ts-ignore
|
||||
return this.ResponseEntity.ok().header('Content-Type', fileType).body(base.read(filePath))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
this.webServer.registryMapping('/api/eval', (ctx: Context) => {
|
||||
this.registryMapping('/api/eval', (ctx: Context) => {
|
||||
try {
|
||||
return { status: 200, data: this.runCode(ctx.body + ''), msg: '代码执行成功!' }
|
||||
} catch (error) {
|
||||
return { status: 500, data: console.stack(error, false), msg: '代码执行异常!' }
|
||||
}
|
||||
})
|
||||
this.webServer.registryMapping('/api/plugin/list', () => {
|
||||
return { status: 200, data: [...this.pluginManager.getPlugins().values()].map((plugin) => plugin.description), msg: '插件列表获取成功!' }
|
||||
})
|
||||
this.webServer.registryMapping('/api/plugin/update', (ctx: Context) => {
|
||||
if (!ctx.params.name) { return { status: 400, msg: '插件名称不得为空!' } }
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
private registryPages() {
|
||||
this.webServer.registryMapping('/api/page/list', () => {
|
||||
this.registryMapping('/api/page/list', () => {
|
||||
return { status: 0, data: { rows: this.mainDatabase.query('SELECT `id`, `type`, `name`, `content` FROM `pages` WHERE `deleted` = 0') } }
|
||||
})
|
||||
this.webServer.registryMapping('/api/page/get', (ctx: Context) => {
|
||||
this.registryMapping('/api/page/get', (ctx: Context) => {
|
||||
let name = decodeURIComponent(`${ctx.params.name}`)
|
||||
let varable = undefined
|
||||
if (!name) { return { status: 400, msg: '名称不能为空!' } }
|
||||
@@ -119,20 +147,20 @@ export class MiaoSpring extends interfaces.Plugin {
|
||||
}
|
||||
return { status: 0, data: JSON.parse(content) }
|
||||
})
|
||||
this.webServer.registryMapping('/api/page/add', (ctx: Context) => {
|
||||
this.registryMapping('/api/page/add', (ctx: Context) => {
|
||||
let body = ctx.body
|
||||
if (typeof body.content !== "string") { body.content = JSON.stringify(body.content) }
|
||||
this.mainDatabase.update("INSERT INTO `pages`(`type`, `name`, `content`) VALUES (?, ?, ?)", body.type || 1, body.name, body.content)
|
||||
return { status: 0, msg: `${body.name} 新增成功!` }
|
||||
})
|
||||
this.webServer.registryMapping('/api/page/update', (ctx: Context) => {
|
||||
this.registryMapping('/api/page/update', (ctx: Context) => {
|
||||
if (!ctx.params.id) { return { status: 400, msg: 'ID 不能为空!' } }
|
||||
const body = ctx.body
|
||||
if (typeof body.content !== "string") { body.content = JSON.stringify(body.content) }
|
||||
this.mainDatabase.update("UPDATE `pages` SET `name` = ?, `content` = ? WHERE id = ?", body.name, body.content, ctx.params.id)
|
||||
return { status: 0, msg: `${body.name} 更新成功!` }
|
||||
})
|
||||
this.webServer.registryMapping('/api/page/delete', (ctx: Context) => {
|
||||
this.registryMapping('/api/page/delete', (ctx: Context) => {
|
||||
if (!ctx.params.name) { return { status: 400, msg: '页面 名称 不能为空!' } }
|
||||
this.mainDatabase.update("UPDATE `pages` SET `name` = CONCAT(name, '_deleted'), deleted = 1 WHERE name = ?", ctx.params.name)
|
||||
return { status: 0, msg: `${ctx.params.name} 删除成功!` }
|
||||
@@ -142,17 +170,17 @@ export class MiaoSpring extends interfaces.Plugin {
|
||||
private configTable = "config"
|
||||
|
||||
private registryDatabase() {
|
||||
this.webServer.registryMapping('/api/config/list', (ctx: Context) => {
|
||||
this.registryMapping('/api/config/list', (ctx: Context) => {
|
||||
return { status: 0, data: this.mainDatabase.query('SELECT id, name, label, url, driver, username, password FROM `' + this.configTable + '` WHERE deleted = 0 AND type = ?', ctx.params.type || 0) }
|
||||
})
|
||||
this.webServer.registryMapping('/api/config/get', (ctx: Context) => {
|
||||
this.registryMapping('/api/config/get', (ctx: Context) => {
|
||||
let name = ctx.params.name
|
||||
if (!name) { return { status: 400, msg: '名称不能为空!' } }
|
||||
let result = this.mainDatabase.query('SELECT id, name, label, url, driver, username, password FROM `' + this.configTable + '` WHERE `name` = ?', name)
|
||||
if (!result.length) { return { status: 404, msg: `配置 ${name} 不存在!` } }
|
||||
return { status: 0, data: result[0] }
|
||||
})
|
||||
this.webServer.registryMapping('/api/config/add', (ctx: Context) => {
|
||||
this.registryMapping('/api/config/add', (ctx: Context) => {
|
||||
let body = ctx.body
|
||||
if (!body.name) { return { status: 400, msg: '名称不能为空!' } }
|
||||
this.mainDatabase.update(
|
||||
@@ -161,7 +189,7 @@ export class MiaoSpring extends interfaces.Plugin {
|
||||
)
|
||||
return { status: 0, msg: `配置 ${body.name} 新增成功!` }
|
||||
})
|
||||
this.webServer.registryMapping('/api/config/update', (ctx: Context) => {
|
||||
this.registryMapping('/api/config/update', (ctx: Context) => {
|
||||
if (!ctx.params.id) { return { status: 400, msg: 'ID 不能为空!' } }
|
||||
let body = ctx.body
|
||||
this.mainDatabase.update(
|
||||
@@ -181,6 +209,7 @@ export class MiaoSpring extends interfaces.Plugin {
|
||||
'pluginManager'
|
||||
]
|
||||
let params = [
|
||||
base.getInstance().getAutowireCapableBeanFactory(),
|
||||
this.mainDatabase,
|
||||
reflect,
|
||||
this.container,
|
||||
@@ -195,5 +224,13 @@ return eval(${JSON.stringify(code)});`)
|
||||
|
||||
disable() {
|
||||
Object.keys(this.mappings).forEach((r) => this.webServer.unregistryMapping(r))
|
||||
this.webServer.unregistryInterceptor({ name: 'RedirectHandle' })
|
||||
this.webServer.unregistryInterceptor({ name: 'StaticHandle' })
|
||||
}
|
||||
}
|
||||
|
||||
class Plugin {
|
||||
id: number
|
||||
name: string
|
||||
source: string
|
||||
}
|
||||
|
||||
31
packages/plugins/src/MiaoWeb.ts
Normal file
31
packages/plugins/src/MiaoWeb.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { constants } from "@ccms/api"
|
||||
import { plugin, interfaces } from "@ccms/plugin"
|
||||
import { Controllers, Controller, Get, Body, Post, Cookie, Header, Param } from "@ccms/web"
|
||||
|
||||
@Controller()
|
||||
export class TestController {
|
||||
@Get()
|
||||
public get() {
|
||||
return 'test'
|
||||
}
|
||||
@Post()
|
||||
public post(@Body() body: any,
|
||||
@Cookie('test') testCookie,
|
||||
@Header('Accept') testHeader,
|
||||
@Param("name") param) {
|
||||
return {
|
||||
body,
|
||||
testCookie,
|
||||
testHeader,
|
||||
param
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@plugin({ author: 'MiaoWoo', servers: [constants.ServerType.Spring], source: __filename })
|
||||
export class MiaoWeb extends interfaces.Plugin {
|
||||
@Controllers(TestController)
|
||||
enable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
/// <reference types="@javatypes/spring-data-redis" />
|
||||
|
||||
import { constants, plugin as pluginApi, amqp, server, web } from '@ccms/api'
|
||||
import { plugin, interfaces, cmd } from '@ccms/plugin'
|
||||
import { AmqpAdmin, ConnectionFactoryAdapter, AmqpManager } from '@ccms/amqp'
|
||||
import { inject, Autowired } from '@ccms/container'
|
||||
import { Server } from '@ccms/web'
|
||||
import { inject, Autowired, ContainerInstance, Container } from '@ccms/container'
|
||||
import { Server, Controller, Get, Param, METADATA_KEY } from '@ccms/web'
|
||||
|
||||
const SearchRankingAmqpAdmin = Symbol('SearchRanking-AmqpAdmin')
|
||||
|
||||
const EXCHANGE_NAME = `search.ranking.${process.env.SPRING_CLOUD_CONFIG_PROFILE || 'dev'}`
|
||||
const QUEUE_NAME = `search.ranking.${process.env.SPRING_CLOUD_CONFIG_PROFILE || 'dev'}`
|
||||
const ROUTER_KEY = `search.ranking.${process.env.SPRING_CLOUD_CONFIG_PROFILE || 'dev'}`
|
||||
|
||||
@plugin({ name: SearchRanking.name, version: SearchRanking.version, author: SearchRanking.author, servers: SearchRanking.servers, source: __filename })
|
||||
export class SearchRanking extends interfaces.Plugin {
|
||||
@@ -10,6 +18,8 @@ export class SearchRanking extends interfaces.Plugin {
|
||||
public static author = 'MiaoWoo'
|
||||
public static servers = [constants.ServerType.Spring]
|
||||
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
@inject(pluginApi.PluginManager)
|
||||
private pluginManager: pluginApi.PluginManager
|
||||
@inject(amqp.Manager)
|
||||
@@ -20,17 +30,11 @@ export class SearchRanking extends interfaces.Plugin {
|
||||
private webServer: Server
|
||||
|
||||
@Autowired()
|
||||
private mongoTemplate: any
|
||||
@Autowired()
|
||||
private redisTemplate: any
|
||||
private redisTemplate: org.springframework.data.redis.core.RedisTemplate<string, any>
|
||||
|
||||
private amqpAdmin: AmqpAdmin
|
||||
private listener: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
|
||||
private readonly exchangeName = 'search.ranking'
|
||||
private readonly queueName = 'search.ranking'
|
||||
private readonly routerKey = 'search.ranking'
|
||||
|
||||
load() {
|
||||
let connection = new ConnectionFactoryAdapter({
|
||||
url: 'amqp://rabbitmq.c.sixi.com:5672',
|
||||
@@ -42,33 +46,26 @@ export class SearchRanking extends interfaces.Plugin {
|
||||
}
|
||||
|
||||
enable() {
|
||||
this.webServer.registryMapping('/api/search', (ctx) => {
|
||||
if (!ctx.params.keyword) { return { status: 400, msg: '查询关键词不得为空!' } }
|
||||
let keyword = ctx.params.keyword + ''
|
||||
let type = ctx.params.type == 'sale' ? 'sale' : 'normal'
|
||||
let time = parseInt(ctx.params.time + '') || 60 * 60 * 24 * 15
|
||||
return this.cacheAndSearch(keyword, type as any, time * 1000)
|
||||
})
|
||||
this.webServer.registryMapping('/api/search/ranking', (ctx) => {
|
||||
if (!ctx.params.keyword || !ctx.params.shopName) { return { status: 400, msg: '查询关键词不得为空!' } }
|
||||
let keyword = ctx.params.keyword + ''
|
||||
let shopName = ctx.params.shopName + ''
|
||||
let type = ctx.params.type == 'sale' ? 'sale' : 'normal'
|
||||
let time = parseInt(ctx.params.time + '') || 60 * 60 * 24 * 15
|
||||
return this.sendSearchRankingCmd(keyword, shopName, type as any, time * 1000)
|
||||
})
|
||||
this.amqpAdmin.declareQueueAndBindExchange(this.queueName, this.exchangeName, this.routerKey)
|
||||
this.amqpAdmin.declareBinding(this.queueName, 'client.topic.exchange', `cmd_res.${this.routerKey}`)
|
||||
this.listener = this.amqpAdmin.createContainer<string>(this.queueName, (content, message, channel) => {
|
||||
this.amqpAdmin.declareQueueAndBindExchange(QUEUE_NAME, EXCHANGE_NAME, ROUTER_KEY)
|
||||
this.amqpAdmin.declareBinding(QUEUE_NAME, 'client.topic.exchange', `cmd_res.${ROUTER_KEY}`)
|
||||
this.listener = this.amqpAdmin.createContainer<string>(QUEUE_NAME, (content, _message, _channel) => {
|
||||
let searchResult = JSON.parse(content)
|
||||
if (searchResult.type == "company") {
|
||||
this.logger.info(content)
|
||||
return
|
||||
}
|
||||
this.redisTemplate.opsForValue().set(searchResult.reqData.cacheKey, searchResult)
|
||||
this.logger.sender(this.Server.getConsoleSender(), `§6查询任务完成! §b关键词: §r${searchResult.reqData.keywords}`)
|
||||
})
|
||||
this.container.bind(SearchRankingAmqpAdmin).toConstantValue(this.amqpAdmin)
|
||||
this.listener.start()
|
||||
this.webServer.registryController(SearchRankingController)
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.container.unbind(SearchRankingAmqpAdmin)
|
||||
this.listener.stop()
|
||||
this.webServer.unregistryController(SearchRankingController)
|
||||
}
|
||||
|
||||
@cmd()
|
||||
@@ -90,14 +87,55 @@ export class SearchRanking extends interfaces.Plugin {
|
||||
this.pluginManager.reload(this)
|
||||
}
|
||||
|
||||
cmdsend(sender: any, ...args: string[]) {
|
||||
}
|
||||
|
||||
cmdsearch(sender: any, keyword: string, type: "sale" | "normal" = "sale", time: number) {
|
||||
this.logger.sender(sender, this.cacheAndSearch(keyword, type, time)?.msg)
|
||||
this.logger.sender(sender, this.container.getNamed<SearchRankingController>(METADATA_KEY.Controller, SearchRankingController.name).cacheAndSearch(keyword, type, time)?.msg)
|
||||
}
|
||||
}
|
||||
|
||||
@Controller({ path: '/api', name: SearchRankingController.name })
|
||||
class SearchRankingController {
|
||||
@Autowired()
|
||||
private redisTemplate: org.springframework.data.redis.core.RedisTemplate<string, any>
|
||||
|
||||
@inject(SearchRankingAmqpAdmin)
|
||||
private amqpAdmin: AmqpAdmin
|
||||
|
||||
@Get()
|
||||
public search(
|
||||
@Param({ name: 'keyword', require: true, message: '查询关键词不得为空!' }) keyword: string,
|
||||
@Param("type") type: string = 'normal',
|
||||
@Param('time') time: number = 60 * 60 * 24 * 15
|
||||
) {
|
||||
return this.cacheAndSearch(keyword, type as any, time * 1000)
|
||||
}
|
||||
|
||||
private cacheAndSearch(keyword: string, type: string = "sale", time: number = 15 * 24 * 60 * 60 * 1000) {
|
||||
@Get("/search/ranking")
|
||||
public searchRanking(
|
||||
@Param({ name: 'keyword', require: true, message: '查询关键词不得为空!' }) keyword: string,
|
||||
@Param("shopName") shopName: string = 'normal',
|
||||
@Param("type") type: string = 'normal',
|
||||
@Param('time') time: number = 60 * 60 * 24 * 15
|
||||
) {
|
||||
return this.sendSearchRankingCmd(keyword, shopName, type as any, time * 1000)
|
||||
}
|
||||
|
||||
@Get('/search/company')
|
||||
public searchCompany(
|
||||
@Param('url') url: string
|
||||
) {
|
||||
this.amqpAdmin.getTemplate().convertAndSend('client.topic.exchange', 'cmd_req', {
|
||||
cmd: 'scout._1688CompanyInfo',
|
||||
data: {
|
||||
type: 'company',
|
||||
url: url,
|
||||
cacheKey: 'SearchRanking:company'
|
||||
},
|
||||
resRouteSuffix: ROUTER_KEY,
|
||||
target: {}
|
||||
})
|
||||
}
|
||||
|
||||
public cacheAndSearch(keyword: string, type: string = "sale", time: number = 15 * 24 * 60 * 60 * 1000) {
|
||||
let cacheKey = this.getCacheKey(keyword, type)
|
||||
if (this.redisTemplate.hasKey(cacheKey)) {
|
||||
let lastSearchTime = this.redisTemplate.opsForValue().get(cacheKey)
|
||||
@@ -119,7 +157,7 @@ export class SearchRanking extends interfaces.Plugin {
|
||||
|
||||
private createKeyworkSearch(keyword: string, type: string) {
|
||||
let cacheDate = Date.now()
|
||||
this.redisTemplate.opsForValue().set(this.getCacheKey(keyword, type), cacheDate)
|
||||
this.redisTemplate.opsForValue().set(this.getCacheKey(keyword, type), cacheDate, 15, java.util.concurrent.TimeUnit.DAYS)
|
||||
this.sendSearchCmd(keyword, type, cacheDate)
|
||||
return { status: 201, msg: `关键词: ${keyword} 排名类型: ${type} 查询任务以创建...`, createTime: cacheDate }
|
||||
}
|
||||
@@ -141,9 +179,10 @@ export class SearchRanking extends interfaces.Plugin {
|
||||
sortType: 'va_rmdarkgmv30rt',
|
||||
button_click: 'top'
|
||||
} : {},
|
||||
pageTotal: 3,
|
||||
cacheKey: this.getResultCacheKey(keywords, type, dateCache)
|
||||
},
|
||||
resRouteSuffix: this.routerKey,
|
||||
resRouteSuffix: ROUTER_KEY,
|
||||
target: {}
|
||||
})
|
||||
}
|
||||
@@ -159,11 +198,10 @@ export class SearchRanking extends interfaces.Plugin {
|
||||
cacheKey: this.getResultCacheKey(keywords, type, cacheTime),
|
||||
cacheTime
|
||||
},
|
||||
resRouteSuffix: this.routerKey,
|
||||
resRouteSuffix: ROUTER_KEY,
|
||||
target: {}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得关键词+类型的上次查询时间
|
||||
* @param keywords 关键词
|
||||
@@ -175,4 +213,4 @@ export class SearchRanking extends interfaces.Plugin {
|
||||
private getResultCacheKey(keywords: string, type: string, date: number) {
|
||||
return `SearchRanking:${keywords}:${type}:${date}`
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,74 +1,110 @@
|
||||
import { plugin as pluginApi } from '@ccms/api'
|
||||
import { plugin, interfaces, cmd, listener, tab } from '@ccms/plugin'
|
||||
import { inject } from '@ccms/container';
|
||||
import { inject } from '@ccms/container'
|
||||
|
||||
import * as reflect from '@ccms/common/dist/reflect';
|
||||
import http from '@ccms/common/dist/http';
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
import http from '@ccms/common/dist/http'
|
||||
|
||||
const ByteArrayInputStream = Java.type("java.io.ByteArrayInputStream")
|
||||
const ByteArrayOutputStream = Java.type("java.io.ByteArrayOutputStream")
|
||||
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets")
|
||||
const GZIPInputStream = Java.type("java.util.zip.GZIPInputStream")
|
||||
const GZIPOutputStream = Java.type("java.util.zip.GZIPOutputStream")
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
const ByteArray = Java.type("byte[]")
|
||||
|
||||
class MiaoMessage {
|
||||
// public static final String CHANNEL = "MiaoChat:Default".toLowerCase();
|
||||
public static CHANNEL: string = "MiaoChat:Default".toLowerCase()
|
||||
// private static final int MAX_MESSAGE_LENGTH = 32000;
|
||||
private static MAX_MESSAGE_LENGTH = 32000;
|
||||
|
||||
private static copy(input, output) {
|
||||
let buffer = new ByteArray(1024)
|
||||
let n: number
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, n)
|
||||
}
|
||||
input.close()
|
||||
output.close()
|
||||
}
|
||||
public static encode(input: any): any {
|
||||
let baos = new ByteArrayOutputStream()
|
||||
MiaoMessage.copy(new ByteArrayInputStream(new JavaString(JSON.stringify(input)).getBytes(StandardCharsets.UTF_8)), new GZIPOutputStream(baos))
|
||||
if (baos.size() > MiaoMessage.MAX_MESSAGE_LENGTH) { return null }
|
||||
return baos.toByteArray()
|
||||
}
|
||||
public static decode(input: any): any {
|
||||
let baos = new ByteArrayOutputStream()
|
||||
MiaoMessage.copy(new GZIPInputStream(new ByteArrayInputStream(input)), baos)
|
||||
return JSON.parse(baos.toString(StandardCharsets.UTF_8.name()))
|
||||
}
|
||||
}
|
||||
|
||||
@plugin({ name: 'Test', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||
export class Test extends interfaces.Plugin {
|
||||
@inject(pluginApi.PluginManager)
|
||||
private PluginManager: pluginApi.PluginManager;
|
||||
private PluginManager: pluginApi.PluginManager
|
||||
|
||||
load() {
|
||||
this.logger.log('Test Plugin load from MiaoScript Plugin System...');
|
||||
this.logger.log('Test Plugin load from MiaoScript Plugin System...')
|
||||
}
|
||||
|
||||
enable() {
|
||||
this.logger.log('Test Plugin enable from MiaoScript Plugin System...');
|
||||
this.logger.log('Test Plugin enable from MiaoScript Plugin System...')
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.logger.log('Test Plugin disable from MiaoScript Plugin System...');
|
||||
this.logger.log('Test Plugin disable from MiaoScript Plugin System...')
|
||||
}
|
||||
|
||||
@cmd()
|
||||
test(sender: any, command: string, args: string[]) {
|
||||
switch (args[0]) {
|
||||
case "run":
|
||||
var script = args.slice(1).join(' ');
|
||||
console.sender(sender, '§b运行脚本:§r', script);
|
||||
console.sender(sender, '§a返回结果:§r', eval(script) || '§4没有返回结果!');
|
||||
break;
|
||||
var script = args.slice(1).join(' ')
|
||||
console.sender(sender, '§b运行脚本:§r', script)
|
||||
console.sender(sender, '§a返回结果:§r', eval(script) || '§4没有返回结果!')
|
||||
break
|
||||
case "reload":
|
||||
this.PluginManager.reload(this);
|
||||
break;
|
||||
this.PluginManager.reload(this)
|
||||
break
|
||||
case "yaml":
|
||||
let yaml = require("js-yaml");
|
||||
this.logger.log(yaml.safeDump({ key: 'value', map: { k1: 1, k2: '2' } }));
|
||||
break;
|
||||
let yaml = require("js-yaml")
|
||||
this.logger.log(yaml.safeDump({ key: 'value', map: { k1: 1, k2: '2' } }))
|
||||
break
|
||||
case "speed":
|
||||
this.logger.sender(sender, sender.location);
|
||||
break;
|
||||
this.logger.sender(sender, sender.location)
|
||||
break
|
||||
case "top":
|
||||
let loc = sender.location;
|
||||
let topY = loc.world.getHighestBlockYAt(loc);
|
||||
loc.y = topY;
|
||||
sender.teleport(loc);
|
||||
break;
|
||||
let loc = sender.location
|
||||
let topY = loc.world.getHighestBlockYAt(loc)
|
||||
loc.y = topY
|
||||
sender.teleport(loc)
|
||||
break
|
||||
case "up":
|
||||
if (!sender.openInventory) { return; }
|
||||
let player = sender;
|
||||
let location = player.location;
|
||||
player.velocity = player.velocity.setY(0.5);
|
||||
setTimeout(() => location.block.type = Java.type('org.bukkit.Material').STONE, 8);
|
||||
break;
|
||||
if (!sender.openInventory) { return }
|
||||
let player = sender
|
||||
let location = player.location
|
||||
player.velocity = player.velocity.setY(0.5)
|
||||
setTimeout(() => location.block.type = Java.type('org.bukkit.Material').STONE, 8)
|
||||
break
|
||||
case "add":
|
||||
break;
|
||||
break
|
||||
case "get":
|
||||
let result = http.get('https://www.baidu.com');
|
||||
this.logger.sender(sender, JSON.stringify(result));
|
||||
let result = http.get('https://www.baidu.com')
|
||||
this.logger.sender(sender, JSON.stringify(result))
|
||||
// 好了 扯结束 继续咸鱼
|
||||
break;
|
||||
break
|
||||
case "ws":
|
||||
let Sponge = Java.type('org.spongepowered.api.Sponge');
|
||||
let Sponge = Java.type('org.spongepowered.api.Sponge')
|
||||
// let promise = reflect.on(Bukkit.server).get('console').get('field_147144_o').get('field_151274_e').get().get(0);
|
||||
console.log(reflect.on(Sponge.server).get('field_147144_o').get())
|
||||
// let channel = reflect.on(promise).get('channel').get().pipeline().first();
|
||||
// console.log(channel);
|
||||
break;
|
||||
break
|
||||
default:
|
||||
this.logger.log(sender, command, args);
|
||||
this.logger.log(sender, command, args)
|
||||
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
"outDir": "dist",
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": false,
|
||||
"inlineSourceMap": true
|
||||
"inlineSourceMap": true,
|
||||
"declaration": false,
|
||||
"declarationMap": false
|
||||
},
|
||||
"exclude": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/sponge",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/sponge-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/common": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
22
packages/sponge/src/chat.ts
Normal file
22
packages/sponge/src/chat.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { chat } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
|
||||
const Sponge = org.spongepowered.api.Sponge
|
||||
const ChatTypes = org.spongepowered.api.text.chat.ChatTypes
|
||||
const TextSerializers = org.spongepowered.api.text.serializer.TextSerializers
|
||||
|
||||
@provideSingleton(chat.Chat)
|
||||
export class SpongeChat extends chat.Chat {
|
||||
sendJson(sender: any, json: string | object) {
|
||||
sender.sendMessage(TextSerializers.JSON.deserialize(typeof json === "string" ? json : JSON.stringify(json)))
|
||||
}
|
||||
sendMessage(sender: any, message: string) {
|
||||
sender.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(message))
|
||||
}
|
||||
sendActionBar(sender: any, message: string) {
|
||||
sender.sendMessage(ChatTypes.ACTION_BAR, TextSerializers.FORMATTING_CODE.deserialize(message))
|
||||
}
|
||||
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
||||
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ const Callable = Java.type('java.util.concurrent.Callable')
|
||||
const TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class SpongeTaskManager implements task.TaskManager {
|
||||
export class SpongeTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
private syncExecutor: any
|
||||
@@ -18,21 +18,20 @@ export class SpongeTaskManager implements task.TaskManager {
|
||||
this.syncExecutor = Sponge.getScheduler().createSyncExecutor(this.pluginInstance)
|
||||
}
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') }
|
||||
create0(func: Function): task.Task {
|
||||
return new SpongeTask(this.pluginInstance, func)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
// @ts-ignore
|
||||
return this.syncExecutor.schedule(new Callable({ call: () => func() }), java.lang.Long.valueOf(0), TimeUnit.NANOSECONDS).get()
|
||||
}
|
||||
disable() {
|
||||
disable0() {
|
||||
Sponge.getScheduler().getScheduledTasks(this.pluginInstance).forEach((task: task.Cancelable) => task.cancel())
|
||||
}
|
||||
}
|
||||
|
||||
export class SpongeTask extends task.Task {
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
submit0(...args: any[]): task.Cancelable {
|
||||
let run = Task.builder().execute(new Consumer({ accept: () => this.run(...args) }))
|
||||
if (this.isAsync) { run.async() }
|
||||
if (this.laterTime) { run.delayTicks(this.laterTime) }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/spring",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.3",
|
||||
"description": "MiaoScript spring package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,12 +21,12 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.0",
|
||||
"@ccms/common": "^0.8.0",
|
||||
"@ccms/container": "^0.8.0",
|
||||
"@ccms/database": "^0.8.0"
|
||||
"@ccms/api": "^0.9.3",
|
||||
"@ccms/common": "^0.9.3",
|
||||
"@ccms/container": "^0.9.3",
|
||||
"@ccms/database": "^0.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,14 +7,15 @@ import { CommandMap } from './internal/command'
|
||||
|
||||
@provideSingleton(command.Command)
|
||||
export class SpringCommand extends command.Command {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
@inject(CommandMap)
|
||||
private commandMap: CommandMap = new CommandMap()
|
||||
private commandMap: CommandMap
|
||||
|
||||
protected create(plugin: any, command: string) {
|
||||
return this.commandMap.register(plugin, command)
|
||||
}
|
||||
public tabComplete(sender: any, input: string, index?: number): string[] {
|
||||
return this.commandMap.tabComplate(sender, input, index)
|
||||
}
|
||||
protected remove(plugin: any, command: string) {
|
||||
this.commandMap.unregister(plugin, command)
|
||||
}
|
||||
@@ -22,6 +23,6 @@ export class SpringCommand extends command.Command {
|
||||
command.setExecutor(super.setExecutor(plugin, command, executor))
|
||||
}
|
||||
protected onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||
command.setTabCompleter(super.setExecutor(plugin, command, tabCompleter))
|
||||
command.setTabCompleter(super.setTabCompleter(plugin, command, tabCompleter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,10 +20,11 @@ export default function SpringImpl(container: Container) {
|
||||
}
|
||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
container.bind(server.Console).toConstantValue(SpringConsole)
|
||||
container.bind(ioc.Autowired).toDynamicValue((ctx) => {
|
||||
container.rebind(ioc.Autowired).toDynamicValue((ctx) => {
|
||||
var metadata: any = reduceMetadata(ctx)
|
||||
if (toString.call(metadata.named) === "[object Symbol]") { return container.get(metadata.named) }
|
||||
if (toString.call(metadata.named) === '[object jdk.internal.dynalink.beans.StaticClass]') { metadata.named = metadata.named.class }
|
||||
let key = toString.call(metadata.named)
|
||||
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
|
||||
if (key === '[object jdk.internal.dynalink.beans.StaticClass]') { metadata.named = metadata.named.class }
|
||||
return beanFactory.getBean(metadata.named)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ export class CommandMap {
|
||||
}
|
||||
|
||||
tabComplate(sender: any, input: string, index?: number): string[] {
|
||||
if (index == 0) { return Object.keys(this.commands) }
|
||||
if (index == 0) { return Object.keys(this.commands).concat('help') }
|
||||
let [command, ...args] = input.split(' ')
|
||||
let exists = this.commands[command]
|
||||
if (exists && exists.tabCompleter) {
|
||||
|
||||
@@ -4,29 +4,45 @@ import { provideSingleton, inject } from '@ccms/container'
|
||||
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
interface MySQLPlugin {
|
||||
name: string
|
||||
source: string
|
||||
}
|
||||
|
||||
@provideSingleton(plugin.PluginScanner)
|
||||
export class MySQLScanner implements plugin.PluginScanner {
|
||||
type: string = "mysql"
|
||||
|
||||
private cacheDir = 'mysql-plugin-cache'
|
||||
private cacheFileMap: Map<string, MySQLPlugin> = new Map()
|
||||
private target: string
|
||||
|
||||
@inject(database.DataBaseManager)
|
||||
private databaseManager: DataBaseManager
|
||||
|
||||
scan(target: any): string[] {
|
||||
scan(target: any): plugin.PluginLoadMetadata[] {
|
||||
this.target = target
|
||||
let plugins = this.databaseManager.getMainDatabase().query<{ name: string }>(`SELECT name FROM ${this.target} WHERE LENGTH(source) != 0 AND deleted = 0`)
|
||||
return plugins.map(p => `mysql:${p.name}`)
|
||||
let plugins = this.databaseManager.getMainDatabase().query<MySQLPlugin>(`SELECT name FROM ${this.target} WHERE LENGTH(source) != 0 AND deleted = 0`)
|
||||
return plugins.map(p => this.read(p))
|
||||
}
|
||||
load(target: any) {
|
||||
if (typeof target !== "string" || !target.startsWith('mysql:')) { return }
|
||||
let name = target.split("mysql:")[1]
|
||||
if (!name) { console.warn(`[PluginScanner][mysql] plugin name can't be null!`); return }
|
||||
var plugin: any = this.databaseManager.getMainDatabase().query<{ source: string }>(`SELECT source FROM ${this.target} WHERE name = ? AND deleted = 0`, name)
|
||||
if (plugin.length == 0) { console.warn(`[PluginScanner][mysql] plugin ${target} not found at mysql database...`); return }
|
||||
let temp = fs.concat(root, 'mysql-plugin-cache', target, `${plugin[0]}.js`)
|
||||
base.save(temp, plugin[0].source)
|
||||
read(mysqlPlugin: MySQLPlugin): plugin.PluginLoadMetadata {
|
||||
// if invoke this function from loadFromFile mysqlPlugin is a string need read from cache
|
||||
if (typeof mysqlPlugin == "string") {
|
||||
if (!this.cacheFileMap.has(mysqlPlugin)) { throw new Error(`this file ${mysqlPlugin} is not read from mysql-scanner. can't reload from this scanner!`) }
|
||||
mysqlPlugin = this.cacheFileMap.get(mysqlPlugin)
|
||||
}
|
||||
let cacheFile = fs.concat(root, this.cacheDir, `${mysqlPlugin.name}.js`)
|
||||
this.cacheFileMap.set(cacheFile, mysqlPlugin)
|
||||
return { name: mysqlPlugin.name, file: cacheFile, type: this.type, mysqlPlugin, scanner: this }
|
||||
}
|
||||
load(metadata: plugin.PluginLoadMetadata) {
|
||||
if (metadata.type !== this.type) { return }
|
||||
var plugin: any = this.databaseManager.getMainDatabase().query<MySQLPlugin>(`SELECT source FROM ${this.target} WHERE name = ? AND deleted = 0`, metadata.name)
|
||||
if (plugin.length == 0) { throw new Error(`[MySQLScanner] plugin ${metadata.name} not found at mysql database...`) }; plugin = plugin[0]
|
||||
if (!plugin.source) { throw new Error(`[MySQLScanner] plugin ${metadata.name} source can\'t be undefiend or empty...`) }
|
||||
base.save(metadata.file, plugin.source)
|
||||
//@ts-ignore
|
||||
return require(temp, { cache: false })
|
||||
metadata.instance = require(metadata.file, { cache: false })
|
||||
return metadata
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { server } from '@ccms/api'
|
||||
import { provideSingleton, inject } from '@ccms/container'
|
||||
import { NativePluginManager } from '@ccms/api/dist/interfaces/server/native_plugin'
|
||||
import { NativePluginManager } from '@ccms/api'
|
||||
import { CommandMap } from './internal/command'
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
@@ -8,8 +8,6 @@ export class SpringServer implements server.Server {
|
||||
@inject(CommandMap)
|
||||
private commandMap: CommandMap
|
||||
|
||||
constructor() {
|
||||
}
|
||||
getVersion(): string {
|
||||
return "SpringFramework"
|
||||
}
|
||||
@@ -47,10 +45,4 @@ export class SpringServer implements server.Server {
|
||||
getRootLogger() {
|
||||
return Packages.org.slf4j.LoggerFactory.getLogger("root") || global.logger
|
||||
}
|
||||
sendJson(sender: any, json: string | object): void {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
tabComplete(sender: any, input: string, index?: number) {
|
||||
return this.commandMap.tabComplate(sender, input, index)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,44 +6,57 @@ const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
const AtomicBoolean = Java.type("java.util.concurrent.atomic.AtomicBoolean")
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
|
||||
const taskId = new AtomicInteger(0)
|
||||
const tasks: { [key: number]: task.Cancelable } = {}
|
||||
const executor = thread_pool.create({
|
||||
groupName: '@ccms/spring'
|
||||
})
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class SpringTaskManager implements task.TaskManager {
|
||||
export class SpringTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
private innerTaskId: any
|
||||
private innerTasks: { [s: string]: task.Cancelable }
|
||||
private innerExecutor: java.util.concurrent.ThreadPoolExecutor
|
||||
private taskId: any
|
||||
private tasks: { [s: string]: task.Cancelable }
|
||||
private executor: java.util.concurrent.ThreadPoolExecutor
|
||||
|
||||
constructor() {
|
||||
this.innerTaskId = taskId
|
||||
this.innerTasks = tasks
|
||||
this.innerExecutor = executor
|
||||
super()
|
||||
this.taskId = new AtomicInteger(0)
|
||||
this.tasks = {}
|
||||
this.executor = thread_pool.create({
|
||||
groupName: '@ccms/spring'
|
||||
})
|
||||
}
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') }
|
||||
return new SpringTask(this.pluginInstance, func)
|
||||
create0(func: Function): task.Task {
|
||||
return new SpringTask(this.pluginInstance, func, this)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func()
|
||||
}
|
||||
disable() {
|
||||
Object.values(this.innerTasks).forEach((task) => task?.cancel())
|
||||
this.innerExecutor.shutdown()
|
||||
disable0() {
|
||||
Object.values(this.tasks).forEach((task) => task?.cancel())
|
||||
this.executor.shutdown()
|
||||
}
|
||||
nextId() {
|
||||
return this.taskId.incrementAndGet()
|
||||
}
|
||||
submit(id: number, task: SpringTask, func: Function) {
|
||||
this.tasks[id] = task
|
||||
this.executor.execute(func as any)
|
||||
}
|
||||
cancel(id: number) {
|
||||
delete this.tasks[id]
|
||||
}
|
||||
}
|
||||
|
||||
export class SpringTask extends task.Task {
|
||||
public id = taskId.incrementAndGet()
|
||||
private id: number
|
||||
private taskManager: SpringTaskManager
|
||||
private running = new AtomicBoolean(true)
|
||||
|
||||
constructor(plugin: any, func: Function, taskManager: SpringTaskManager) {
|
||||
super(plugin, func)
|
||||
this.id = taskManager.nextId()
|
||||
this.taskManager = taskManager
|
||||
}
|
||||
|
||||
run(...args: any[]) {
|
||||
if (this.laterTime > 0) {
|
||||
try {
|
||||
@@ -70,19 +83,18 @@ export class SpringTask extends task.Task {
|
||||
this.cancel()
|
||||
}
|
||||
|
||||
cancel(): any {
|
||||
cancel0(): any {
|
||||
var wasRunning = this.running.getAndSet(false)
|
||||
if (wasRunning) {
|
||||
delete tasks[this.id]
|
||||
this.taskManager.cancel(this.id)
|
||||
}
|
||||
}
|
||||
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
tasks[this.id] = this
|
||||
executor.execute((() => this.run(...args)) as any)
|
||||
submit0(...args: any[]) {
|
||||
this.taskManager.submit(this.id, this, () => this.run(...args))
|
||||
return {
|
||||
cancel: () => {
|
||||
return this.cancel()
|
||||
return this.cancel0()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user