Compare commits

..

38 Commits

Author SHA1 Message Date
47c85f70eb v0.9.9 2020-10-02 20:00:31 +08:00
da9e2063ca fix: continer Autowired error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 19:57:10 +08:00
0568a7abbe v0.9.8 2020-10-02 18:59:52 +08:00
7375e8e2e9 feat: add .editorconfig
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 18:54:28 +08:00
41d3923d94 feat: backup plugins
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 18:54:10 +08:00
f111b9891c feat: define config save & load
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 18:53:31 +08:00
2e4fdcb798 fix: Autowired Java class error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 18:48:37 +08:00
ab7ca932a3 fix: server method error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 16:43:18 +08:00
e8b3d43cdf feat: hide internal function
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 16:21:09 +08:00
eaaa0ef139 refactor: update type define
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-10-02 16:20:33 +08:00
94840ae59d feat: add papi hook
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-27 19:39:10 +08:00
c31eaeb8f6 feat: backup plugin
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-26 22:03:49 +08:00
469a66a277 feat: update javatypes version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-26 14:50:04 +08:00
cd6a2023dc v0.9.7 2020-09-25 10:13:59 +08:00
498b0ee017 fix: config inject error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-25 10:12:28 +08:00
9bfaf984c1 v0.9.6 2020-09-24 19:26:04 +08:00
3c33ebf4e6 feat: add sender check & add prun subcommand
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 18:36:53 +08:00
8af69c98f3 refactor: plugin system & config manager
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 18:36:10 +08:00
72277f4d1a v0.9.5 2020-09-24 15:36:45 +08:00
d85f75ba1f fix: plugin bug
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 15:32:05 +08:00
ed14d317f4 fix: command tab complate error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 15:27:34 +08:00
fb8a11ea05 v0.9.4 2020-09-24 13:51:39 +08:00
eae80fa30b backup: plugins 2020-09-24
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 13:51:18 +08:00
3e69fc42d9 feat: compatible 1.8.8 chat
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 13:48:14 +08:00
c5595a65fb fix: sponge command dispatch error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 10:51:31 +08:00
df266905f2 feat: update client support mcsso
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 10:33:38 +08:00
f8046e38be fix: command registry error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 10:33:16 +08:00
51fb5aece3 refactor: extract proxy & fix bungee chaneel
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-24 10:31:20 +08:00
7a1dd3e7b3 feat: update dependencies version
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-23 17:52:15 +08:00
8f3c799531 v0.9.3 2020-09-23 11:26:09 +08:00
3389dbd566 fix: bungee task error 2020-09-23 11:25:53 +08:00
54604e10b8 backup: plugins 2020-09-22
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-22 18:43:02 +08:00
d7247bae19 feat: optimize task impl
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-22 18:42:39 +08:00
3ee2dcad0b feat: add bungee proxy
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-22 17:36:32 +08:00
bc19021c63 feat: update Autowired & support command alias
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-22 17:36:04 +08:00
e9a4f2f351 refactor: chat & command tabComplete
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-09-22 15:29:12 +08:00
9be9c400ad v0.9.2 2020-09-17 17:45:04 +08:00
8eaf789bce feat: update ms system 2020-09-17 17:44:48 +08:00
96 changed files with 2302 additions and 1726 deletions

12
.editorconfig Normal file
View File

@@ -0,0 +1,12 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

View File

@@ -1,5 +1,5 @@
{
"version": "0.9.1",
"version": "0.9.9",
"useWorkspaces": true,
"npmClient": "yarn",
"packages": [

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/amqp",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript amqp package",
"keywords": [
"miaoscript",
@@ -19,17 +19,17 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/common": "^0.9.0",
"@ccms/container": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/common": "^0.9.8",
"@ccms/container": "^0.9.9"
},
"devDependencies": {
"@ccms/nashorn": "^0.9.0",
"@javatypes/amqp-client": "^0.0.2",
"@javatypes/spring-amqp": "^0.0.2",
"@javatypes/spring-rabbit": "^0.0.2",
"@ccms/nashorn": "^0.9.8",
"@javatypes/amqp-client": "^0.0.3",
"@javatypes/spring-amqp": "^0.0.3",
"@javatypes/spring-rabbit": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
}
}

View File

@@ -2,7 +2,7 @@ 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')
export const AcknowledgeMode = org.springframework.amqp.core.AcknowledgeMode
interface ContainerConfig {
connectionFactory: ConnectionFactoryAdapter | typeof ConnectionFactory
queueNames: string[]
@@ -27,4 +27,4 @@ export class MessageListenerContainerAdapter {
getHandler() {
return this._Handler
}
}
}

View File

@@ -46,7 +46,7 @@ export class AmqpAdmin {
}
declareBinding(queue: string, exchange: string, routerKey: string, argument: any = null) {
let binding = new this.Binding(queue, this.DestinationType.QUEUE, exchange, routerKey, argument)
let binding = new this.Binding(queue, org.springframework.amqp.core.Binding.DestinationType.QUEUE, exchange, routerKey, argument)
this.amqpAdmin.declareBinding(binding)
return this
}
@@ -86,4 +86,4 @@ export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
return this.handler(content, message, channel)
}
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/api",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -19,9 +19,9 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/common": "^0.9.0",
"@ccms/container": "^0.9.0",
"@ccms/ployfill": "^0.9.0",
"@ccms/common": "^0.9.8",
"@ccms/container": "^0.9.9",
"@ccms/ployfill": "^0.9.8",
"base64-js": "^1.3.1",
"source-map-builder": "^0.0.7"
},
@@ -29,6 +29,6 @@
"@types/base64-js": "^1.3.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
}
}

View File

@@ -1,4 +1,4 @@
import { injectable } from "@ccms/container";
import { injectable } 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]
}
}
/**

View File

@@ -1,5 +1,17 @@
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.")
}
@@ -9,7 +21,7 @@ export namespace chat {
clearActionBar(sender: any) {
this.sendActionBar(sender, '')
}
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 1, time: number = 5, fadeOut: number = 1) {
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) {

View File

@@ -13,7 +13,7 @@ export namespace command {
*/
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
var cmd = this.create(plugin, name)
if (!cmd) { throw Error("") }
if (!cmd) { throw Error(`Plugin ${plugin.description.name} can't create Command ${name}!`) }
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
if (exec.cmd && typeof exec.cmd === "function") {
this.onCommand(plugin, cmd, exec.cmd)
@@ -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 插件
@@ -59,9 +62,9 @@ export namespace command {
var complete = tabCompleter(sender, command, Java.from(args)) || []
return this.copyPartialMatches(complete, token)
} catch (ex) {
console.i18n("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
console.i18n("ms.api.command.tab.completer.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
console.ex(ex)
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
return []
}
}

View File

@@ -130,23 +130,22 @@ export namespace event {
}
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
// add to cache Be used for close plugin to close event
if (!listenerMap[name]) listenerMap[name] = []
var offExec = () => {
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: exec.name || '[anonymous]' }))
}
var off = {
event: eventCls,
listener: listener,
off: offExec
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), exec: exec.name || '[anonymous]' }))
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls), exec: executor }))
return off
}
@@ -157,7 +156,7 @@ export namespace event {
disable(plugin: any) {
var eventCache = this.listenerMap[plugin.description.name]
if (eventCache) {
eventCache.forEach(t => t.off())
eventCache.forEach(off => off())
delete this.listenerMap[plugin.description.name]
}
}

View File

@@ -3,6 +3,7 @@ import "@ccms/nashorn"
export * from './chat'
export * from './task'
export * from './event'
export * from './proxy'
export * from './console'
export * from './channel'
export * from './command'

View File

@@ -1,3 +1,5 @@
import { injectable } from '@ccms/container'
export namespace plugin {
/**
* MiaoScript Plugin
@@ -11,23 +13,20 @@ 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")
/**
@@ -38,10 +37,6 @@ export namespace plugin {
* 插件加载类型
*/
type: string
/**
* 插件名称
*/
name?: string
/**
* 插件文件
*/
@@ -116,22 +111,22 @@ export namespace 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

View File

@@ -4,6 +4,8 @@ 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,21 +22,44 @@ 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 Server {
getVersion(): string {
throw new Error("Method not implemented.")
}
getPlayer(name: string): any {
throw new Error("Method not implemented.")
}
getOnlinePlayers(): any[] {
throw new Error("Method not implemented.")
}
getConsoleSender(): any {
throw new Error("Method not implemented.")
}
getService(service: string): any {
throw new Error("Method not implemented.")
}
dispatchCommand(sender: string | any, command: string): boolean {
throw new Error("Method not implemented.")
}
dispatchConsoleCommand(command: string): boolean {
throw new Error("Method not implemented.")
}
getPluginsFolder(): string {
throw new Error("Method not implemented.")
}
getNativePluginManager(): NativePluginManager {
throw new Error("Method not implemented.")
}
getDedicatedServer?(): any {
throw new Error("Method not implemented.")
}
getNettyPipeline(): any {
throw new Error("Method not implemented.")
}
getRootLogger(): any {
throw new Error("Method not implemented.")
}
}
@injectable()
export class ServerChecker {
@@ -58,56 +79,15 @@ export namespace server {
}
}
@injectable()
export abstract class ReflectServer implements server.Server {
export abstract class ReflectServer extends server.Server {
protected pipeline: any
protected rootLogger: any
constructor() {
super()
this.reflect()
}
getVersion(): string {
throw new Error("Method not implemented.")
}
getPlayer(name: string) {
throw new Error("Method not implemented.")
}
getOnlinePlayers(): any[] {
throw new Error("Method not implemented.")
}
getConsoleSender() {
throw new Error("Method not implemented.")
}
getService(service: string) {
throw new Error("Method not implemented.")
}
dispatchCommand(sender: any, command: string): boolean {
throw new Error("Method not implemented.")
}
dispatchConsoleCommand(command: string): boolean {
throw new Error("Method not implemented.")
}
getPluginsFolder(): string {
throw new Error("Method not implemented.")
}
getNativePluginManager(): NativePluginManager {
throw new Error("Method not implemented.")
}
getDedicatedServer() {
throw new Error("Method not implemented.")
}
getNettyPipeline() {
throw new Error("Method not implemented.")
}
getRootLogger() {
throw new Error("Method not implemented.")
}
sendJson(sender: any, json: string | object): void {
throw new Error("Method not implemented.")
}
tabComplete?(sender: any, input: string, index?: number): string[] {
throw new Error("Method not implemented.")
}
protected reflect() {
try {
let consoleServer = this.getDedicatedServer()

161
packages/api/src/proxy.ts Normal file
View File

@@ -0,0 +1,161 @@
import { provideSingleton, Autowired, optional } from '@ccms/container'
import { channel } from './channel'
export namespace proxy {
const ByteArrayOutputStream = Java.type('java.io.ByteArrayOutputStream')
const DataOutputStream = Java.type('java.io.DataOutputStream')
namespace bungeecord {
const CHANNEL_NAME = "BungeeCord"
export class SubChannelBuilder {
private channel: channel.Channel
private player: any
private params: string[]
constructor(channel: channel.Channel, player: any) {
this.channel = channel
this.player = player
this.params = []
}
connect(server: string) {
this.params.push("Connect")
this.params.push(server)
return this.finalSend()
}
connectOther(player: string, server: string) {
this.params.push("ConnectOther")
this.params.push(player)
this.params.push(server)
return this.finalSend()
}
ip() {
this.params.push("IP")
return this.finalSend()
}
ipOther(player: string) {
this.params.push("IPOther")
this.params.push(player)
return this.finalSend()
}
playerCount(server: string | "ALL") {
this.params.push("PlayerCount")
this.params.push(server)
return this.finalSend()
}
/**
* 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)
return this.finalSend()
}
/**
* 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) {
return 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)
}
return this.channel.send(this.player, CHANNEL_NAME, byteArray.toByteArray())
}
private finalSend() {
return {
send: this.send.bind(this)
}
}
}
}
@provideSingleton(BungeeCord)
export class BungeeCord {
@optional()
@Autowired()
private channel: channel.Channel
/**
* 获得代理
* @param player 玩家
*/
for(player: any): bungeecord.SubChannelBuilder {
return new bungeecord.SubChannelBuilder(this.channel, player)
}
}
}

View File

@@ -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
}
/**
* 在主线程执行代码
* @param func 执行内容
*/
callSyncMethod(func: Function): any;
abstract callSyncMethod(func: Function): any
/**
* 关闭任务管理器
*/
disable();
disable(plugin?: plugin.Plugin) {
if (plugin) { return this.pluginDisable(plugin) }
this.disable0()
}
protected abstract create0(func: Function): task.Task
protected 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 任务参数
*/
protected abstract submit0(...args: any[]): Cancelable
}
/**
* 返可取消的对象
*/
export interface Cancelable {
cancel(): boolean;
cancel(): boolean
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bukkit",
"version": "0.9.1",
"version": "0.9.9",
"description": "MiaoScript bukkit package",
"keywords": [
"miaoscript",
@@ -19,14 +19,14 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@javatypes/spigot-api": "^0.0.2",
"@javatypes/spigot-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/common": "^0.9.0",
"@ccms/container": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/common": "^0.9.8",
"@ccms/container": "^0.9.9"
}
}

View File

@@ -9,7 +9,7 @@ const Messenger = Bukkit.getMessenger()
export class BukkitChannel extends channel.Channel {
@inject(plugin.PluginInstance)
private pluginInstance: any
private cacheChannel = new Map<string, any[]>()
/**
* 给玩家发送通道消息
* @param player 接受消息的玩家
@@ -26,15 +26,29 @@ export class BukkitChannel extends channel.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.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)
}
}
}

View File

@@ -4,13 +4,20 @@ 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) {
bukkitChat.send(sender, { text: message }, 0)
this.sendJson(sender, { text: message }, 0)
}
sendActionBar(sender: any, message: string) {
bukkitChat.send(sender, { text: message }, 2)
this.sendJson(sender, { text: message }, 2)
}
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 1, time: number = 5, fadeOut: number = 1) {
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
try {
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
} catch (error) {
sender.sendTitle(title, subtitle)
}
}
}

View File

@@ -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)
}));
}))
}
}

View File

@@ -9,6 +9,7 @@ let RemapUtils: any
let playerConnectionFieldName: string
let sendPacketMethodName: string
let above_1_16 = false
let downgrade = false
/**
* 获取NMS版本
@@ -59,12 +60,18 @@ function init() {
let packetTypeClass = nmsCls("PacketPlayOutChat")
PacketPlayOutChat = Java.type(packetTypeClass.getName())
let packetTypeConstructor: { parameterTypes: any[] }
Java.from(packetTypeClass.constructors).forEach(function (c) {
let constructors = packetTypeClass.constructors
Java.from(constructors).forEach(function (c) {
if (c.parameterTypes.length === 2) {
packetTypeConstructor = c
}
if (c.parameterTypes.length === 3) {
packetTypeConstructor = c
above_1_16 = true
}
})
let nmsChatMessageTypeClass = packetTypeConstructor.parameterTypes[1]
let parameterTypes = packetTypeConstructor.parameterTypes
let nmsChatMessageTypeClass = parameterTypes[1]
if (nmsChatMessageTypeClass.isEnum()) {
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
}
@@ -83,7 +90,13 @@ function json(sender: { name: string }, json: string) {
}
function send(sender: any, json: any, type: number) {
sendPacket(sender, new PacketPlayOutChat(ChatSerializer[nmsChatSerializerMethodName](json), chatMessageTypes == null ? type : chatMessageTypes[type]))
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: { handle: { [x: string]: { [x: string]: (arg0: any) => void } } }, p: any) {

View File

@@ -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)
}

View File

@@ -16,13 +16,13 @@ export class BukkitServer extends server.ReflectServer {
}
getPlayer(name: string) {
return Bukkit.getPlayer(name)
return Bukkit.getPlayerExact(name)
}
getVersion(): string {
return Bukkit.getVersion()
}
getOnlinePlayers() {
return Bukkit.getOnlinePlayers() as unknown as any[]
return Bukkit.getOnlinePlayers()
}
getConsoleSender() {
return Bukkit.getConsoleSender()
@@ -54,13 +54,4 @@ export class BukkitServer extends server.ReflectServer {
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, typeof json == "string" ? json : JSON.stringify(json))
if (result !== false) {
this.dispatchConsoleCommand(result)
}
}
}

View File

@@ -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) {

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/bungee",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript bungee package",
"keywords": [
"miaoscript",
@@ -19,14 +19,14 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@javatypes/bungee-api": "^0.0.2",
"@javatypes/bungee-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/common": "^0.9.0",
"@ccms/container": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/common": "^0.9.8",
"@ccms/container": "^0.9.9"
}
}

View File

@@ -6,20 +6,20 @@ const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
@provideSingleton(channel.Channel)
export class BungeeChannel extends channel.Channel {
@inject(event.Event)
private eventManager: event.Event;
private eventManager: event.Event
send(player: any, channel: string, data: any) {
throw new Error("Method not implemented.");
throw new Error("Method not implemented.")
}
register(channel: string, listener: channel.ChannelListener) {
Bungee.registerChannel(channel);
Bungee.registerChannel(channel)
// console.console('§6[§eWARN§6] §eMiaoScript channel in BungeeCord only register. you need self hanler PluginMessageEvent!')
return this.eventManager.listen({ description: { name: channel } }, "PluginMessageEvent", (event: net.md_5.bungee.api.event.PluginMessageEvent) => {
listener(event.getData(), event)
})
}
unregister(channel: string, listener: any) {
Bungee.unregisterChannel(channel);
listener.off();
unregister(channel: string, off: any) {
Bungee.unregisterChannel(channel)
off()
}
}

View File

@@ -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
}
}

View File

@@ -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)

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@ccms/client",
"version": "0.9.0",
"version": "0.9.4",
"description": "MiaoScript client package",
"keywords": [
"miaoscript",
@@ -22,10 +22,10 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"minecraft-protocol": "^1.13.0"
"minecraft-protocol": "^1.16.0"
},
"devDependencies": {
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
}
}

View File

@@ -3,12 +3,12 @@ import { $ } from './color'
export function attachEvents(client) {
client.on('chat', (packet) => {
// Listen for chat messages and echo them back.
var jsonMsg = JSON.parse(packet.message);
var jsonMsg = JSON.parse(packet.message)
console.log($(jsonMsg))
})
client.on('state', (newState, oldState) => {
console.log('Client Change State', oldState, 'to', newState)
let targetServer = process.argv[3]
let targetServer = process.argv[6]
if (newState == "play" && targetServer) {
setTimeout(() => {
client.write('chat', {
@@ -24,4 +24,10 @@ export function attachEvents(client) {
} else if (packet.health > 0) {
}
})
client.on('kick_disconnect', (packet) => {
console.log($(packet.reason))
})
client.on('disconnect', (packet) => {
console.log($(packet.reason))
})
}

View File

@@ -5,33 +5,52 @@ import { attachForge } from './forge'
import { attachEvents } from './event'
let username = process.argv[2] || 'Mr_jtb'
let version = process.argv[3] || '1.12.2'
let address = process.argv[4] || '192.168.2.5:25577'
let realAddress = address.split(":");
let client = createConnection(realAddress[0], parseInt(realAddress[1] || "25565"), username)
let password = process.argv[3] || ''
let version = process.argv[4] || '1.12.2'
let readAddress = process.argv[5] || '192.168.2.5:25577'
let realAddress = readAddress.split(":")
let address = realAddress[0]
let port = parseInt(realAddress[1] || "25565")
let client = commandLineCreateClient()
function createConnection(host: string, port: number, username: string) {
function commandLineCreateClient() {
return createConnection(address, port, username, password)
}
function createConnection(host: string, port: number, username: string, password: string) {
let client = createClient({
version,
host,
port,
username,
skipValidation: true
password,
clientToken: 'd02c7f39-2376-45da-a5a5-50e24fa8b185',
//@ts-ignore
authServer: 'https://mcsso.yumc.pw/api/yggdrasil/authserver',
sessionServer: 'https://mcsso.yumc.pw/api/yggdrasil/sessionserver'
})
attachCommon(client)
attachForge(client)
attachEvents(client)
return client;
return client
}
client.on('error', (error) => {
console.log("Client Error", error)
})
client.on('end', (resone) => {
console.log("Client End Resone:", resone)
client = createConnection('192.168.2.5', 25577, username)
})
function attachCommon(client) {
client.on('error', (error) => {
console.log("Client Error", error)
})
client.on('end', (resone) => {
console.log("Client End Resone:", resone)
if (`${resone}` != "SocketClosed") {
setTimeout(() => {
client = commandLineCreateClient()
}, 500)
} else {
process.exit(0)
}
})
}
const rl = createInterface({
input: process.stdin,
@@ -54,22 +73,22 @@ const rl = createInterface({
rl.on('line', function (line) {
switch (line) {
case "":
break;
break
case "eval":
break;
break
case "write":
break;
break
case "/respawn":
client.write('client_command', { payload: 0 })
break;
break
case "//reco":
client.end("")
client = createConnection('192.168.2.5', 25577, username)
break;
client = commandLineCreateClient()
break
case "//quit":
console.info('Disconnected')
client.end("")
break;
break
case "//end":
console.info('Forcibly ended client')
process.exit(0)

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/common",
"version": "0.9.0",
"version": "0.9.8",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -19,11 +19,11 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.9.0",
"@javatypes/jdk": "^0.0.2",
"@ccms/nashorn": "^0.9.8",
"@javatypes/jdk": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
}

View File

@@ -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 })
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/compile",
"version": "0.9.0",
"version": "0.9.4",
"description": "MiaoScript compile package",
"keywords": [
"miaoscript",
@@ -21,6 +21,6 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/container",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript container package",
"keywords": [
"miaoscript",
@@ -19,10 +19,10 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.9.0",
"@ccms/nashorn": "^0.9.8",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"inversify": "^5.0.1",

View File

@@ -2,7 +2,7 @@
import "reflect-metadata"
import { initContainer, getContainer } from './decorators'
import { interfaces, Container } from 'inversify'
import { interfaces, Container, inject, named } from 'inversify'
import { fluentProvide } from 'inversify-binding-decorators'
import { ioc } from "./constants"
@@ -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!')
}
}
@@ -59,9 +59,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)
export const Autowired = (className?: any) => {
return function (target: any, propertyKey: string, index?: number) {
let container = getContainer()
if (className && (className instanceof Symbol || className instanceof Function)) {
return inject(className)(target, propertyKey, index)
}
let type = Reflect.getMetadata('design:type', target, propertyKey)
if (type && type !== Object && !Java.isJavaObject(type)) {
inject(type)(target, propertyKey, index)
named(className || propertyKey)(target, propertyKey, index)
} else if (container.isBound(ioc.Autowired)) {
console.debug('Autowired', 'ioc.Autowired', 'named', className || propertyKey)
target[propertyKey] = container.getNamed(ioc.Autowired, className || propertyKey)
} else {
throw new Error(`No matching bindings found for target: ${target.constructor.name} type: ${type} named: ${className || propertyKey}`)
}
}
}
@@ -70,7 +83,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 +95,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'

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/core",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -21,11 +21,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/container": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/container": "^0.9.9"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -49,10 +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.exit(0)
console.i18n("ms.core.engine.disable.finish", { version: 'v' + global.ScriptEngineVersion, time: (new Date().getTime() - disableStartTime) / 1000 })
}
}
@@ -86,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()
@@ -103,7 +105,7 @@ function initialize() {
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 })

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/database",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript database package",
"keywords": [
"miaoscript",
@@ -19,13 +19,13 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@javatypes/spring-jdbc": "^0.0.2",
"@javatypes/spring-jdbc": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/container": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/container": "^0.9.9"
}
}

View File

@@ -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} => {exec}"
ms.api.event.unregister: "[{name}] 注销事件 {event} => {exec}"
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}..."

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/i18n",
"version": "0.9.0",
"version": "0.9.8",
"description": "MiaoScript i18n package",
"keywords": [
"miaoscript",
@@ -19,11 +19,11 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.9.0",
"@ccms/nashorn": "^0.9.8",
"@types/js-yaml": "^3.12.5",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"js-yaml": "^3.14.0"

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/keyvalue",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript keyvalue package",
"keywords": [
"miaoscript",
@@ -19,18 +19,18 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/common": "^0.9.0",
"@ccms/container": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/common": "^0.9.8",
"@ccms/container": "^0.9.9"
},
"devDependencies": {
"@ccms/nashorn": "^0.9.0",
"@javatypes/amqp-client": "^0.0.2",
"@javatypes/spring-amqp": "^0.0.2",
"@javatypes/spring-rabbit": "^0.0.2",
"@ccms/nashorn": "^0.9.8",
"@javatypes/amqp-client": "^0.0.3",
"@javatypes/spring-amqp": "^0.0.3",
"@javatypes/spring-rabbit": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
}

View File

@@ -1,17 +0,0 @@
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
}
}

View File

@@ -1,30 +0,0 @@
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
}
}

View File

@@ -1,31 +0,0 @@
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
}
}

View File

@@ -1,30 +0,0 @@
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
}
}

View File

@@ -1,37 +0,0 @@
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
}
}

View File

@@ -1,7 +0,0 @@
export * from './admin'
export * from './callback'
export * from './connection'
export * from './container'
export * from './converter'
export * from './listener'
export * from './template'

View File

@@ -1,49 +0,0 @@
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))
}
}
}

View File

@@ -1,27 +0,0 @@
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
}
}

View File

@@ -1,89 +0,0 @@
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)
}
}

View File

@@ -1,3 +0,0 @@
export const METADATA_KEY = {
}

View File

@@ -1,34 +1,3 @@
/// <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'
export { }

View File

@@ -1,5 +0,0 @@
export class AmqpListener {
constructor() {
}
}

View File

@@ -1,18 +0,0 @@
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))
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/nashorn",
"version": "0.9.0",
"version": "0.9.8",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -22,6 +22,6 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
}
}

View File

@@ -17,6 +17,7 @@ declare global {
function to<T = any>(array: T[], type?: T): T[]
function extend(...parentTypes: any[]): any
function synchronized(func: () => void, lock: any): Function
function isJavaObject(obj: any): boolean
function asJSONCompatible<T = any>(obj: T): T
//@ts-ignore
// function super(type: any);
@@ -48,7 +49,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

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/nodejs",
"version": "0.9.0",
"version": "0.9.8",
"description": "MiaoScript nodejs package",
"keywords": [
"miaoscript",
@@ -19,10 +19,10 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.9.0",
"@ccms/nashorn": "^0.9.8",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/nukkit",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript nukkit package",
"keywords": [
"miaoscript",
@@ -19,14 +19,14 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@javatypes/nukkit-api": "^0.0.2",
"@javatypes/nukkit-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/common": "^0.9.0",
"@ccms/container": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/common": "^0.9.8",
"@ccms/container": "^0.9.9"
}
}

View File

@@ -1,25 +1,25 @@
import { server } from '@ccms/api'
import { provideSingleton } from '@ccms/container';
import { provideSingleton } from '@ccms/container'
let Nukkit: cn.nukkit.Server = base.getInstance().getServer();
const File = Java.type("java.io.File");
let Nukkit: cn.nukkit.Server = base.getInstance().getServer()
const File = Java.type("java.io.File")
@provideSingleton(server.Server)
export class NukkitServer implements server.Server {
private pluginsFolder: string;
private pluginsFolder: string
constructor() {
this.pluginsFolder = new File(base.getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getCanonicalPath()
}
getPlayer(name: string) {
return Nukkit.getPlayer(name)
return Nukkit.getPlayerExact(name)
}
getVersion(): string {
return Nukkit.getVersion()
}
getOnlinePlayers() {
return Nukkit.getOnlinePlayers() as unknown as any[]
return Nukkit.getOnlinePlayers().values()
}
getConsoleSender() {
return Nukkit.getConsoleSender()
@@ -37,18 +37,15 @@ export class NukkitServer implements server.Server {
return Nukkit.dispatchCommand(Nukkit.getConsoleSender(), command)
}
getPluginsFolder(): string {
return this.pluginsFolder;
return this.pluginsFolder
}
getNativePluginManager() {
return Nukkit.getPluginManager() as any;
return Nukkit.getPluginManager() as any
}
getNettyPipeline() {
throw new Error("Method not implemented.");
throw new Error("Method not implemented.")
}
getRootLogger() {
return Packages.org.apache.logging.log4j.LogManager.getRootLogger()
}
sendJson(sender: string | any, json: object | string): void {
throw new Error("Method not implemented.");
}
}

View File

@@ -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;
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/ployfill",
"version": "0.9.0",
"version": "0.9.8",
"description": "MiaoScript ployfill package",
"author": "MiaoWoo <admin@yumc.pw>",
"homepage": "https://github.com/circlecloud/ms.git",
@@ -14,14 +14,14 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ccms/i18n": "^0.9.0",
"@ccms/nodejs": "^0.9.0",
"@ccms/i18n": "^0.9.8",
"@ccms/nodejs": "^0.9.8",
"core-js": "^3.6.5"
},
"devDependencies": {
"@ccms/nashorn": "^0.9.0",
"@ccms/nashorn": "^0.9.8",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
}
}

View File

@@ -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')
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/plugin",
"version": "0.9.1",
"version": "0.9.9",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -22,13 +22,13 @@
"@types/js-yaml": "^3.12.5",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/common": "^0.9.0",
"@ccms/container": "^0.9.0",
"@ccms/i18n": "^0.9.0",
"@ccms/api": "^0.9.9",
"@ccms/common": "^0.9.8",
"@ccms/container": "^0.9.9",
"@ccms/i18n": "^0.9.8",
"js-yaml": "^3.14.0"
}
}

View File

@@ -1,29 +1,35 @@
import { command, plugin, server } from '@ccms/api'
import { provideSingleton, postConstruct, inject } from '@ccms/container'
import { provideSingleton, inject, Autowired } from '@ccms/container'
import { getPluginCommandMetadata, getPluginTabCompleterMetadata } from './utils'
@provideSingleton(PluginCommandManager)
export class PluginCommandManager {
@inject(server.ServerChecker)
private ServerChecker: server.ServerChecker
@inject(command.Command)
@Autowired()
private CommandManager: command.Command
@Autowired()
private ServerChecker: server.ServerChecker
constructor() {
process.on('plugin.before.enable', (plugin: plugin.Plugin) => this.registryCommand(plugin))
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.unregistryCommand(plugin))
process.on('plugin.before.enable', this.registryCommand.bind(this))
process.on('plugin.after.disable', this.unregistryCommand.bind(this))
}
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
})
for (const cmd of cmds) {
if (!this.ServerChecker.check(cmd.servers)) {
console.debug(`[${pluginInstance.description.name}] ${cmd.target.constructor.name} incompatible command ${cmd.name} server(${cmd.servers}) ignore.`)
continue
}
for (let command of [cmd.name, ...cmd.alias]) {
this.CommandManager.on(pluginInstance, command, {
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
tab: tabs.has(command) ?
pluginInstance[tabs.get(command).executor].bind(pluginInstance) :
console.debug(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`)
})
}
}
}

View File

@@ -1,6 +1,9 @@
import * as yaml from 'js-yaml'
import * as fs from '@ccms/common/dist/fs'
import { plugin } from '@ccms/api'
import { provideSingleton } from '@ccms/container'
import { interfaces } from './interfaces'
import { getPluginConfigMetadata } from './utils'
export interface PluginConfigLoader {
@@ -13,7 +16,7 @@ export class YamlPluginConfig implements PluginConfigLoader {
return yaml.safeLoad(content)
}
dump(variable: any): string {
return yaml.safeDump(variable, { skipInvalid: true })
return yaml.safeDump(variable, { skipInvalid: true, lineWidth: 120 })
}
}
@@ -22,63 +25,93 @@ export class JsonPluginConfig implements PluginConfigLoader {
return JSON.parse(content)
}
dump(variable: any): string {
return JSON.stringify(variable)
return JSON.stringify(variable, undefined, 4)
}
}
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)
export interface PluginConfig {
/**
* Save Config to File
*/
readonly save?: () => void
/**
* Reload Config from File
*/
readonly reload?: () => void
[key: string]: any
}
function loadConfig(plugin: plugin.Plugin) {
let configs = getPluginConfigMetadata(plugin)
for (let [_, config] of configs) {
@provideSingleton(PluginConfigManager)
export class PluginConfigManager {
private configLoaderMap = new Map<string, PluginConfigLoader>()
constructor() {
this.configLoaderMap.set("json", new JsonPluginConfig())
let yaml = new YamlPluginConfig()
this.configLoaderMap.set("yml", yaml)
this.configLoaderMap.set("yaml", yaml)
process.on('plugin.before.load', this.loadConfig.bind(this))
process.on('plugin.after.disable', this.saveConfig.bind(this))
}
getConfigLoader(format: string) {
if (!this.configLoaderMap.has(format)) { throw new Error(`Unsupport config format ${format} !`) }
return this.configLoaderMap.get(format)
}
loadConfig(plugin: plugin.Plugin) {
let configs = getPluginConfigMetadata(plugin)
for (let [_, config] of configs) {
this.loadConfig0(plugin, config)
}
}
saveConfig(plugin: plugin.Plugin) {
let configs = getPluginConfigMetadata(plugin)
for (let [_, config] of configs) {
this.saveConfig0(plugin, config)
}
}
private defienConfigProp(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata, value: any) {
Object.defineProperties(value, {
'save': { value: () => this.saveConfig0(plugin, metadata) },
'reload': { value: () => this.loadConfig0(plugin, metadata) }
})
Object.defineProperty(plugin, metadata.variable, { value })
}
private loadConfig0(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata) {
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 })
metadata.file = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, metadata.filename)
let configLoader = this.getConfigLoader(metadata.format)
let value = plugin[metadata.variable]
if (!fs.exists(metadata.file)) {
base.save(metadata.file, configLoader.dump(value))
console.i18n("ms.plugin.manager.config.save.default", { plugin: plugin.description.name, name: metadata.name, format: metadata.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])}`)
value = configLoader.load(base.read(metadata.file))
console.debug(`[${plugin.description.name}] Load Config ${metadata.variable} from file ${metadata.file} =>\n${JSON.stringify(value, undefined, 4)}`)
}
this.defienConfigProp(plugin, metadata, value)
} catch (error) {
console.i18n("ms.plugin.manager.config.load.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
console.i18n("ms.plugin.manager.config.load.error", { plugin: plugin.description.name, name: metadata.name, format: metadata.format, error })
console.ex(error)
}
}
}
function saveConfig(plugin: plugin.Plugin) {
let configs = getPluginConfigMetadata(plugin)
for (let [_, config] of configs) {
private saveConfig0(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata) {
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])) }
if (metadata.readonly) { console.debug(`[${plugin.description.name}] Skip Save Config ${metadata.variable} Because it's readonly!`) }
metadata.file = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, metadata.filename)
let result = this.getConfigLoader(metadata.format).dump(plugin[metadata.variable])
base.save(metadata.file, result)
console.debug(`[${plugin.description.name}] Save Config ${metadata.variable} to file ${metadata.file} =>\n${result}`)
return true
} catch (error) {
console.i18n("ms.plugin.manager.config.save.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
console.i18n("ms.plugin.manager.config.save.error", { plugin: plugin.description.name, name: metadata.name, format: metadata.format, error })
console.ex(error)
return false
}
}
}
function init() {
configLoaderMap.set("json", new JsonPluginConfig())
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()

View File

@@ -1,6 +1,6 @@
export const METADATA_KEY = {
plugin: Symbol.for("@ccms/plugin:plugin"),
souece: Symbol.for("@ccms/plugin:souece"),
source: Symbol.for("@ccms/plugin:source"),
cmd: Symbol.for("@ccms/plugin:cmd"),
tab: Symbol.for("@ccms/plugin:tab"),
listener: Symbol.for("@ccms/plugin:listener"),
@@ -10,4 +10,4 @@ export const METADATA_KEY = {
enable: Symbol.for("@ccms/plugin:stage:enable"),
disable: Symbol.for("@ccms/plugin:stage:disable")
}
};
}

View File

@@ -19,7 +19,7 @@ export function plugin(metadata: pluginApi.PluginMetadata | any) {
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect)
const previousSources: Map<string, pluginApi.PluginMetadata> = getPluginSources()
previousSources.set(metadata.source.toString(), metadata)
Reflect.defineMetadata(METADATA_KEY.souece, previousSources, Reflect)
Reflect.defineMetadata(METADATA_KEY.source, previousSources, Reflect)
}
}
@@ -30,11 +30,11 @@ export function plugin(metadata: pluginApi.PluginMetadata | any) {
export function cmd(metadata: interfaces.CommandMetadata = {}) {
return function (target: any, key: string, value: any) {
metadata.name = metadata.name || key
metadata.alias = metadata.alias || []
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)
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor)
Reflect.defineMetadata(METADATA_KEY.cmd, [metadata, ...getPluginCommandMetadata(target)], target.constructor)
}
}
@@ -46,10 +46,13 @@ 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.alias = metadata.alias || []
metadata.target = target
metadata.executor = key
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginTabCompleterMetadata(target)
let previousMetadata = 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 +64,10 @@ 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, ...getPluginListenerMetadata(target)], target.constructor)
Reflect.defineMetadata(METADATA_KEY.listener, metadata, target[key])
}
}
@@ -73,7 +77,8 @@ export function config(metadata: interfaces.ConfigMetadata = {}) {
metadata.variable = key
metadata.version = metadata.version ?? 1
metadata.format = metadata.format ?? 'yml'
const previousMetadata: Map<string, interfaces.ConfigMetadata> = getPluginConfigMetadata(target)
metadata.filename = metadata.filename ?? metadata.name + '.' + metadata.format
let previousMetadata = getPluginConfigMetadata(target)
previousMetadata.set(metadata.name, metadata)
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor)
}
@@ -84,8 +89,7 @@ function stage(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)
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...getPluginStageMetadata(target, stage)], target.constructor)
}
}
}

View File

@@ -1,26 +1,36 @@
import { event, plugin, server } from '@ccms/api'
import { provideSingleton, postConstruct, inject } from '@ccms/container'
import { provideSingleton, Autowired } from '@ccms/container'
import { getPluginListenerMetadata } from './utils'
@provideSingleton(PluginEventManager)
export class PluginEventManager {
@inject(server.ServerChecker)
private ServerChecker: server.ServerChecker
@inject(event.Event)
@Autowired()
private EventManager: event.Event
@Autowired()
private ServerChecker: server.ServerChecker
constructor() {
process.on('plugin.before.enable', (plugin: plugin.Plugin) => this.registryListener(plugin))
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.unregistryListener(plugin))
process.on('plugin.before.enable', this.registryListener.bind(this))
process.on('plugin.after.disable', this.unregistryListener.bind(this))
}
mapEventName() {
return this.EventManager.mapEventName().toFixed(0)
}
private registryListener(pluginInstance: plugin.Plugin) {
let events = getPluginListenerMetadata(pluginInstance)
for (const event of events) {
// ignore space listener
if (!this.ServerChecker.check(event.servers)) { continue }
if (!this.ServerChecker.check(event.servers)) {
console.debug(`[${pluginInstance.description.name}] ${event.target.constructor.name} incompatible event ${event.name} server(${event.servers}) ignore.`)
continue
}
// here must bind this to pluginInstance
this.EventManager.listen(pluginInstance, event.name, pluginInstance[event.executor].bind(pluginInstance), event.priority, event.ignoreCancel)
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)
}
}

View File

@@ -6,6 +6,8 @@ export * from './manager'
export * from './decorators'
export * from './interfaces'
export { PluginConfig } from './config'
export {
plugin as JSPlugin,
cmd as Cmd,

View File

@@ -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[]
/**
* 命令描述
*/
@@ -67,6 +75,13 @@ export namespace interfaces {
* 是否为只读(关闭时将不会自动保存)
*/
readonly?: boolean
/**
* 配置文件名称
*/
filename?: string
/**
* 配置文件全路径
*/
file?: any
}
export type PluginLike = Plugin | string
}

View File

@@ -1,9 +1,11 @@
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>
@@ -22,8 +24,4 @@ export class BasicLoader implements plugin.PluginLoader {
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 { }
}

View File

@@ -1,16 +1,18 @@
import { plugin, server } from "@ccms/api"
import { inject, ContainerInstance, Container, provideSingleton } from "@ccms/container"
import { inject, ContainerInstance, Container, provideSingletonNamed, Autowired } 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
@Autowired()
private serverChecker: server.ServerChecker
private pluginMetadataMap: Map<string, plugin.PluginMetadata>
@@ -28,7 +30,6 @@ export class IocLoader implements plugin.PluginLoader {
}
build(metadata: plugin.PluginMetadata) {
if (!this.allowProcess(metadata.servers)) { return }
let pluginInstance: plugin.Plugin
try {
this.bindPlugin(metadata)
@@ -68,28 +69,15 @@ export class IocLoader implements plugin.PluginLoader {
console.i18n('ms.plugin.manager.build.duplicate', { exists: pluginInstance.description.source, source: metadata.source })
}
this.container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
} catch{
} catch {
this.container.bind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
}
}
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)

View File

@@ -1,11 +1,13 @@
import i18n from '@ccms/i18n'
import { plugin, server, event } from '@ccms/api'
import { inject, provideSingleton, Container, ContainerInstance } from '@ccms/container'
import { inject, provideSingleton, Container, ContainerInstance, Autowired } from '@ccms/container'
import './config'
import { interfaces } from './interfaces'
import { PluginCommandManager } from './command'
import { PluginTaskManager } from './task'
import { PluginEventManager } from './event'
import { PluginCommandManager } from './command'
import { PluginConfigManager } from './config'
const Thread = Java.type('java.lang.Thread')
@@ -17,13 +19,18 @@ export class PluginManagerImpl implements plugin.PluginManager {
private pluginInstance: any
@inject(server.ServerType)
private serverType: string
@inject(event.Event)
private EventManager: event.Event
@inject(PluginCommandManager)
private commandManager: PluginCommandManager
@inject(PluginEventManager)
@Autowired()
private serverChecker: server.ServerChecker
@Autowired()
private taskManager: PluginTaskManager
@Autowired()
private eventManager: PluginEventManager
@Autowired()
private configManager: PluginConfigManager
@Autowired()
private commandManager: PluginCommandManager
private initialized: boolean = false
@@ -41,15 +48,17 @@ export class PluginManagerImpl implements plugin.PluginManager {
this.metadataMap = new Map()
// ignore unused
this.commandManager
this.taskManager
this.eventManager
this.configManager
this.commandManager
}
initialize() {
if (this.pluginInstance === undefined) { throw new Error("Can't found Plugin Instance!") }
if (this.initialized !== true) {
console.i18n('ms.plugin.initialize', { plugin: this.pluginInstance, loader: Thread.currentThread().contextClassLoader })
console.i18n('ms.plugin.event.map', { count: this.EventManager.mapEventName().toFixed(0), type: this.serverType })
console.i18n('ms.plugin.event.map', { count: this.eventManager.mapEventName(), type: this.serverType })
let pluginScanner = this.container.getAll<plugin.PluginScanner>(plugin.PluginScanner)
pluginScanner.forEach((scanner) => {
console.debug(`loading plugin sacnner ${scanner.type}...`)
@@ -74,7 +83,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
try {
this.loadPlugin(scanner.load(loadMetadata))
} catch (error) {
console.error(`plugin scanner ${scanner.type} load ${loadMetadata.name} occurred error ${error}`)
console.error(`plugin scanner ${scanner.type} load ${loadMetadata.file} occurred error ${error}`)
console.ex(error)
}
})
@@ -102,7 +111,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
process.emit(`plugin.before.${stage}`, plugin)
this.runCatch(plugin, stage)
this.runCatch(plugin, `${this.serverType}${stage}`)
plugin.description.loadMetadata.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 })
@@ -112,7 +121,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
private loadPlugin(loadMetadata: plugin.PluginLoadMetadata) {
if (!loadMetadata) { throw new Error('loadMetadata can\'t be undefiend when loadPlugin!') }
if (loadMetadata.loaded) { throw new Error(`Plugin ${loadMetadata.name} is already loaded by ${loadMetadata.loader?.type}!`) }
if (loadMetadata.loaded) { throw new Error(`Plugin file ${loadMetadata.file} is already loaded by ${loadMetadata.loader?.type}!`) }
try {
for (const [, loader] of this.loaderMap) {
if (this.loaderRequirePlugin(loadMetadata, loader)?.loaded) return loadMetadata.metadata
@@ -129,7 +138,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
if (loader.require(loadMetadata).loaded) {
loadMetadata.loader = loader
let metadata = loadMetadata.metadata
if (this.metadataMap.has(metadata.name)) {
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}...`)
}
@@ -215,16 +224,17 @@ export class PluginManagerImpl implements plugin.PluginManager {
try {
this.buildPlugin(metadata)
} catch (error) {
console.error(error)
console.console(error)
}
})
}
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失败!`) }
if (this.instanceMap.has(metadata.name)) { throw new Error(`Plugin ${metadata.name} is already load from ${metadata.source}...`) }
this.instanceMap.set(metadata.name, pluginInstance)
return pluginInstance
}

View File

@@ -2,9 +2,11 @@ import { plugin } from "@ccms/api"
import * as fs from '@ccms/common/dist/fs'
import { provideSingletonNamed } from "@ccms/container"
@provideSingletonNamed(plugin.PluginScanner, 'file')
const SCANNER_TYPE_NAME = 'file'
@provideSingletonNamed(plugin.PluginScanner, SCANNER_TYPE_NAME)
export class JSFileScanner implements plugin.PluginScanner {
type: string = 'file'
type: string = SCANNER_TYPE_NAME
scan(target: any): plugin.PluginLoadMetadata[] {
return this.scanFolder(fs.concat(root, target)).map((file) => this.read(file))

View File

@@ -0,0 +1,16 @@
import { plugin, task } from '@ccms/api'
import { provideSingleton, Autowired } from '@ccms/container'
@provideSingleton(PluginTaskManager)
export class PluginTaskManager {
@Autowired()
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)
}
}

View File

@@ -14,7 +14,7 @@ function getPlugin(name: string) {
function getPluginSources() {
let pluginSources: Map<string, plugin.PluginMetadata> = Reflect.getMetadata(
METADATA_KEY.souece,
METADATA_KEY.source,
Reflect
) || pluginSourceCache
return pluginSources
@@ -37,10 +37,10 @@ function getPluginMetadata(target: any) {
}
function getPluginCommandMetadata(target: any) {
let commandMetadata: Map<string, interfaces.CommandMetadata> = Reflect.getMetadata(
let commandMetadata: interfaces.CommandMetadata[] = Reflect.getMetadata(
METADATA_KEY.cmd,
target.constructor
) || new Map<string, interfaces.CommandMetadata>()
) || []
return commandMetadata
}

View File

@@ -0,0 +1,129 @@
# MiaoReward
## 插件简介
- 还在为服务器收入不足而倒闭烦恼嘛
- 还在为肝帝不氪金而烦恼嘛
- 快来接入 喵式奖励
- 通过QQ小程序广告 增加服务器收入
## 插件展示
- 插件帮助![image.png](https://i.loli.net/2020/09/12/uNbwO2sCVriZzJx.png)
- 扫码绑定![image.png](https://i.loli.net/2020/09/13/hOtyV8bP9kGeuCD.png)
- 查看个人信息![image.png](https://i.loli.net/2020/09/12/bTLGjQC7eqxAUSi.png)
- 兑换排行![image.png](https://i.loli.net/2020/09/12/zNbgKQChtj7IikD.png)
- 玩家兑换公告![image.png](https://i.loli.net/2020/09/12/JWFoUtwXBSP6fcA.png)
- 配置兑换比例![image.png](https://i.loli.net/2020/09/12/HpGVWErwZ7YTBxK.png)
- 服务器信息查询![image.png](https://i.loli.net/2020/09/12/CbvSDfg4BF39PLI.png)
- 玩家请求授权![image.png](https://i.loli.net/2020/09/24/QH6Dfp8RYJC5BtL.png)
- 玩家扫码![image.png](https://i.loli.net/2020/09/24/LSuhamJ4ji12EzM.png)
- 玩家扫码确认![image.png](https://i.loli.net/2020/09/24/sKjAl3tImg7buHe.png)
- 玩家扫码兑换完成![image.png](https://i.loli.net/2020/09/24/JG2SBtgHLzNeaEO.png)
- 腐竹扫码确认![image.png](https://i.loli.net/2020/09/24/c7sS18KJvQ3MRuZ.png)
- 腐竹扫码完成![image.png](https://i.loli.net/2020/09/24/RtsoSdV7j6OmE8Q.png)
## 插件命令
```
>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搜索小程序 `圈云盒子` 并登录
- 申请内测服务器账号
- 个人中心 => 配置面板 => 圈云盒子客服群
- 打开群详情 加群
### 接下来就是赚钱的操作
### 服务器准备工作
- 打开 [圈云盒子管理后台](https://reward.yumc.pw)
- 先安装 `MiaoScript` [站内地址](https://www.mcbbs.net/thread-774401-1-1.html)
- 可以通过 Yum 快速安装 `/yum install MiaoScript`
- 等待 MiaoScript 引擎启动完成(首次启动可能需要10-20秒 依赖于您的网络环境)
- 执行 `/mspm install MiaoReward`
### 绑定服务器
- 由于当前框架存在BUG 请先执行 `/mspm reload MiaoReward` 生成配置文件
- 执行 `/mrd bind server`
- 使用QQ扫码
- 选择需要绑定的服务器
- 完成绑定
- 配置服务器兑换比例
- 执行 `/mrd ratio 0.001` (最低为 1:0.0001)
- 执行兑换比例确认指令
- 执行 `/mrd server` 查看服务器信息
- 如果群组服需要绑定多台服务器(前提是每个服务器都有玩家在)
- 执行 `/gmspm install MiaoReward` 批量安装
- 可以直接复制绑定之后的 `MiaoScript/plugins/MiaoReward/config.yml`
- 黏贴配置文件到所有需要绑定的服务器上
- 然后 `/gmspm reload MiaoReward` 批量重载插件
### QQ群配置
- 打开小程序
- 登录
- 个人中心 => 设置面板 => 添加到群应用 => 选择你的QQ群
- 配置群快捷栏 个人中心 => 设置面板 => 查看设置群快捷栏
- 配置结果![image.png](https://i.loli.net/2020/09/24/C5ReMOo29mFbVAl.png)
### 玩家绑定账号
- 执行 `/mrd bind`
- 使用QQ扫码
- 完成绑定
- 执行 `/mrd query` 查询信息
## 使用说明
- 玩家可以通过下列方式获取喵币
- 签到 5-10 喵币
- 视频广告 5-15 喵币
- 盒子广告 5-15 喵币
- 获得的喵币可以在服务器兑换成对应的奖励
- 腐竹可以在平台将喵币兑换成RMB(兑换比例请加群联系客服详谈)
- 登录小程序后 个人中心 => 配置面板 => 圈云盒子客服群
## PAPI兼容
- 目前已经兼容 PAPI 变量
- `%mrd_balance%` 玩家喵币
- `%mrd_sign%` 玩家签到(*/1)
- `%mrd_video%` 玩家视频观看次数(*/300)
- `%mrd_box%` 玩家盒子观看次数(*/300)
- 如果玩家变量没有及时更新 执行 `/mrd query``重新登录游戏` 即可
## 配置文件
```yml
# 服务器ID
serverId: 16
# 服务器Token
serverToken: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
# 兑换指令
drawCommand: 'p give %player_name% %amount%'
# 冷却时间
drawCooldown: 300
# 提示前缀
prefix: '§6[§b广告系统§6]§r'
```
## 插件源码
- [MiaoScript包管理中心](http://ms.yumc.pw/api/plugin/download/name/MiaoReward)
## Roadmap
- 绑定服务器(已完成)
- 绑定玩家(已完成)
- 兑换喵币(已完成)
- 自助开通服务器(开发中)
- 自助兑换RMB(开发中)
- 自助提现(开发中)

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@ccms/plugins",
"version": "0.9.1",
"version": "0.9.9",
"description": "MiaoScript plugins package",
"keywords": [
"miaoscript",
@@ -20,16 +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",
"@javatypes/spring-data-redis": "^0.0.3",
"@javatypes/spring-web": "^0.0.3",
"@javatypes/tomcat": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/container": "^0.9.0",
"@ccms/plugin": "^0.9.1"
"@ccms/api": "^0.9.9",
"@ccms/container": "^0.9.9",
"@ccms/plugin": "^0.9.9"
}
}

View File

@@ -2,16 +2,16 @@
/// <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, channel, constants, chat } from '@ccms/api'
import { optional, Autowired } 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,42 +22,45 @@ 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()
}
}
@plugin({ name: 'MiaoChat', version: '1.0.0', author: 'MiaoWoo', source: __filename })
export class MiaoChat extends interfaces.Plugin {
@inject(server.Server)
@Autowired()
private Server: server.Server
@inject(channel.Channel)
@optional() private Channel: channel.Channel
@optional()
@Autowired()
private chat: chat.Chat
@Autowired()
private Channel: channel.Channel
private channelOff: { off: () => void };
private channelOff: { off: () => void }
@config()
private config = {
@@ -129,34 +132,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 +167,7 @@ export class MiaoChat extends interfaces.Plugin {
enable() {
this.PlaceholderAPI = {
setPlaceholders: (player: any, string: string) => {
return string;
return string
}
}
}
@@ -174,10 +177,14 @@ export class MiaoChat extends interfaces.Plugin {
}
bukkitenable() {
if (!this.chat) {
this.logger.console('§4消息管理器注入失败 请检查当前服务器是否兼容...')
this.AsyncPlayerChatEvent['off']()
}
// 尝试加载 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)
@@ -185,16 +192,20 @@ export class MiaoChat extends interfaces.Plugin {
}
spongeenable() {
if (!this.chat) {
this.logger.console('§4消息管理器注入失败 请检查当前服务器是否兼容...')
this.MessageChannelEvent$Chat['off']()
}
// 尝试加载 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 +224,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) {
@@ -225,15 +236,15 @@ export class MiaoChat extends interfaces.Plugin {
})
}
@cmd({ servers: ["bungee"] })
@cmd({ servers: [constants.ServerType.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"] })
@cmd({ servers: [`!${constants.ServerType.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 }))
}
@@ -241,104 +252,99 @@ export class MiaoChat extends interfaces.Plugin {
tabmchat(_sender: any, _command: string, _args: string[]) {
}
@listener({ servers: ['bukkit'] })
@listener({ servers: [constants.ServerType.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'] })
@listener({ servers: [constants.ServerType.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) {

View File

@@ -81,6 +81,7 @@ export class MiaoCoin extends interfaces.Plugin {
}
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()

View File

@@ -1,6 +1,6 @@
/// <reference types="@ccms/nashorn" />
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'
@@ -27,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)
@@ -248,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 {

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,6 @@
import { plugin as pluginApi, task, server, plugin, channel, constants } from '@ccms/api'
import { plugin as pluginApi, task, server, channel, constants, proxy } from '@ccms/api'
import { Translate } from '@ccms/i18n'
import { inject, DefaultContainer as container, optional, JSClass } from '@ccms/container'
import { DefaultContainer as container, JSClass, Autowired } from '@ccms/container'
import { interfaces, JSPlugin, Cmd, Tab, enable, Listener, disable } from '@ccms/plugin'
import * as fs from '@ccms/common/dist/fs'
@@ -10,41 +9,53 @@ import http from '@ccms/common/dist/http'
let help = [
'§6========= §6[§aMiaoScriptPackageManager§6] 帮助 §aBy §bMiaoWoo §6=========',
'§6/mpm §ainstall §e<插件名称> §6- §3安装仓库插件',
'§6/mpm §aload §e<插件名称> §6- §3安装本地插件',
'§6/mpm §aunload §e<插件名称> §6- §3卸载已安装插件',
'§6/mpm §areload §e<插件名称> §6- §3重载已安装插件(无名称则重载自身)',
'§6/mpm §alist [i] §6- §3列出仓库插件[已安装的插件]',
'§6/mpm §aupdate §e[插件名称] §6- §3更新插件(无名称则更新源)',
'§6/mpm §aupgrade §e[插件名称] §6- §3升级插件/框架(§4无名称则升级框架§3)',
'§6/mpm §arun §e<JS代码> §6- §3运行JS代码',
'§6/mpm §adeploy §e<插件名称> §6- §3发布插件',
'§6/mpm §crestart §6- §4重启MiaoScript脚本引擎'
'§6/mspm §ainstall §e<插件名称> §6- §3安装仓库插件',
'§6/mspm §aload §e<插件名称> §6- §3安装本地插件',
'§6/mspm §aunload §e<插件名称> §6- §3卸载已安装插件',
'§6/mspm §areload §e<插件名称> §6- §3重载已安装插件(无名称则重载自身)',
'§6/mspm §alist [i] §6- §3列出仓库插件[已安装的插件]',
'§6/mspm §aupdate §e[插件名称] §6- §3更新插件(无名称则更新源)',
'§6/mspm §aupgrade §e[插件名称] §6- §3升级插件/框架(§4无名称则升级框架§3)',
'§6/mspm §arun §e<JS代码> §6- §3运行JS代码',
'§6/mspm §adeploy §e<插件名称> §6- §3发布插件',
'§6/mspm §crestart §6- §4重启MiaoScript脚本引擎'
]
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}\n§6版本: §a{version}\n§6作者: §3{author}\n§6来源: §c{from}',
'list.install.body': `§6插件名称: §b{name}
§6├版本: §a{version}
§6├作者: §3{author}
§6└来源: §c{from}`,
'list.header': '§6当前 §bMiaoScriptPackageCenter §6中存在下列插件:',
'list.body': '§6插件名称: §b{name}\n§6版本: §a{version}\n§6作者: §3{author}\n§6更新时间: §9{updated_at}',
'list.body': `§6插件名称: §b{name}
§6├版本: §a{version}
§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插件!',
'cloud.update.exists': '§6插件 §b{name} §a发现新版本 §3{new_version} §6当前版本 §3{old_version}!',
'download.start': '§6开始下载插件: §b{name}',
'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.already': '§6插件 §b{name} §6版本 §3{version} §c已安装在服务器 §3更新请用 update 命令!',
'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}',
'prun.script': '§6指定插件:§b {name}',
'run.script': '§b运行脚本:§r {script}',
'run.result': '§a返回结果:§r {result}',
'run.noresult': '§4没有返回结果!',
@@ -52,32 +63,72 @@ let langMap = {
let fallbackMap = langMap
@JSPlugin({ prefix: 'PM', version: '1.2.0', author: 'MiaoWoo', source: __filename })
export class MiaoScriptPackageManager extends interfaces.Plugin {
@inject(plugin.PluginManager)
private pluginManager: pluginApi.PluginManager
@inject(task.TaskManager)
private taskManager: task.TaskManager
@inject(server.ServerType)
private serverType: string
@inject(server.Server)
private server: server.Server
@inject(pluginApi.PluginFolder)
private pluginFolder: string
@inject(channel.Channel)
@optional() private channel: channel.Channel
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,
hasPermission: () => true,
sendMessage: (message) => this.sendMessage(message)
})
this._proxy = new FakeSenderAdapter()
}
sendMessage(message) {
return this.plugin.sendBungeeCordMessage(this.name, `§6[§3BPM§6][§a${this.plugin.serverName}§6] ${message}`)
}
getHandler() {
return this._proxy
}
}
class BukkitFakeSender extends FakeSender {
constructor(name: string, plugin: MiaoScriptPackageManager) {
super(name, plugin, Java.type('org.bukkit.command.CommandSender'))
}
}
class SpongeFakeSender extends FakeSender {
constructor(name: string, plugin: MiaoScriptPackageManager) {
super(name, plugin, Java.type('org.spongepowered.api.command.CommandSource'))
}
sendMessage(message) {
return super.sendMessage(message.content)
}
}
@JSPlugin({ prefix: 'PM', version: '1.3.0', author: 'MiaoWoo', source: __filename })
export class MiaoScriptPackageManager extends interfaces.Plugin {
@Autowired()
private pluginManager: pluginApi.PluginManager
@Autowired()
private taskManager: task.TaskManager
@Autowired(server.ServerType)
private serverType: string
@Autowired()
private server: server.Server
@Autowired(pluginApi.PluginFolder)
private pluginFolder: string
@Autowired()
private channel: channel.Channel
@Autowired()
private bungee: proxy.BungeeCord
@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 serverName: string
private isBungeeCord = false
public serverName: string
private translate: Translate
private channelOff: { off: () => void }
@@ -96,6 +147,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
let subChannel = input.readUTF()
switch (subChannel) {
case "GetServer":
this.isBungeeCord = true
this.serverName = input.readUTF()
break
case "MiaoScriptPackageManager":
@@ -114,27 +166,30 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
private bungeeCordDetect(player) {
if (player) {
let byteArray = new this.ByteArrayOutputStream()
let out = new this.DataOutputStream(byteArray)
out.writeUTF("GetServer")
player.sendPluginMessage(base.getInstance(), "BungeeCord", byteArray.toByteArray())
this.bungee.for(player).getServer().send()
}
}
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))
player.sendPluginMessage(base.getInstance(), "BungeeCord", byteArray.toByteArray())
this.bungee.for(player).forward("ALL", "MiaoScriptPackageManager", command).send()
}
}
private readForward(input) {
let message = JSON.parse(input.readUTF())
this.taskManager.create(() => this.main(this.server.getConsoleSender(), message.command, message.args)).async().submit()
this.sendBungeeCordMessage(message.sender, `§6[§cMS§6][§bPM§6] [§3BPM§6][§a${this.serverName}§6] §6命令 §b/mpm ${message.args?.join?.(' ')} §a执行成功!`)
let fakeSender = this.getProxySender(message.sender)
this.taskManager.create(() => this.main(fakeSender, message.command, message.args)).async().submit()
this.logger.sender(fakeSender, `§6命令 §b/mspm ${message.args?.join?.(' ')} §a执行成功!`)
}
private getProxySender(name: string) {
switch (this.serverType) {
case constants.ServerType.Bukkit:
return new BukkitFakeSender(name, this).getHandler()
case constants.ServerType.Sponge:
return new SpongeFakeSender(name, this).getHandler()
default:
return this.server.getConsoleSender()
}
}
@Listener({ servers: [constants.ServerType.Bukkit] })
@@ -147,20 +202,16 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
@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())
}
}
private sendBungeeCordMessage(sender, message) {
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())
this.bungee.for(players[0]).message(sender, message).send()
}
}
@@ -168,16 +219,24 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
this.channelOff?.off()
}
@Cmd()
bmpm(sender: any, command: string, args: string[]) {
if (!sender.isOp()) { return this.logger.sender(sender, '§c你没有此命令的权限!') }
@Cmd({ servers: [`!${constants.ServerType.Bungee}`] })
gmspm(sender: any, command: string, args: string[]) {
if (!sender.hasPermission('mspm.admin')) { 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, `[§3BPM§6][§a${this.serverName}§6] §6命令 §b/mpm ${args.join?.(' ')} §a发布成功!`)
this.logger.sender(sender, `§6[§3BPM§6][§a${this.serverName}§6] §6命令 §b/mspm ${args.join?.(' ')} §a发布成功!`)
}
@Cmd()
mpm(sender: any, command: string, args: string[]) {
if (!sender.isOp()) { return this.logger.sender(sender, '§c你没有此命令的权限!') }
@Cmd({ servers: [constants.ServerType.Bungee] })
bungeemspm(sender: any, command: string, args: string[]) {
if (!sender.hasPermission('mspm.admin')) { return this.i18n(sender, 'main.command.no.permission') }
this.taskManager.create(() => this.main(sender, command, args)).async().submit()
}
@Cmd({ servers: [`!${constants.ServerType.Bungee}`] })
mspm(sender: any, command: string, args: string[]) {
if (!sender.hasPermission('mspm.admin')) { return this.i18n(sender, 'main.command.no.permission') }
this.taskManager.create(() => this.main(sender, command, args)).async().submit()
}
@@ -200,6 +259,24 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
this.logger.sender(sender, help)
}
cmdinfo(sender: any) {
this.logger.sender(sender, [
])
}
cmdsudo(sender: any, name: string, ...args: string[]) {
this.taskManager.create(() => {
let player = this.server.getPlayer(name)
if (!player) {
return this.logger.sender(sender, `§4玩家 ${player.getName()} 不在线或不存在!`)
}
let command = args.join(' ')
this.server.dispatchCommand(player, command)
this.logger.sender(sender, `§6玩家 §a${player.getName()} §6命令 §b${command} §a执行完成!`)
}).submit()
}
cmdload(sender: any, name: string) {
let pluginFile = fs.concat(__dirname + '', name)
if (!fs.exists(pluginFile)) {
@@ -225,7 +302,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)) {
this.i18n(sender, 'install.already', { name, version: this.pluginManager.getPlugins().get(name).description.version })
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) {
@@ -241,29 +325,46 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
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 })
}
}
@@ -300,14 +401,27 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
try {
let script = args.join(' ')
this.i18n(sender, 'run.script', { script })
let result = this.runCode(script, sender)
let result = this.runCode(script, sender, this)
this.i18n(sender, 'run.result', { result: result == undefined ? this.translate.translate('run.noresult') : result + '' })
} catch (ex) {
this.logger.sender(sender, this.logger.stack(ex))
}
}
private runCode(code: string, sender: any) {
cmdprun(sender: any, name: string, ...args: any[]) {
try {
if (!this.pluginManager.getPlugins().has(name)) { return this.logger.sender(sender, `§4插件 §c${name} §4不存在!`) }
let script = args.join(' ')
this.i18n(sender, 'prun.script', { name })
this.i18n(sender, 'run.script', { script })
let result = this.runCode(script, sender, this.pluginManager.getPlugins().get(name))
this.i18n(sender, 'run.result', { result: result == undefined ? this.translate.translate('run.noresult') : typeof result == "string" ? result : JSON.stringify(result) })
} catch (ex) {
this.logger.sender(sender, this.logger.stack(ex))
}
}
private runCode(code: string, sender: any, _this: any) {
let paramNames = [
'sender',
'reflect',
@@ -328,8 +442,8 @@ if (this.serverType == "spring") {
var db = dbm.getMainDatabase()
var df = base.getInstance().getAutowireCapableBeanFactory()
}
return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
return tfunc.apply(this, params) + ''
return eval(${JSON.stringify(code)});`)
return tfunc.apply(_this, params)
}
cmddeploy(sender: any, name: any) {
@@ -343,20 +457,23 @@ return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
version: plugin.description.version,
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 })
this.i18n(sender, result.code == 200 ? 'deploy.success' : 'deploy.fail', { name, version: plugin.description.version, 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()
tabmpm(sender: any, command: any, args: string | any[]) {
if (args.length === 1) { return ['list', 'install', 'update', 'upgrade', 'reload', 'restart', 'run', 'help', 'create', 'deploy'] }
@Tab({ alias: ['gmspm', 'bungeemspm'] })
tabmspm(_sender: any, _command: any, args: string | any[]) {
if (args.length === 1) { return ['list', 'install', 'update', 'upgrade', 'reload', 'restart', 'run', 'prun', 'sudo', 'help', 'create', 'deploy'] }
if (args.length > 1) {
switch (args[0]) {
case "list":
@@ -367,6 +484,12 @@ return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
if (args.length == 2) return ["system", ...this.pluginManager.getPlugins().keys()]
if (args.length == 3 && args[1] == "system") return ["confirm"]
return []
case "prun":
if (args.length == 2) return [...this.pluginManager.getPlugins().keys()]
return []
case "sudo":
if (args.length == 2) return Java.from(this.server.getOnlinePlayers()).map(p => p.getName())
return []
case "update":
case "load":
case "unload":
@@ -393,19 +516,15 @@ return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
}).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.concat(root, this.pluginFolder, name + '.js'))
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()
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/sponge",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -19,14 +19,14 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@javatypes/sponge-api": "^0.0.2",
"@javatypes/sponge-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/common": "^0.9.0",
"@ccms/container": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/common": "^0.9.8",
"@ccms/container": "^0.9.9"
}
}

View 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)
}
}

View File

@@ -49,11 +49,11 @@ class SimpleCommandCallable {
this.callable = new CommandCallable({
//CommandResult process(CommandSource source, String arguments) throws CommandException
process: (sender: any, args) => {
return this.executor(sender, '', command, Java.to(args.split(" ").filter(e => e))) ? CommandResult.success() : CommandResult.empty()
return this.executor(sender, '', command, Java.to(args.split(" "))) ? CommandResult.success() : CommandResult.empty()
},
//List<String> getSuggestions(CommandSource source, String arguments, @Nullable Location<World> targetPosition) throws CommandException
getSuggestions: (sender: any, args, target) => {
return this.tabCompleter(sender, '', command, Java.to(args.split(" ").filter(e => e)))
return this.tabCompleter(sender, '', command, Java.to(args.split(" ")))
},
//boolean testPermission(CommandSource source)
testPermission: () => {

View File

@@ -3,13 +3,14 @@
import { server } from '@ccms/api'
import { Container } from '@ccms/container'
import { SpongeConsole } from './console';
import './event';
import './server';
import './command';
import './channel';
import './task';
import { SpongeConsole } from './console'
import './chat'
import './task'
import './event'
import './server'
import './command'
import './channel'
export default function SpongeImpl(container: Container) {
container.bind(server.Console).toConstantValue(SpongeConsole);
container.bind(server.Console).toConstantValue(SpongeConsole)
}

View File

@@ -35,10 +35,10 @@ export class SpongeServer extends server.ReflectServer {
if (typeof sender === 'string') {
sender = this.getPlayer(sender)
}
return Sponge.getCommandManager().process(sender, command).getQueryResult().get() != 0
return Sponge.getCommandManager().process(sender, command).getSuccessCount().get() != 0
}
dispatchConsoleCommand(command: string): boolean {
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getQueryResult().get() != 0
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getSuccessCount().get() != 0
}
getPluginsFolder(): string {
return this.pluginsFolder
@@ -55,10 +55,4 @@ export class SpongeServer extends server.ReflectServer {
getRootLogger() {
return this.rootLogger
}
sendJson(sender: string | any, json: string): void {
if (typeof sender === "string") {
sender = this.getPlayer(sender)
}
sender.sendMessage(TextSerializers.JSON.deserialize(json))
}
}

View File

@@ -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) }

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/spring",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript spring package",
"keywords": [
"miaoscript",
@@ -21,12 +21,12 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/common": "^0.9.0",
"@ccms/container": "^0.9.0",
"@ccms/database": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/common": "^0.9.8",
"@ccms/container": "^0.9.9",
"@ccms/database": "^0.9.9"
}
}

View File

@@ -13,6 +13,9 @@ export class SpringCommand extends command.Command {
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)
}

View File

@@ -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)
})
}

View File

@@ -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)
}
}

View File

@@ -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()
}
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/web",
"version": "0.9.0",
"version": "0.9.9",
"description": "MiaoScript web package",
"keywords": [
"miaoscript",
@@ -19,17 +19,17 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@javatypes/jdk": "^0.0.2",
"@javatypes/spring-beans": "^0.0.2",
"@javatypes/spring-core": "^0.0.2",
"@javatypes/spring-web": "^0.0.2",
"@javatypes/tomcat": "^0.0.2",
"@javatypes/jdk": "^0.0.3",
"@javatypes/spring-beans": "^0.0.3",
"@javatypes/spring-core": "^0.0.3",
"@javatypes/spring-web": "^0.0.3",
"@javatypes/tomcat": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
},
"dependencies": {
"@ccms/api": "^0.9.0",
"@ccms/container": "^0.9.0"
"@ccms/api": "^0.9.9",
"@ccms/container": "^0.9.9"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ccms/websocket",
"version": "0.9.0",
"version": "0.9.8",
"description": "MiaoScript websocket package",
"keywords": [
"miaoscript",
@@ -19,10 +19,10 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"devDependencies": {
"@ccms/nashorn": "^0.9.0",
"@javatypes/tomcat-websocket-api": "^0.0.2",
"@ccms/nashorn": "^0.9.8",
"@javatypes/tomcat-websocket-api": "^0.0.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.9.6"
"typescript": "^4.0.3"
}
}