Compare commits
248 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 393e63c017 | |||
| 46d6748f31 | |||
| b6803ed01c | |||
| bbfc70fdd6 | |||
| e28af3fbbc | |||
| 14eef46e67 | |||
| 1c4f512c89 | |||
| a8ae60625b | |||
| e7bc14294e | |||
| 4750f31b6e | |||
| 18df821049 | |||
| ef98c49e1d | |||
| 5f0c3bbdd4 | |||
| bf3638dda0 | |||
| 842335edbe | |||
| f573d0c758 | |||
| 13b04a904e | |||
| 2c1eea5bc1 | |||
| 8a07e85fda | |||
| 32db0bba56 | |||
| b417d8ff08 | |||
| 6fd7038ffe | |||
| 321b21a947 | |||
| 0ae7346678 | |||
| 7114876046 | |||
| 01fcc1337a | |||
| 476f7acc39 | |||
| 5b11be11da | |||
| 80c6b123c1 | |||
| a7a40b374b | |||
| 9888f908e9 | |||
| 73ada5fd17 | |||
| 79f151de5c | |||
| 16fcbfa69c | |||
| 7e1111470c | |||
| d407631072 | |||
| 4d7b27188a | |||
| 7bd8302b24 | |||
| b065bcd843 | |||
| c8a31b6d5a | |||
| 75492c77e8 | |||
| 8dbbb369b2 | |||
| 24ba6bd353 | |||
| a02bd6dc95 | |||
| 21cf867f43 | |||
| 4290d1132e | |||
| 1ed5dd1d24 | |||
| d751dc8614 | |||
| c45bbb9821 | |||
| c9ca4ffd39 | |||
| 5943d6882f | |||
| d24d0d39a1 | |||
| 95cd8c4889 | |||
| 78fcbbe9a5 | |||
| baa6e95222 | |||
| 3a045bd335 | |||
| dd28d9fae5 | |||
| 72bd6b4c9c | |||
| 58478116c6 | |||
| d29efb2332 | |||
| 0899276530 | |||
| 5c3ed4e36d | |||
| b926951656 | |||
| b47acf69ea | |||
| 63aef1fe60 | |||
| 541a3bb96b | |||
| 873964575b | |||
| 54af491399 | |||
| 43d9b97347 | |||
| 25aef3ed62 | |||
| c622abecda | |||
| f527c225fe | |||
| 26eceac330 | |||
| f5702c5080 | |||
| 101f152da7 | |||
| 97db272041 | |||
| a5ca0c2346 | |||
| aab94fe5ea | |||
| d3d7a9cdbf | |||
| 9dee4b3a60 | |||
| f1863c3b39 | |||
| 0120e84f3f | |||
| 00130f549c | |||
| fafcd09cc1 | |||
| 2bd8f0c5ff | |||
| 695a490296 | |||
| 1a546470a5 | |||
| e68c17576a | |||
| eaee2f9c91 | |||
| 3596fc0804 | |||
| 5e89872477 | |||
| c12670bd9e | |||
| b9ef3f2e33 | |||
| 4b3176e98e | |||
| 4922f6a39d | |||
| 195c84e1ae | |||
| 7d63a57991 | |||
| 1931391cba | |||
| 2dda9bd0fc | |||
| 937b24ecda | |||
| c9eff3dae4 | |||
| 098a4f8557 | |||
| 8566c6a883 | |||
| 0584ec9d85 | |||
| 87f197fe06 | |||
| 860946a44b | |||
| f40eddd5e3 | |||
| b67474f7ff | |||
| 8e5588ca23 | |||
| acbeda9659 | |||
| a4c549d446 | |||
| c311d3fdb1 | |||
| 1c29a059d9 | |||
| d22b72f10a | |||
| e74cfda86b | |||
| 24fe3b9026 | |||
| ee9ae408ec | |||
| d679915062 | |||
| eaa11ac89e | |||
| 5ddfb1c40f | |||
| da68821a1f | |||
| ec65d00f28 | |||
| a2c3eff622 | |||
| 8d2422fd64 | |||
| 9bc6cc1ff2 | |||
| 6fc3592536 | |||
| 49b96b3ac4 | |||
| 73b9c2f163 | |||
| f5a7a269e4 | |||
| 662e70b72c | |||
| b71ce1b24d | |||
| 1ea8966f26 | |||
| 0ed3f1fbd5 | |||
| f4b461409b | |||
| ace2c48ae2 | |||
| 39861b2c46 | |||
| 6c9ea9fb74 | |||
| 15f09abce0 | |||
| eb832a0830 | |||
| 1d35c836fc | |||
| e53f2cea76 | |||
| 1395865d8a | |||
| bae5355c1b | |||
| 41d2edc719 | |||
| d608e2c066 | |||
| e7c22b5961 | |||
| 18b46cdcc7 | |||
| d057fd5464 | |||
| 247c566219 | |||
| ed9fec281c | |||
| 15197355c5 | |||
| 988bb3b914 | |||
| 47048a5b1b | |||
| b3539d419e | |||
| c10247e241 | |||
| 553632e6ba | |||
| 6b7a729e65 | |||
| 488eecba07 | |||
| ce431aded4 | |||
| 525fde9f51 | |||
| ca11db68a6 | |||
| 3f475a7dc1 | |||
| e7d44af48c | |||
| 0b416adfd2 | |||
| 429cece606 | |||
| c34b744994 | |||
| 4d64a5d264 | |||
| 13c0584749 | |||
| f5f50d0dd6 | |||
| 0176cabd41 | |||
| a3f8451842 | |||
| 9ea4a067f1 | |||
| 3143851969 | |||
| 7e4c44eadd | |||
| e323467ed8 | |||
| eba21c08dc | |||
| a872172fff | |||
| c996fa6873 | |||
| 8616c3fe22 | |||
| 407de98468 | |||
| c13668dbe2 | |||
| a0b334b151 | |||
| d7e8b05573 | |||
| 9fd4b51d98 | |||
| 246867b999 | |||
| 381ea25b46 | |||
| 6d81a72106 | |||
| f20171f898 | |||
| eaf491f74d | |||
| 49f886c5ba | |||
| 3cf83023eb | |||
| 9f64f89222 | |||
| bdecc96fcf | |||
| f660b4a4f8 | |||
| e8d41e8a43 | |||
| d9e2b50953 | |||
| 93c83cac94 | |||
| b506d06173 | |||
| 8d81d6938e | |||
| d90264194c | |||
| cc96519e80 | |||
| 982e14953c | |||
| b0409c46ba | |||
| fb3eb9704f | |||
| effa43d42f | |||
| 06684939bc | |||
| 9eb052addb | |||
| 9acd824656 | |||
| 61195accc9 | |||
| 568f723c06 | |||
| bca12d6f02 | |||
| 9b3d76b6dd | |||
| 84d9eb8881 | |||
| 6b4d0cc64c | |||
| 1d783ebd1f | |||
| 87ac658a22 | |||
| b793ec192f | |||
| 606bbb3991 | |||
| cacde0627b | |||
| 6f5254497f | |||
| 2639fbd818 | |||
| 93997cd695 | |||
| 268f5d2837 | |||
| 5642a93974 | |||
| 85fe0cf87a | |||
| f4ea32862f | |||
| eaf1456771 | |||
| 9546881691 | |||
| 94ebbf3cba | |||
| 9e650aa203 | |||
| 7ce0705d41 | |||
| 106e429a3f | |||
| 05d12b347a | |||
| 7bf5f53afd | |||
| e4bb878648 | |||
| d724feaec0 | |||
| 9cb614bebd | |||
| 7d6269b2d3 | |||
| eae0ff2c1e | |||
| 093a3dda00 | |||
| 93ec202894 | |||
| a780467d87 | |||
| 0102b172f3 | |||
| 64111732fb | |||
| ffa62ee243 | |||
| bd9af562f2 | |||
| 59108bab27 | |||
| 6258ae83d0 |
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
@@ -10,6 +10,7 @@
|
||||
"stream": true
|
||||
},
|
||||
"publish": {
|
||||
"access": "public",
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,13 +12,14 @@
|
||||
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
|
||||
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
|
||||
"ug": "yarn upgrade-interactive --latest",
|
||||
"np": "lerna exec \"npm publish --registry https://registry.npmjs.org\" --scope=\"@ccms/!(client|plugins|types)\"",
|
||||
"lp": "lerna publish"
|
||||
"np": "lerna exec \"npm publish --access=public --registry https://registry.npmjs.org\" --scope=\"@ccms/!(client|plugins)\"",
|
||||
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
|
||||
"lp": "lerna publish --registry https://registry.npmjs.org"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"devDependencies": {
|
||||
"lerna": "^3.21.0"
|
||||
"lerna": "^3.22.1"
|
||||
}
|
||||
}
|
||||
|
||||
1
packages/amqp/.npmignore
Symbolic link
1
packages/amqp/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
35
packages/amqp/package.json
Normal file
35
packages/amqp/package.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@ccms/amqp",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript amqp package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/common": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.8.2",
|
||||
"@javatypes/amqp-client": "^0.0.2",
|
||||
"@javatypes/spring-amqp": "^0.0.2",
|
||||
"@javatypes/spring-rabbit": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.5"
|
||||
}
|
||||
}
|
||||
17
packages/amqp/src/adapter/admin.ts
Normal file
17
packages/amqp/src/adapter/admin.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { RabbitTemplateAdapter } from "./template"
|
||||
import { JSClass } from "@ccms/container"
|
||||
|
||||
export const RabbitAdmin = Java.type('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
|
||||
export class RabbitAdminAdapter {
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
constructor(config: RabbitTemplateAdapter | org.springframework.amqp.rabbit.core.RabbitTemplate | ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory) {
|
||||
this._Handler = new RabbitAdmin((config instanceof RabbitTemplateAdapter || config instanceof ConnectionFactoryAdapter) ? config.getHandler() : config)
|
||||
}
|
||||
getHandler(): org.springframework.amqp.rabbit.core.RabbitAdmin {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
30
packages/amqp/src/adapter/callback.ts
Normal file
30
packages/amqp/src/adapter/callback.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
export const ConfirmCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback')
|
||||
export const ReturnCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback')
|
||||
|
||||
export abstract class ConfirmCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback
|
||||
constructor() {
|
||||
let ConfirmCallbackImpl = Java.extend(ReturnCallback, {
|
||||
confirm: (correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string) => this.confirm(correlationData, ack, cause)
|
||||
})
|
||||
this._Handler = new ConfirmCallbackImpl()
|
||||
}
|
||||
abstract confirm(correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class ReturnCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback
|
||||
constructor() {
|
||||
let ReturnCallbackImpl = Java.extend(ReturnCallback, {
|
||||
returnedMessage: (message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string) => this.returnedMessage(message, replyCode, replyText, exchange, routingKey)
|
||||
})
|
||||
this._Handler = new ReturnCallbackImpl()
|
||||
}
|
||||
abstract returnedMessage(message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
31
packages/amqp/src/adapter/connection.ts
Normal file
31
packages/amqp/src/adapter/connection.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import threadPool from '@ccms/common/dist/thread-pool'
|
||||
|
||||
export const ConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.ConnectionFactory')
|
||||
const CachingConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.CachingConnectionFactory')
|
||||
interface ConnectionConfig {
|
||||
url: string,
|
||||
username?: string,
|
||||
password?: string,
|
||||
publisherConfirms?: boolean
|
||||
cacheSize?: number
|
||||
}
|
||||
|
||||
export class ConnectionFactoryAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.connection.CachingConnectionFactory
|
||||
|
||||
constructor(config: ConnectionConfig) {
|
||||
if (!config.url) { throw new Error('Connection UrI Can\'t be undefiend!') }
|
||||
config = { publisherConfirms: true, cacheSize: 50, ...config }
|
||||
this._Handler = new CachingConnectionFactory(new java.net.URI(config.url))
|
||||
config.username && this._Handler.setUsername(config.username)
|
||||
config.password && this._Handler.setPassword(config.password)
|
||||
this._Handler.setPublisherConfirms(config.publisherConfirms)
|
||||
this._Handler.setExecutor(threadPool.create({
|
||||
groupName: '@ccms/amqp-rabbit'
|
||||
}))
|
||||
this._Handler.setChannelCacheSize(config.cacheSize)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
30
packages/amqp/src/adapter/container.ts
Normal file
30
packages/amqp/src/adapter/container.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { ConnectionFactoryAdapter, ConnectionFactory } from "./connection"
|
||||
import { ChannelAwareMessageListenerAdapter, ChannelAwareMessageListener } from "./listener"
|
||||
|
||||
export const SimpleMessageListenerContainer = org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
export const AcknowledgeMode: org.springframework.amqp.core.AcknowledgeMode = Java.type('org.springframework.amqp.core.AcknowledgeMode')
|
||||
interface ContainerConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | typeof ConnectionFactory
|
||||
queueNames: string[]
|
||||
messageListener: ChannelAwareMessageListenerAdapter | typeof ChannelAwareMessageListener
|
||||
maxConcurrentConsumers?: number
|
||||
concurrentConsumers?: number
|
||||
acknowledgeMode?: org.springframework.amqp.core.AcknowledgeMode
|
||||
}
|
||||
|
||||
export class MessageListenerContainerAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
constructor(config: ContainerConfig) {
|
||||
config = { concurrentConsumers: 5, maxConcurrentConsumers: 10, acknowledgeMode: AcknowledgeMode.AUTO, ...config }
|
||||
this._Handler = new SimpleMessageListenerContainer(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
//@ts-ignore
|
||||
this._Handler.setQueueNames(config.queueNames)
|
||||
this._Handler.setMaxConcurrentConsumers(config.maxConcurrentConsumers)
|
||||
this._Handler.setConcurrentConsumers(config.concurrentConsumers)
|
||||
this._Handler.setAcknowledgeMode(config.acknowledgeMode)
|
||||
this._Handler.setMessageListener(config.messageListener instanceof ChannelAwareMessageListenerAdapter ? config.messageListener.getHandler() : config.messageListener)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
37
packages/amqp/src/adapter/converter.ts
Normal file
37
packages/amqp/src/adapter/converter.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
const Message = org.springframework.amqp.core.Message
|
||||
|
||||
export const MessageConverter = Java.type('org.springframework.amqp.support.converter.MessageConverter')
|
||||
|
||||
export class MessageConverterAdapter {
|
||||
private _Handler: org.springframework.amqp.support.converter.MessageConverter
|
||||
constructor() {
|
||||
var MessageConverterImpl = Java.extend(MessageConverter, {
|
||||
toMessage: (object: any, messageProperties: org.springframework.amqp.core.MessageProperties) => this.toMessage(object, messageProperties),
|
||||
fromMessage: (message: org.springframework.amqp.core.Message) => this.fromMessage(message)
|
||||
})
|
||||
this._Handler = new MessageConverterImpl()
|
||||
}
|
||||
toMessage(object: any, messageProperties: org.springframework.amqp.core.MessageProperties) {
|
||||
if (typeof object == "string") {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
|
||||
return new Message(new JavaString(object).getBytes(), messageProperties)
|
||||
} else {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
return new Message(new JavaString(JSON.stringify(object)).getBytes(), messageProperties)
|
||||
}
|
||||
}
|
||||
fromMessage(message: org.springframework.amqp.core.Message) {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_TEXT_PLAIN) {
|
||||
return new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding())
|
||||
}
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
return JSON.parse(new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding()))
|
||||
}
|
||||
return message
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
7
packages/amqp/src/adapter/index.ts
Normal file
7
packages/amqp/src/adapter/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export * from './admin'
|
||||
export * from './callback'
|
||||
export * from './connection'
|
||||
export * from './container'
|
||||
export * from './converter'
|
||||
export * from './listener'
|
||||
export * from './template'
|
||||
49
packages/amqp/src/adapter/listener.ts
Normal file
49
packages/amqp/src/adapter/listener.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
export const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
export const ChannelAwareMessageListener = Java.type('org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener')
|
||||
export const AmqpRejectAndDontRequeueException = org.springframework.amqp.AmqpRejectAndDontRequeueException
|
||||
export const Channel: com.rabbitmq.client.Channel = Java.type('com.rabbitmq.client.Channel')
|
||||
export const Message = org.springframework.amqp.core.Message
|
||||
export type MessageHandler<T> = (content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => any
|
||||
export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener
|
||||
constructor(manual: boolean = false) {
|
||||
let ChannelAwareMessageListenerImpl = Java.extend(ChannelAwareMessageListener, {
|
||||
onMessage: (message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => {
|
||||
let content = new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding() || "UTF-8")
|
||||
try {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
content = JSON.parse(content)
|
||||
}
|
||||
} catch (error) {
|
||||
if (manual) {
|
||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
|
||||
} else {
|
||||
throw new AmqpRejectAndDontRequeueException(`${error}`, error)
|
||||
}
|
||||
}
|
||||
manual ? this.manualOnMessage(content, message, channel) : this.onMessage(content, message, channel)
|
||||
}
|
||||
})
|
||||
this._Handler = new ChannelAwareMessageListenerImpl()
|
||||
}
|
||||
abstract onMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any
|
||||
onError(error: Error, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any { }
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
private manualOnMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
let deliveryTag = message.getMessageProperties().getDeliveryTag()
|
||||
try {
|
||||
if (this.onMessage(content, message, channel)) {
|
||||
channel.basicAck(deliveryTag, false)
|
||||
} else if (message.getMessageProperties().getRedelivered()) {
|
||||
channel.basicReject(deliveryTag, true)
|
||||
} else {
|
||||
channel.basicNack(deliveryTag, false, true)
|
||||
}
|
||||
} catch (error) {
|
||||
channel.basicReject(deliveryTag, this.onError(error, message, channel))
|
||||
}
|
||||
}
|
||||
}
|
||||
27
packages/amqp/src/adapter/template.ts
Normal file
27
packages/amqp/src/adapter/template.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { MessageConverterAdapter } from "./converter"
|
||||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { ConfirmCallbackAdapter, ReturnCallbackAdapter } from "./callback"
|
||||
|
||||
export const RabbitTemplate = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate')
|
||||
|
||||
interface TemplateConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory
|
||||
confirmCallback?: ConfirmCallbackAdapter
|
||||
returnCallback?: ReturnCallbackAdapter
|
||||
messageConverter?: MessageConverterAdapter
|
||||
}
|
||||
export class RabbitTemplateAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate
|
||||
constructor(config: TemplateConfig) {
|
||||
config = { messageConverter: new MessageConverterAdapter(), ...config }
|
||||
console.debug(JSON.stringify(config))
|
||||
this._Handler = new RabbitTemplate(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
config.returnCallback && this._Handler.setReturnCallback(config.returnCallback.getHandler())
|
||||
config.confirmCallback && this._Handler.setConfirmCallback(config.confirmCallback.getHandler())
|
||||
config.messageConverter && this._Handler.setMessageConverter(config.messageConverter.getHandler())
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
89
packages/amqp/src/admin.ts
Normal file
89
packages/amqp/src/admin.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { JSClass } from "@ccms/container"
|
||||
import { RabbitAdminAdapter, MessageListenerContainerAdapter, AcknowledgeMode, MessageHandler, ChannelAwareMessageListenerAdapter } from "./adapter"
|
||||
|
||||
export class AmqpAdmin {
|
||||
@JSClass('org.springframework.amqp.core.TopicExchange')
|
||||
private TopicExchange: typeof org.springframework.amqp.core.TopicExchange
|
||||
@JSClass('org.springframework.amqp.core.Queue')
|
||||
private Queue: typeof org.springframework.amqp.core.Queue
|
||||
@JSClass('org.springframework.amqp.core.Binding')
|
||||
private Binding: typeof org.springframework.amqp.core.Binding
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: typeof org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
@JSClass('org.springframework.amqp.core.Binding.DestinationType')
|
||||
private DestinationType: org.springframework.amqp.core.Binding.DestinationType
|
||||
|
||||
private amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
|
||||
constructor(amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin | any) {
|
||||
if (amqpAdmin instanceof this.RabbitAdmin) {
|
||||
this.amqpAdmin = amqpAdmin
|
||||
} else if (amqpAdmin instanceof RabbitAdminAdapter) {
|
||||
this.amqpAdmin = amqpAdmin.getHandler()
|
||||
} else {
|
||||
this.amqpAdmin = new RabbitAdminAdapter(amqpAdmin).getHandler()
|
||||
}
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this.amqpAdmin
|
||||
}
|
||||
|
||||
getQueueProperties(name: string) {
|
||||
return this.amqpAdmin.getQueueProperties(name)
|
||||
}
|
||||
|
||||
declareExchange(name: string) {
|
||||
let exchange = new this.TopicExchange(name, true, false)
|
||||
this.amqpAdmin.declareExchange(exchange)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueue(name: string) {
|
||||
let queue = new this.Queue(name, true)
|
||||
this.amqpAdmin.declareQueue(queue)
|
||||
return this
|
||||
}
|
||||
|
||||
declareBinding(queue: string, exchange: string, routerKey: string, argument: any = null) {
|
||||
let binding = new this.Binding(queue, this.DestinationType.QUEUE, exchange, routerKey, argument)
|
||||
this.amqpAdmin.declareBinding(binding)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueueAndBindExchange(queue: string, exchange: string, routerKey: string) {
|
||||
return this.declareQueue(queue).declareExchange(exchange).declareBinding(queue, exchange, routerKey)
|
||||
}
|
||||
|
||||
createContainer<T>(queue: string, listener: MessageHandler<T>, acknowledgeMode = AcknowledgeMode.AUTO) {
|
||||
let connection = this.amqpAdmin.getRabbitTemplate().getConnectionFactory()
|
||||
return new MessageListenerContainerAdapter({
|
||||
connectionFactory: connection,
|
||||
queueNames: [queue],
|
||||
messageListener: new SimpleMessageHandler(listener),
|
||||
acknowledgeMode: acknowledgeMode
|
||||
}).getHandler()
|
||||
}
|
||||
|
||||
send()
|
||||
send() {
|
||||
|
||||
}
|
||||
|
||||
getTemplate() {
|
||||
return this.amqpAdmin.getRabbitTemplate()
|
||||
}
|
||||
|
||||
close() {
|
||||
this.getTemplate().stop()
|
||||
}
|
||||
}
|
||||
|
||||
export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
|
||||
constructor(private handler: MessageHandler<any>) {
|
||||
super()
|
||||
}
|
||||
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
return this.handler(content, message, channel)
|
||||
}
|
||||
}
|
||||
3
packages/amqp/src/constants.ts
Normal file
3
packages/amqp/src/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const METADATA_KEY = {
|
||||
|
||||
}
|
||||
34
packages/amqp/src/index.ts
Normal file
34
packages/amqp/src/index.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/spring-amqp" />
|
||||
/// <reference types="@javatypes/spring-rabbit" />
|
||||
/// <reference types="@javatypes/amqp-client" />
|
||||
|
||||
import { amqp } from '@ccms/api'
|
||||
import { getContainer, reduceMetadata } from '@ccms/container'
|
||||
|
||||
function init() {
|
||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
getContainer().bind(amqp.rabbit.Template).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitTemplate')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitTemplate`)
|
||||
}
|
||||
})
|
||||
getContainer().bind(amqp.rabbit.Admin).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitAdmin')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitAdmin`)
|
||||
}
|
||||
})
|
||||
}
|
||||
init()
|
||||
|
||||
export * from './admin'
|
||||
export * from './adapter'
|
||||
export * from './manager'
|
||||
export * from './constants'
|
||||
5
packages/amqp/src/listener.ts
Normal file
5
packages/amqp/src/listener.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export class AmqpListener {
|
||||
constructor() {
|
||||
|
||||
}
|
||||
}
|
||||
18
packages/amqp/src/manager.ts
Normal file
18
packages/amqp/src/manager.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { amqp } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
|
||||
import { ConnectionFactoryAdapter, RabbitTemplateAdapter, RabbitAdminAdapter } from "./adapter"
|
||||
import { AmqpAdmin } from "./admin"
|
||||
|
||||
@provideSingleton(amqp.Manager)
|
||||
export class AmqpManager {
|
||||
createConnection(url: string, username: string, password: string) {
|
||||
return new ConnectionFactoryAdapter({ url, username, password })
|
||||
}
|
||||
createTemplate(adapter: ConnectionFactoryAdapter) {
|
||||
return new RabbitTemplateAdapter({ connectionFactory: adapter })
|
||||
}
|
||||
createAdmin(adapter: RabbitTemplateAdapter | ConnectionFactoryAdapter) {
|
||||
return new AmqpAdmin(new RabbitAdminAdapter(adapter))
|
||||
}
|
||||
}
|
||||
7
packages/amqp/tsconfig.json
Normal file
7
packages/amqp/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/api",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,15 +19,16 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/container": "^0.7.0",
|
||||
"@ccms/ployfill": "^0.7.0",
|
||||
"@ccms/common": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2",
|
||||
"@ccms/ployfill": "^0.8.2",
|
||||
"base64-js": "^1.3.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/base64-js": "^1.2.5",
|
||||
"@types/base64-js": "^1.3.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import i18n from '@ccms/i18n'
|
||||
import { injectable } from "@ccms/container";
|
||||
import { injectable } from "@ccms/container"
|
||||
import { plugin } from './interfaces'
|
||||
|
||||
export namespace command {
|
||||
@injectable()
|
||||
@@ -10,16 +11,17 @@ export namespace command {
|
||||
* @param name 命令
|
||||
* @param exec 执行器
|
||||
*/
|
||||
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||
var cmd = this.create(plugin, name);
|
||||
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||
var cmd = this.create(plugin, name)
|
||||
if (!cmd) { throw Error("") }
|
||||
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);
|
||||
this.onCommand(plugin, cmd, exec.cmd)
|
||||
} else {
|
||||
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
|
||||
}
|
||||
if (exec.tab && typeof exec.tab === "function") {
|
||||
this.onTabComplete(plugin, cmd, exec.tab);
|
||||
this.onTabComplete(plugin, cmd, exec.tab)
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -27,40 +29,40 @@ export namespace command {
|
||||
* @param plugin 插件
|
||||
* @param name 命令
|
||||
*/
|
||||
off(plugin: any, name: string) {
|
||||
off(plugin: plugin.Plugin, name: string) {
|
||||
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
||||
this.remove(plugin, name);
|
||||
this.remove(plugin, name)
|
||||
}
|
||||
|
||||
protected abstract create(plugin: any, command: string);
|
||||
protected abstract remove(plugin: any, command: string);
|
||||
protected abstract onCommand(plugin: any, command: any, executor: Function);
|
||||
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
|
||||
protected setExecutor(plugin: any, command: any, executor: Function) {
|
||||
protected abstract create(plugin: plugin.Plugin, command: string): any
|
||||
protected abstract remove(plugin: plugin.Plugin, command: string): void
|
||||
protected abstract onCommand(plugin: plugin.Plugin, command: any, executor: Function)
|
||||
protected abstract onTabComplete(plugin: plugin.Plugin, command: any, tabCompleter: Function)
|
||||
protected setExecutor(plugin: plugin.Plugin, command: any, executor: Function) {
|
||||
return (sender: any, _: any, command: string, args: string[]) => {
|
||||
try {
|
||||
return executor(sender, command, Java.from(args));
|
||||
return executor(sender, command, Java.from(args))
|
||||
} catch (ex) {
|
||||
console.i18n("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||
console.ex(ex);
|
||||
console.ex(ex)
|
||||
if (sender.name != 'CONSOLE') {
|
||||
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
||||
}
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
|
||||
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
|
||||
return (sender: any, _: any, command: string, args: string[]) => {
|
||||
try {
|
||||
var token = args[args.length - 1];
|
||||
var complete = tabCompleter(sender, command, Java.from(args)) || [];
|
||||
return this.copyPartialMatches(complete, token);
|
||||
var token = args[args.length - 1]
|
||||
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.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)]);
|
||||
return [];
|
||||
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)])
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,7 +72,7 @@ export namespace command {
|
||||
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
||||
array.push(e)
|
||||
}
|
||||
});
|
||||
})
|
||||
return array
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@ import i18m from '@ccms/i18n'
|
||||
import { SourceMapBuilder } from 'source-map-builder'
|
||||
import * as base64 from 'base64-js'
|
||||
|
||||
const Arrays = Java.type('java.util.Arrays');
|
||||
const Level = Java.type('java.util.logging.Level');
|
||||
const Paths = Java.type('java.nio.file.Paths');
|
||||
const ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
|
||||
const Arrays = Java.type('java.util.Arrays')
|
||||
const Level = Java.type('java.util.logging.Level')
|
||||
const Paths = Java.type('java.nio.file.Paths')
|
||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||
|
||||
enum LogLevel {
|
||||
ALL,
|
||||
@@ -19,19 +19,19 @@ enum LogLevel {
|
||||
}
|
||||
|
||||
export class MiaoScriptConsole implements Console {
|
||||
Console: NodeJS.ConsoleConstructor;
|
||||
Console: NodeJS.ConsoleConstructor
|
||||
|
||||
private static sourceMaps: { [key: string]: SourceMapBuilder } = {};
|
||||
private static sourceFileMaps: { [key: string]: string } = {};
|
||||
private _name: string = '';
|
||||
private _level: LogLevel = LogLevel.INFO;
|
||||
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||
private static sourceFileMaps: { [key: string]: string } = {}
|
||||
private _name: string = ''
|
||||
private _level: LogLevel = LogLevel.INFO
|
||||
|
||||
protected logger: any;
|
||||
protected prefix: string = '§6[§bMiaoScript§6]§r ';
|
||||
protected logger: any
|
||||
protected prefix: string = '§6[§bMiaoScript§6]§r '
|
||||
|
||||
constructor(name?: string) {
|
||||
this.name = name;
|
||||
this.logger = global.logger;
|
||||
this.name = name
|
||||
this.logger = global.logger
|
||||
if (global.debug) {
|
||||
this._level = LogLevel.DEBUG
|
||||
}
|
||||
@@ -41,36 +41,36 @@ export class MiaoScriptConsole implements Console {
|
||||
}
|
||||
|
||||
get name() {
|
||||
return this._name;
|
||||
return this._name
|
||||
}
|
||||
|
||||
set name(name: string) {
|
||||
if (name) {
|
||||
this._name = `[${name}] `;
|
||||
this._name = `[${name}] `
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
|
||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
||||
}
|
||||
}
|
||||
log(...args: any[]): void {
|
||||
this.logger.info(this.name + args.join(' '));
|
||||
this.logger.info(this.name + args.join(' '))
|
||||
}
|
||||
info(...args: any[]) {
|
||||
this.logger.info(this.name + args.join(' '));
|
||||
this.logger.info(this.name + args.join(' '))
|
||||
}
|
||||
warn(...args: any[]) {
|
||||
this.logger.warning(this.name + args.join(' '));
|
||||
this.logger.warning(this.name + args.join(' '))
|
||||
}
|
||||
error(...args: any[]) {
|
||||
this.logger.log(Level.SEVERE, this.name + args.join(' '));
|
||||
this.logger.log(Level.SEVERE, this.name + args.join(' '))
|
||||
}
|
||||
debug(...args: any[]) {
|
||||
if (global.debug) {
|
||||
this.logger.info(this.name + '[DEBUG] ' + args.join(' '));
|
||||
this.logger.info(this.name + '[DEBUG] ' + args.join(' '))
|
||||
}
|
||||
}
|
||||
trace(...args: any[]): void {
|
||||
if (this._level <= LogLevel.TRACE) {
|
||||
this.logger.info(this.name + '[TRACE] ' + args.join(' '));
|
||||
this.logger.info(this.name + '[TRACE] ' + args.join(' '))
|
||||
}
|
||||
}
|
||||
sender(...args) {
|
||||
@@ -95,29 +95,29 @@ export class MiaoScriptConsole implements Console {
|
||||
if (fileName.endsWith('js')) {
|
||||
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = null
|
||||
let sourceLine = base.read(fileName).split('\n');
|
||||
let sourceLine = base.read(fileName).split('\n')
|
||||
let lastLine = sourceLine[sourceLine.length - 1]
|
||||
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||
let sourceContent = null;
|
||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1];
|
||||
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||
let sourceContent = null
|
||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
||||
if (sourceMappingURL.startsWith('data:application/jsonbase64,')) {
|
||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||
} else if (sourceMappingURL.startsWith('http')) {
|
||||
// TODO
|
||||
} else {
|
||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile();
|
||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
||||
if (file.exists()) { sourceContent = base.read(file) }
|
||||
}
|
||||
if (sourceContent) {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||
MiaoScriptConsole.sourceFileMaps[fileName] = Paths.get(fileName, '..', MiaoScriptConsole.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath();
|
||||
MiaoScriptConsole.sourceFileMaps[fileName] = Paths.get(fileName, '..', MiaoScriptConsole.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (MiaoScriptConsole.sourceMaps[fileName]) {
|
||||
let sourceMapping = MiaoScriptConsole.sourceMaps[fileName].getSource(lineNumber, 25, true, true);
|
||||
let sourceMapping = MiaoScriptConsole.sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
||||
fileName = MiaoScriptConsole.sourceFileMaps[fileName]
|
||||
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine; }
|
||||
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine }
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -128,22 +128,26 @@ export class MiaoScriptConsole implements Console {
|
||||
lineNumber
|
||||
}
|
||||
}
|
||||
stack(ex: Error): string[] {
|
||||
let stack = ex.getStackTrace();
|
||||
let cache = ['§c' + ex];
|
||||
stack(ex: Error, color: boolean = true): string[] {
|
||||
let stack = ex.getStackTrace()
|
||||
let cache = [(color ? '§c' : '') + ex]
|
||||
//@ts-ignore
|
||||
if (stack.class) {
|
||||
stack = Arrays.asList(stack)
|
||||
}
|
||||
stack.forEach(trace => {
|
||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:')) { return }
|
||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
|
||||
if (trace.className.startsWith('<')) {
|
||||
let { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
|
||||
} else {
|
||||
cache.push(` -> ${fileName}:${lineNumber} => ${trace.methodName}`)
|
||||
}
|
||||
} else {
|
||||
let className = trace.className;
|
||||
var fileName = trace.fileName as string;
|
||||
let className = trace.className
|
||||
var fileName = trace.fileName as string
|
||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
||||
className = className.substr(className.lastIndexOf('$') + 1)
|
||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||
@@ -151,70 +155,74 @@ export class MiaoScriptConsole implements Console {
|
||||
} else {
|
||||
for (let prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`);
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||
} else {
|
||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
||||
}
|
||||
}
|
||||
});
|
||||
return cache;
|
||||
})
|
||||
return cache
|
||||
}
|
||||
assert(value: any, message?: string, ...optionalParams: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
clear(): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
count(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
countReset(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dir(obj: any, options?: NodeJS.InspectOptions): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dirxml(...data: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
group(...label: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
groupCollapsed(...label: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
groupEnd(): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
table(tabularData: any, properties?: string[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
time(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timeEnd(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timeLog(label?: string, ...data: any[]): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
markTimeline(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
profile(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
profileEnd(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timeStamp(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timeline(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
timelineEnd(label?: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
}
|
||||
|
||||
7
packages/api/src/interfaces/amqp.ts
Normal file
7
packages/api/src/interfaces/amqp.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export namespace amqp {
|
||||
export const Manager = Symbol('AmqpManager')
|
||||
export namespace rabbit {
|
||||
export const Admin = Symbol('RabbitAdmin')
|
||||
export const Template = Symbol('RabbitTemplate')
|
||||
}
|
||||
}
|
||||
5
packages/api/src/interfaces/database.ts
Normal file
5
packages/api/src/interfaces/database.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export namespace database {
|
||||
export const DataBaseManager = Symbol("DataBaseManager");
|
||||
export const DataSource = Symbol("DataSource");
|
||||
export const DataBase = Symbol("DataBase");
|
||||
}
|
||||
@@ -1,2 +1,5 @@
|
||||
export * from './web'
|
||||
export * from './amqp'
|
||||
export * from './plugin'
|
||||
export * from './server'
|
||||
export * from './database'
|
||||
|
||||
@@ -2,73 +2,186 @@ export namespace plugin {
|
||||
/**
|
||||
* MiaoScript Plugin
|
||||
*/
|
||||
export const Plugin = Symbol("Plugin");
|
||||
export const Plugin = Symbol("Plugin")
|
||||
/**
|
||||
* MiaoScript Plugin Folder
|
||||
*/
|
||||
export const PluginFolder = Symbol("PluginFolder");
|
||||
export const PluginFolder = Symbol("PluginFolder")
|
||||
/**
|
||||
* Runtime Plugin Instance
|
||||
*/
|
||||
export const PluginInstance = Symbol("PluginInstance");
|
||||
export const PluginInstance = Symbol("PluginInstance")
|
||||
/**
|
||||
* MiaoScript Plugin Manager Symbol
|
||||
*/
|
||||
export const PluginManager = Symbol("PluginManager");
|
||||
export const PluginManager = Symbol("PluginManager")
|
||||
/**
|
||||
* MiaoScript Plugin Manager Interface
|
||||
*/
|
||||
export interface PluginManager {
|
||||
scan(folder: string): void;
|
||||
build(): void;
|
||||
loadFromFile(file: string): Plugin;
|
||||
load(...args: any[]): void;
|
||||
enable(...args: any[]): void;
|
||||
disable(...args: any[]): void;
|
||||
reload(...args: any[]): void;
|
||||
getPlugins(): Map<string, any>;
|
||||
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>
|
||||
}
|
||||
export const PluginScanner = Symbol("PluginScanner")
|
||||
/**
|
||||
* 插件加载元信息
|
||||
*/
|
||||
export interface PluginLoadMetadata {
|
||||
/**
|
||||
* 插件加载类型
|
||||
*/
|
||||
type: string
|
||||
/**
|
||||
* 插件名称
|
||||
*/
|
||||
name?: string
|
||||
/**
|
||||
* 插件文件
|
||||
*/
|
||||
file?: string
|
||||
/**
|
||||
* 插件实例
|
||||
*/
|
||||
instance?: any
|
||||
/**
|
||||
* 插件元信息
|
||||
*/
|
||||
metadata?: PluginMetadata
|
||||
/**
|
||||
* 插件扫描器
|
||||
*/
|
||||
scanner: PluginScanner
|
||||
/**
|
||||
* 插件加载器
|
||||
*/
|
||||
loader?: PluginLoader
|
||||
/**
|
||||
* 是否已加载
|
||||
*/
|
||||
loaded?: boolean
|
||||
[key: string]: any
|
||||
}
|
||||
/**
|
||||
* 插件扫描器
|
||||
*/
|
||||
export interface PluginScanner {
|
||||
/**
|
||||
* 扫描器类型
|
||||
*/
|
||||
type: string
|
||||
/**
|
||||
* 扫描插件目录 返回插件加载元信息列表
|
||||
* @param target 扫描目标
|
||||
*/
|
||||
scan(target: any): PluginLoadMetadata[]
|
||||
/**
|
||||
* 读取插件 返回插件加载元信息
|
||||
* @param target
|
||||
*/
|
||||
read(target: any): PluginLoadMetadata
|
||||
/**
|
||||
* 加载扫描到的目标
|
||||
* @param target 加载目标
|
||||
*/
|
||||
load(target: PluginLoadMetadata): PluginLoadMetadata
|
||||
}
|
||||
export const PluginLoader = Symbol("PluginLoader")
|
||||
/**
|
||||
* 插件加载器
|
||||
*/
|
||||
export interface PluginLoader {
|
||||
/**
|
||||
* 加载器类型
|
||||
*/
|
||||
type: string
|
||||
/**
|
||||
* 加载插件 获取元数据
|
||||
* @param target 加载目标
|
||||
* @param result 扫描器加载的结果
|
||||
*/
|
||||
require(loadMetadata: PluginLoadMetadata): PluginLoadMetadata
|
||||
/**
|
||||
* 构建插件
|
||||
* @param metadata 插件元信息
|
||||
*/
|
||||
build(metadata: PluginMetadata): Plugin
|
||||
/**
|
||||
* Load 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
load(plugin: Plugin): void
|
||||
/**
|
||||
* Enable 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
enable(plugin: Plugin): void
|
||||
/**
|
||||
* Disable 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
disable(plugin: Plugin): void
|
||||
/**
|
||||
* Reload 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
reload(plugin: Plugin): void
|
||||
}
|
||||
export interface Plugin {
|
||||
description: PluginMetadata;
|
||||
logger: Console;
|
||||
load(): void;
|
||||
enable(): void;
|
||||
disable(): void;
|
||||
description: PluginMetadata
|
||||
logger: Console
|
||||
load(): void
|
||||
enable(): void
|
||||
disable(): void
|
||||
}
|
||||
interface BaseMetadata {
|
||||
export interface BaseMetadata {
|
||||
/**
|
||||
* 名称 为空则为对象名称
|
||||
*/
|
||||
name?: string;
|
||||
name?: string
|
||||
/**
|
||||
* 支持的服务器列表 为空则代表所有
|
||||
*/
|
||||
servers?: string[];
|
||||
servers?: string[]
|
||||
}
|
||||
export interface PluginMetadata extends BaseMetadata {
|
||||
/**
|
||||
* 插件名称
|
||||
*/
|
||||
name: string;
|
||||
name: string
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
prefix?: string;
|
||||
prefix?: string
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
version: string;
|
||||
version: string
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
author: string | string[];
|
||||
author: string | string[]
|
||||
/**
|
||||
* 插件源文件 必须指定为 __filename
|
||||
*/
|
||||
source: string;
|
||||
source: string
|
||||
/**
|
||||
* 插件类型 默认为 ioc 执行 MiaoScript 加载逻辑
|
||||
*/
|
||||
type?: string
|
||||
/**
|
||||
* 插件加载信息
|
||||
*/
|
||||
loadMetadata?: PluginLoadMetadata
|
||||
/**
|
||||
* 插件本体
|
||||
*/
|
||||
target?: any;
|
||||
target?: any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +1,143 @@
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
import { NativePluginManager } from './native_plugin'
|
||||
import { constants } from '../../constants'
|
||||
|
||||
export namespace server {
|
||||
/**
|
||||
* Runtime ServerType
|
||||
*/
|
||||
export const ServerType = Symbol("ServerType");
|
||||
export const ServerType = Symbol("ServerType")
|
||||
/**
|
||||
* Runtime Console
|
||||
*/
|
||||
export const Console = Symbol("Console");
|
||||
export const Console = Symbol("Console")
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
export const Server = Symbol("Server");
|
||||
export const Server = Symbol("Server")
|
||||
/**
|
||||
* Runtime Server Instance
|
||||
*/
|
||||
export const ServerInstance = Symbol("ServerInstance");
|
||||
export const ServerInstance = Symbol("ServerInstance")
|
||||
/**
|
||||
* 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;
|
||||
getNettyPipeline(): any;
|
||||
getRootLogger(): any;
|
||||
sendJson(sender: string | any, json: object | string): void;
|
||||
tabComplete?(sender: string | any, input: string, index?: number);
|
||||
getVersion(): string
|
||||
getPlayer(name: string): any
|
||||
getOnlinePlayers(): any[]
|
||||
getConsoleSender(): any
|
||||
getService(service: string): any
|
||||
dispatchCommand(sender: string | any, command: string): boolean
|
||||
dispatchConsoleCommand(command: string): boolean
|
||||
getPluginsFolder(): string
|
||||
getNativePluginManager(): NativePluginManager
|
||||
getDedicatedServer?(): any
|
||||
getNettyPipeline(): any
|
||||
getRootLogger(): any
|
||||
sendJson(sender: string | any, json: object | string): void
|
||||
tabComplete?(sender: string | any, input: string, index?: number): string[]
|
||||
}
|
||||
@injectable()
|
||||
export abstract class ReflectServer implements server.Server {
|
||||
protected pipeline: any
|
||||
protected rootLogger: any
|
||||
|
||||
constructor() {
|
||||
this.reflect()
|
||||
}
|
||||
|
||||
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()
|
||||
this.reflectPipeline(consoleServer)
|
||||
this.reflectRootLogger(consoleServer)
|
||||
} catch (error) {
|
||||
console.error('Error When Reflect MinecraftServer!', error)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
protected reflectPipeline(consoleServer: any) {
|
||||
let connection: any
|
||||
let promise: any
|
||||
for (const method of constants.Reflect.Method.getServerConnection) {
|
||||
try {
|
||||
connection = reflect.on(consoleServer).call(method).get()
|
||||
if (connection.class.name.indexOf('ServerConnection') !== -1
|
||||
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
|
||||
connection = undefined
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||
try {
|
||||
promise = reflect.on(connection).get(field).get().get(0)
|
||||
if (promise.class.name.indexOf('Promise') !== -1) { break }
|
||||
promise = undefined
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||
}
|
||||
protected reflectRootLogger(consoleServer: any) {
|
||||
try {
|
||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
||||
} catch (error) {
|
||||
try { this.rootLogger = reflect.on(consoleServer).get(0).get().parent } catch (error) { }
|
||||
}
|
||||
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
|
||||
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
||||
this.rootLogger = undefined
|
||||
}
|
||||
// get root logger
|
||||
for (let index = 0; index < 5 && this.rootLogger.parent; index++) {
|
||||
this.rootLogger = this.rootLogger.parent
|
||||
}
|
||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
3
packages/api/src/interfaces/web.ts
Normal file
3
packages/api/src/interfaces/web.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export namespace web {
|
||||
export const Server = Symbol('Server')
|
||||
}
|
||||
@@ -58,9 +58,9 @@ export namespace task {
|
||||
return this;
|
||||
}
|
||||
|
||||
protected run(): void {
|
||||
protected run(...args: any[]): void {
|
||||
try {
|
||||
this.func();
|
||||
this.func(...args);
|
||||
} catch (ex) {
|
||||
console.console('§4插件执行任务时发生错误', ex)
|
||||
console.ex(ex);
|
||||
@@ -69,8 +69,9 @@ export namespace task {
|
||||
|
||||
/**
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
*/
|
||||
abstract submit(): Cancelable;
|
||||
abstract submit(...args: any[]): Cancelable;
|
||||
}
|
||||
/**
|
||||
* 返可取消的对象
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bukkit",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/spigot-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.7.0",
|
||||
"@ccms/common": "^0.7.0",
|
||||
"@ccms/container": "^0.7.0"
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/common": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// <reference types="@ccms/types/dist/typings/bukkit" />
|
||||
/// <reference types="@javatypes/spigot-api" />
|
||||
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
@@ -7,14 +7,12 @@ import chat from './enhance/chat'
|
||||
let Bukkit = org.bukkit.Bukkit;
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
export class BukkitServer implements server.Server {
|
||||
export class BukkitServer extends server.ReflectServer {
|
||||
private pluginsFolder: string;
|
||||
private pipeline: any;
|
||||
private rootLogger: any;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
|
||||
this.reflect()
|
||||
}
|
||||
|
||||
getPlayer(name: string) {
|
||||
@@ -47,6 +45,9 @@ export class BukkitServer implements server.Server {
|
||||
getNativePluginManager() {
|
||||
return Bukkit.getPluginManager() as any;
|
||||
}
|
||||
getDedicatedServer() {
|
||||
return reflect.on(Bukkit.getServer()).get('console').get()
|
||||
}
|
||||
getNettyPipeline() {
|
||||
return this.pipeline;
|
||||
}
|
||||
@@ -62,41 +63,4 @@ export class BukkitServer implements server.Server {
|
||||
this.dispatchConsoleCommand(result)
|
||||
}
|
||||
}
|
||||
|
||||
private reflect() {
|
||||
let consoleServer = reflect.on(Bukkit.getServer()).get('console').get()
|
||||
this.reflectPipeline(consoleServer)
|
||||
this.reflectRootLogger(consoleServer)
|
||||
}
|
||||
|
||||
private reflectPipeline(consoleServer: any) {
|
||||
let connection: any;
|
||||
let promise: any;
|
||||
for (const method of constants.Reflect.Method.getServerConnection) {
|
||||
try {
|
||||
connection = reflect.on(consoleServer).call(method).get()
|
||||
if (connection.class.name.indexOf('ServerConnection') !== -1
|
||||
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break; }
|
||||
connection = undefined;
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||
try {
|
||||
promise = reflect.on(connection).get(field).get().get(0);
|
||||
if (promise.class.name.indexOf('Promise') !== -1) { break; }
|
||||
promise = undefined;
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||
}
|
||||
|
||||
private reflectRootLogger(consoleServer: any) {
|
||||
try {
|
||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
||||
} catch (error) {
|
||||
console.error("Can't found rootLogger!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,10 +23,8 @@ export class BukkitTaskManager implements task.TaskManager {
|
||||
}
|
||||
|
||||
export class BukkitTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = new BukkitRunnable({
|
||||
run: () => this.run()
|
||||
})
|
||||
submit(...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) {
|
||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bungee",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/bungee-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.7.0",
|
||||
"@ccms/common": "^0.7.0",
|
||||
"@ccms/container": "^0.7.0"
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/common": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// <reference types="@ccms/types/dist/typings/bungee" />
|
||||
/// <reference types="@javatypes/bungee-api" />
|
||||
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
@@ -22,8 +22,8 @@ export class BungeeTaskManager implements task.TaskManager {
|
||||
}
|
||||
|
||||
export class BungeeTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = new Runnable({ run: () => this.run() })
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
let run = new Runnable({ run: () => this.run(...args) })
|
||||
if (this.isAsync) {
|
||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ccms/client",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript client package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,10 +22,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"minecraft-protocol": "^1.11.0"
|
||||
"minecraft-protocol": "^1.13.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/common",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,12 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.8.2",
|
||||
"@javatypes/jdk": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.7.0"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
||||
@@ -1,196 +1,204 @@
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
|
||||
/**
|
||||
* 反射工具类
|
||||
* Created by MiaoWoo on 2017/2/9 0009.
|
||||
*/
|
||||
const JavaClass = Java.type('java.lang.Class');
|
||||
const JavaClass = Java.type('java.lang.Class')
|
||||
const JavaObject = Java.type('java.lang.Object')
|
||||
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
|
||||
const methodCache = [];
|
||||
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
|
||||
const methodCache = []
|
||||
|
||||
class Reflect {
|
||||
private obj: any;
|
||||
private class: any
|
||||
private obj: java.lang.Object
|
||||
private class: java.lang.Class<any>
|
||||
|
||||
constructor(obj: any) {
|
||||
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
|
||||
if (obj instanceof JavaClass) {
|
||||
this.obj = null;
|
||||
this.class = obj;
|
||||
this.obj = null
|
||||
this.class = obj
|
||||
} else {
|
||||
this.obj = obj;
|
||||
this.obj = obj
|
||||
if (obj !== null && obj !== undefined && obj.class) {
|
||||
this.class = obj.class;
|
||||
this.class = obj.class
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
method(...args: any[]) {
|
||||
return declaredMethod(this.class, args[0], types(args.slice(1)));
|
||||
method(name: string, ...args: java.lang.Class<any>[]) {
|
||||
return declaredMethod(this.class, name, ...args)
|
||||
}
|
||||
|
||||
methods() {
|
||||
return Java.from(declaredMethods(this.class));
|
||||
return Java.from(declaredMethods(this.class))
|
||||
}
|
||||
|
||||
field(name): Reflect {
|
||||
field(name: string | java.lang.String): Reflect {
|
||||
try {
|
||||
// Try getting a public field
|
||||
let field = this.class.field(name);
|
||||
return on(field.get(this.obj));
|
||||
let field = this.class.getField(name)
|
||||
return on(field.get(this.obj))
|
||||
} catch (ex) {
|
||||
// Try again, getting a non-public field
|
||||
return on(accessible(declaredField(this.class, name)).get(this.obj));
|
||||
return on(accessible(declaredField(this.class, name)).get(this.obj))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fields(declared = false) {
|
||||
return Java.from(declared ? this.class.declaredFields : this.class.fields);
|
||||
fields(declared = false): java.lang.reflect.Field[] {
|
||||
return Java.from(declared ? this.class.getDeclaredFields() : this.class.getFields())
|
||||
}
|
||||
|
||||
values(declared = false) {
|
||||
let cache = {};
|
||||
this.fields(declared).forEach(fed => cache[fed.name] = this.field(fed.name).get())
|
||||
return cache;
|
||||
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.field(field.getName()).get() }, {}) as any
|
||||
}
|
||||
|
||||
call(...args): Reflect {
|
||||
let params = args.slice(1);
|
||||
let method = accessible(declaredMethod(this.class, args[0], types(params)));
|
||||
let result = method.invoke(this.get(), params);
|
||||
return result && on(result);
|
||||
};
|
||||
call(...args: any[]): Reflect {
|
||||
let params = args.slice(1)
|
||||
let method = accessible(declaredMethod(this.class, args[0], ...types(params)))
|
||||
let result = method.invoke(this.get(), params)
|
||||
return result && on(result)
|
||||
}
|
||||
|
||||
get(...args): Reflect | any {
|
||||
return args.length === 1 ? this.field(args[0]) : this.obj;
|
||||
};
|
||||
get(): any
|
||||
get(index: number, declared?: boolean): Reflect
|
||||
get(prop: string): Reflect
|
||||
get(param?: string | number, declared: boolean = true): Reflect | any {
|
||||
if (param == undefined || param == null) return this.obj
|
||||
if (typeof param == "number") {
|
||||
return on(accessible(this.fields(declared)[param]).get(this.obj))
|
||||
}
|
||||
if (typeof param == "string") {
|
||||
return this.field(param)
|
||||
}
|
||||
}
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
set(name, value): Reflect {
|
||||
accessible(declaredField(this.class, name)).set(this.obj, value);
|
||||
return this;
|
||||
};
|
||||
set(name: any, value: any): Reflect {
|
||||
accessible(declaredField(this.class, name)).set(this.obj, value)
|
||||
return this
|
||||
}
|
||||
|
||||
create(...args): Reflect {
|
||||
return on(declaredConstructor(this.class, args).newInstance(args));
|
||||
};
|
||||
return on(declaredConstructor(this.class, args).newInstance(args))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array of types for an array of objects
|
||||
*/
|
||||
function types(values, def?) {
|
||||
function types(values: any[], def?: any) {
|
||||
if (values === null) {
|
||||
return [];
|
||||
return []
|
||||
}
|
||||
let result: any[] = [];
|
||||
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class));
|
||||
return result;
|
||||
let result: java.lang.Class<any>[] = []
|
||||
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class))
|
||||
return result
|
||||
}
|
||||
|
||||
function accessible(accessible) {
|
||||
function accessible<T extends java.lang.reflect.AccessibleObject>(accessible: T): T {
|
||||
if (accessible === null) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
if (!accessible.isAccessible()) {
|
||||
accessible.setAccessible(true);
|
||||
accessible.setAccessible(true)
|
||||
}
|
||||
return accessible;
|
||||
return accessible
|
||||
}
|
||||
|
||||
function declaredConstructor(clazz, param) {
|
||||
let constructor;
|
||||
let constructor
|
||||
try {
|
||||
constructor = clazz.getDeclaredConstructor(types(param));
|
||||
constructor = clazz.getDeclaredConstructor(types(param))
|
||||
} catch (ex) {
|
||||
try {
|
||||
constructor = clazz.getDeclaredConstructor(types(param, true));
|
||||
constructor = clazz.getDeclaredConstructor(types(param, true))
|
||||
} catch (ex) {
|
||||
constructor = clazz.getDeclaredConstructors()[0];
|
||||
constructor = clazz.getDeclaredConstructors()[0]
|
||||
}
|
||||
}
|
||||
return accessible(constructor);
|
||||
return accessible(constructor)
|
||||
}
|
||||
|
||||
function declaredField(clazz, name) {
|
||||
function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.String) {
|
||||
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
|
||||
let target = clazz;
|
||||
let field = null;
|
||||
let target = clazz
|
||||
let field = null
|
||||
// noinspection JSUnresolvedVariable
|
||||
while (target !== JavaObject.class) {
|
||||
try {
|
||||
field = target.getDeclaredField(name);
|
||||
if (field !== null) { break; }
|
||||
field = target.getDeclaredField(name)
|
||||
if (field !== null) { break }
|
||||
} catch (e) {
|
||||
if (target === undefined) { break; }
|
||||
target = target.getSuperclass();
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
}
|
||||
}
|
||||
if (field === null) {
|
||||
throw new NoSuchFieldException(name + " is not found in " + clazz.name);
|
||||
throw new NoSuchFieldException(name + " is not found in " + clazz.getName())
|
||||
}
|
||||
return field;
|
||||
return field
|
||||
}
|
||||
|
||||
function declaredMethod(clazz, name, clazzs) {
|
||||
let key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
|
||||
function declaredMethod(clazz: java.lang.Class<any>, name: string, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
||||
let key = clazz.getName() + '.' + name + ':' + (clazzs || []).join(':')
|
||||
if (!methodCache[key]) {
|
||||
try {
|
||||
methodCache[key] = clazz.getMethod(name, clazzs);
|
||||
methodCache[key] = clazz.getMethod(name, ...clazzs)
|
||||
} catch (ex) {
|
||||
try {
|
||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
|
||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs as any)
|
||||
} catch (ex) {
|
||||
for (const m of Java.from(declaredMethods(clazz))) {
|
||||
if (m.name == name) {
|
||||
methodCache[key] = m;
|
||||
break;
|
||||
if (m.getName() == name) {
|
||||
methodCache[key] = m
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return methodCache[key];
|
||||
return methodCache[key]
|
||||
}
|
||||
|
||||
function declaredMethods(clazz) {
|
||||
return clazz.declaredMethods;
|
||||
function declaredMethods(clazz: java.lang.Class<any>) {
|
||||
return clazz.getDeclaredMethods()
|
||||
}
|
||||
|
||||
let classMethodsCache: any[] = [];
|
||||
let classMethodsCache: any[] = []
|
||||
|
||||
function mapToObject(javaObj) {
|
||||
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||
let target = {};
|
||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
|
||||
return target;
|
||||
let target = {}
|
||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t))
|
||||
return target
|
||||
}
|
||||
|
||||
function getJavaObjectMethods(javaObj) {
|
||||
let className = javaObj.class.name;
|
||||
let className = javaObj.class.name
|
||||
if (!classMethodsCache[className]) {
|
||||
let names: any[] = [];
|
||||
let methods = javaObj.class.methods;
|
||||
let names: any[] = []
|
||||
let methods = javaObj.class.methods
|
||||
for (let i in methods) {
|
||||
names.push(methods[i].name);
|
||||
names.push(methods[i].name)
|
||||
}
|
||||
classMethodsCache[className] = names;
|
||||
classMethodsCache[className] = names
|
||||
}
|
||||
return classMethodsCache[className];
|
||||
return classMethodsCache[className]
|
||||
}
|
||||
|
||||
function mapMethod(target, source, name) {
|
||||
target[name] = function __SimpleDynamicMethod__(...args) {
|
||||
if (args.length > 0) {
|
||||
return source[name](args);
|
||||
return source[name](args)
|
||||
} else {
|
||||
return source[name]();
|
||||
return source[name]()
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function on(obj) {
|
||||
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
||||
return new Reflect(obj);
|
||||
return new Reflect(obj)
|
||||
}
|
||||
|
||||
export = {
|
||||
|
||||
32
packages/common/src/thread-pool.ts
Normal file
32
packages/common/src/thread-pool.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
const ThreadGroup = Java.type("java.lang.ThreadGroup")
|
||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
|
||||
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
|
||||
|
||||
interface ThreadPoolConfig {
|
||||
corePoolSize?: number
|
||||
maximumPoolSize?: number
|
||||
keepAliveTime?: number
|
||||
workQueueSize?: number
|
||||
groupName: string
|
||||
}
|
||||
|
||||
export default {
|
||||
create(config: ThreadPoolConfig): java.util.concurrent.ThreadPoolExecutor {
|
||||
let threadCount = new AtomicInteger(0)
|
||||
config = {
|
||||
corePoolSize: 10,
|
||||
maximumPoolSize: 100,
|
||||
keepAliveTime: 60,
|
||||
workQueueSize: 500,
|
||||
...config
|
||||
}
|
||||
return new ThreadPoolExecutor(
|
||||
config.corePoolSize, config.maximumPoolSize, config.keepAliveTime, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue(config.workQueueSize),
|
||||
(run: any) => new Thread(new ThreadGroup(config.groupName), run, config.groupName + "-" + threadCount.incrementAndGet()),
|
||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/compile",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,6 +21,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/container",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,9 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.8.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"inversify": "^5.0.1",
|
||||
|
||||
7
packages/container/src/constants.ts
Normal file
7
packages/container/src/constants.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export namespace ioc {
|
||||
export const Autowired = Symbol('Autowired')
|
||||
export const Resource = Symbol('Resource')
|
||||
export const JavaClass = Symbol('JavaClass')
|
||||
export const JavaInstance = Symbol('JavaInstance')
|
||||
export const JavaStaticClass = Symbol('JavaStaticClass')
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { interfaces, Container } from "inversify";
|
||||
import { interfaces, Container } from "inversify"
|
||||
|
||||
let _container: Container;
|
||||
let _container: Container
|
||||
|
||||
const ContainerInstance = Symbol.for("@ccms/ioc:Container");
|
||||
const INJECTION = Symbol.for("INJECTION");
|
||||
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
|
||||
const INJECTION = Symbol.for("INJECTION")
|
||||
|
||||
function _proxyGetter(
|
||||
proto: any,
|
||||
@@ -13,17 +13,17 @@ function _proxyGetter(
|
||||
) {
|
||||
function getter(this: object) {
|
||||
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
Reflect.defineMetadata(INJECTION, resolve(), this, key);
|
||||
Reflect.defineMetadata(INJECTION, resolve(), this, key)
|
||||
}
|
||||
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
||||
return Reflect.getMetadata(INJECTION, this, key);
|
||||
return Reflect.getMetadata(INJECTION, this, key)
|
||||
} else {
|
||||
return resolve();
|
||||
return resolve()
|
||||
}
|
||||
}
|
||||
|
||||
function setter(this: object, newVal: any) {
|
||||
Reflect.defineMetadata(INJECTION, newVal, this, key);
|
||||
Reflect.defineMetadata(INJECTION, newVal, this, key)
|
||||
}
|
||||
|
||||
Object.defineProperty(proto, key, {
|
||||
@@ -31,63 +31,63 @@ function _proxyGetter(
|
||||
enumerable: true,
|
||||
get: getter,
|
||||
set: setter
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
function initContainer(container: Container) {
|
||||
Reflect.defineMetadata(ContainerInstance, container, Reflect);
|
||||
_container = container;
|
||||
Reflect.defineMetadata(ContainerInstance, container, Reflect)
|
||||
return _container = container
|
||||
}
|
||||
|
||||
function getContainer(): Container {
|
||||
return _container || Reflect.getMetadata(ContainerInstance, Reflect)
|
||||
return _container || initContainer(new Container())
|
||||
}
|
||||
|
||||
function makePropertyInjectDecorator(doCache: boolean) {
|
||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||
return function(proto: any, key: string): void {
|
||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||
return function (proto: any, key: string): void {
|
||||
let resolve = () => {
|
||||
return getContainer().get(serviceIdentifier);
|
||||
};
|
||||
_proxyGetter(proto, key, resolve, doCache);
|
||||
};
|
||||
};
|
||||
return getContainer().get(serviceIdentifier)
|
||||
}
|
||||
_proxyGetter(proto, key, resolve, doCache)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makePropertyInjectNamedDecorator(doCache: boolean) {
|
||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
||||
return function(proto: any, key: string): void {
|
||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
||||
return function (proto: any, key: string): void {
|
||||
let resolve = () => {
|
||||
return getContainer().getNamed(serviceIdentifier, named);
|
||||
};
|
||||
_proxyGetter(proto, key, resolve, doCache);
|
||||
};
|
||||
};
|
||||
return getContainer().getNamed(serviceIdentifier, named)
|
||||
}
|
||||
_proxyGetter(proto, key, resolve, doCache)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makePropertyInjectTaggedDecorator(doCache: boolean) {
|
||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
||||
return function(proto: any, propertyName: string): void {
|
||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
||||
return function (proto: any, propertyName: string): void {
|
||||
let resolve = () => {
|
||||
return getContainer().getTagged(serviceIdentifier, key, value);
|
||||
};
|
||||
_proxyGetter(proto, propertyName, resolve, doCache);
|
||||
};
|
||||
};
|
||||
return getContainer().getTagged(serviceIdentifier, key, value)
|
||||
}
|
||||
_proxyGetter(proto, propertyName, resolve, doCache)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makePropertyMultiInjectDecorator(doCache: boolean) {
|
||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||
return function(proto: any, key: string): void {
|
||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||
return function (proto: any, key: string): void {
|
||||
let resolve = () => {
|
||||
return getContainer().getAll(serviceIdentifier);
|
||||
};
|
||||
_proxyGetter(proto, key, resolve, doCache);
|
||||
};
|
||||
};
|
||||
return getContainer().getAll(serviceIdentifier)
|
||||
}
|
||||
_proxyGetter(proto, key, resolve, doCache)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let doCache = true;
|
||||
let doCache = true
|
||||
|
||||
let lazyInject = makePropertyInjectDecorator(doCache)
|
||||
let lazyInjectNamed = makePropertyInjectNamedDecorator(doCache)
|
||||
@@ -102,4 +102,4 @@ export {
|
||||
lazyInjectNamed,
|
||||
lazyInjectTagged,
|
||||
lazyMultiInject
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,25 +1,91 @@
|
||||
import "reflect-metadata";
|
||||
import { initContainer } from './decorators'
|
||||
import { interfaces, Container } from 'inversify';
|
||||
import { fluentProvide } from 'inversify-binding-decorators';
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
|
||||
const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
||||
return fluentProvide(identifier).whenTargetNamed(name).done();
|
||||
};
|
||||
import "reflect-metadata"
|
||||
import { initContainer, getContainer } from './decorators'
|
||||
import { interfaces, Container } from 'inversify'
|
||||
import { fluentProvide } from 'inversify-binding-decorators'
|
||||
import { ioc } from "./constants"
|
||||
|
||||
const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
|
||||
return fluentProvide(identifier).inSingletonScope().done();
|
||||
};
|
||||
/**
|
||||
* 注册一个命名对象
|
||||
* @param identifier 标识符
|
||||
* @param name 名称
|
||||
*/
|
||||
export const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
||||
return fluentProvide(identifier).whenTargetNamed(name).done()
|
||||
}
|
||||
|
||||
const DefaultContainer = new Container();
|
||||
initContainer(DefaultContainer);
|
||||
/**
|
||||
* 注册一个单例对象
|
||||
* @param identifier 标识符
|
||||
*/
|
||||
export const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
|
||||
return fluentProvide(identifier).inSingletonScope().done()
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册一个单例对象
|
||||
* @param identifier 标识符
|
||||
*/
|
||||
export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
||||
return fluentProvide(identifier).inSingletonScope().whenTargetNamed(name).done()
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个 java.lang.Class
|
||||
* @param className Java全类名
|
||||
*/
|
||||
export const JavaClass = (className: string) => {
|
||||
return function (target: any, 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!')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个JS的Java类
|
||||
* @param className Java 全类名
|
||||
*/
|
||||
export const JSClass = (className: string) => {
|
||||
return function (target: any, 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!')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动注入实例由平台实现
|
||||
* @param className 类名
|
||||
*/
|
||||
export const Autowired = (className?: string | any) => {
|
||||
return function (target: any, propertyKey: string) {
|
||||
target[propertyKey] = getContainer().getNamed(ioc.Autowired, className || propertyKey)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动注入资源由平台实现
|
||||
* @param className 类名
|
||||
*/
|
||||
export const Resource = (resourceName?: string | any) => {
|
||||
return function (target: any, propertyKey: string) {
|
||||
target[propertyKey] = getContainer().getNamed(ioc.Resource, resourceName || propertyKey)
|
||||
}
|
||||
}
|
||||
|
||||
export const reduceMetadata = (ctx: interfaces.Context): any => {
|
||||
return ctx.currentRequest.target.metadata.reduce((result, entry, index) => {
|
||||
result[entry.key] = entry.value
|
||||
return result
|
||||
}, {})
|
||||
}
|
||||
|
||||
export const DefaultContainer = new Container()
|
||||
initContainer(DefaultContainer)
|
||||
|
||||
export * from 'inversify'
|
||||
export * from './constants'
|
||||
export * from './decorators'
|
||||
export * from 'inversify-binding-decorators'
|
||||
export {
|
||||
fluentProvide,
|
||||
provideNamed,
|
||||
provideSingleton,
|
||||
DefaultContainer
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/core",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.7.0",
|
||||
"@ccms/container": "^0.7.0"
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -26,17 +26,16 @@ class MiaoScriptCore {
|
||||
}
|
||||
|
||||
loadServerConsole() {
|
||||
global.setGlobal('eventCenter', new EventEmitter(), { writable: false, configurable: false });
|
||||
//@ts-ignore
|
||||
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
||||
}
|
||||
|
||||
loadTaskFunction() {
|
||||
global.setGlobal('setTimeout', (func: Function, tick: number, async: boolean = false) => {
|
||||
this.taskManager.create(func).later(tick).async(async).submit()
|
||||
global.setGlobal('setTimeout', (func: Function, tick: number, ...args: any[]) => {
|
||||
return this.taskManager.create(func).later(tick).submit(...args)
|
||||
}, { writable: false, configurable: false })
|
||||
global.setGlobal('setInterval', (func: Function, tick: number, async: boolean = false) => {
|
||||
this.taskManager.create(func).timer(tick).async(async).submit()
|
||||
global.setGlobal('setInterval', (func: Function, tick: number, ...args: any[]) => {
|
||||
return this.taskManager.create(func).timer(tick).submit(...args)
|
||||
}, { writable: false, configurable: false })
|
||||
}
|
||||
|
||||
@@ -54,8 +53,7 @@ class MiaoScriptCore {
|
||||
console.i18n("ms.core.engine.disable")
|
||||
this.pluginManager.disable(this.pluginManager.getPlugins())
|
||||
this.taskManager.disable()
|
||||
//@ts-ignore
|
||||
require.disable()
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
1
packages/database/.npmignore
Symbolic link
1
packages/database/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.npmignore
|
||||
31
packages/database/package.json
Normal file
31
packages/database/package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@ccms/database",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript database package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/spring-jdbc": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2"
|
||||
}
|
||||
}
|
||||
3
packages/database/src/constants.ts
Normal file
3
packages/database/src/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const METADATA_KEY = {
|
||||
|
||||
}
|
||||
90
packages/database/src/database.ts
Normal file
90
packages/database/src/database.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { Model } from './model'
|
||||
|
||||
const HikariDataSource = Java.type('com.zaxxer.hikari.HikariDataSource')
|
||||
const HikariConfig = Java.type('com.zaxxer.hikari.HikariConfig')
|
||||
const JdbcTemplate = Java.type('org.springframework.jdbc.core.JdbcTemplate')
|
||||
|
||||
/**
|
||||
* 数据库配置
|
||||
*/
|
||||
export interface DataBaseConfig {
|
||||
/**
|
||||
* 数据库连接串
|
||||
*/
|
||||
url: string | javax.sql.DataSource
|
||||
/**
|
||||
* 数据库驱动
|
||||
*/
|
||||
driverClassName?: string
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
username?: string
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
password?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库封装类
|
||||
*/
|
||||
export class DataBase {
|
||||
private dataSource: javax.sql.DataSource
|
||||
private jdbcTemplate: org.springframework.jdbc.core.JdbcTemplate
|
||||
|
||||
constructor(dbConfig: DataBaseConfig) {
|
||||
if (!dbConfig.url) { throw new Error('DataBase url can\'t be null!') }
|
||||
this.createDataSource(dbConfig)
|
||||
this.initialize()
|
||||
}
|
||||
|
||||
private createDataSource(dbConfig: DataBaseConfig) {
|
||||
if (typeof dbConfig.url === "string") {
|
||||
if (!dbConfig.username || !dbConfig.password) {
|
||||
throw new Error('DataBase username or password can\'t be null!')
|
||||
}
|
||||
let config = new HikariConfig()
|
||||
if (dbConfig.driverClassName) {
|
||||
config.setDriverClassName(dbConfig.driverClassName)
|
||||
}
|
||||
config.setUsername(dbConfig.username)
|
||||
config.setPassword(dbConfig.password)
|
||||
config.setJdbcUrl(dbConfig.url)
|
||||
this.dataSource = new HikariDataSource(config)
|
||||
} else {
|
||||
this.dataSource = dbConfig.url
|
||||
}
|
||||
}
|
||||
|
||||
private initialize() {
|
||||
this.jdbcTemplate = new JdbcTemplate(this.dataSource)
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL查询
|
||||
* @param sql SQL语句
|
||||
*/
|
||||
query<T>(sql: string, ...args: any[]): Array<T> {
|
||||
let startTime = Date.now()
|
||||
let result = Java.from<any>(this.jdbcTemplate.queryForList(sql, args))
|
||||
console.debug(java.lang.String.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行SQL更新
|
||||
* @param sql SQL语句
|
||||
*/
|
||||
update(sql: string, ...args: any[]): number {
|
||||
let startTime = Date.now()
|
||||
let result = this.jdbcTemplate.update(sql, args)
|
||||
console.debug(java.lang.String.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
close() {
|
||||
//@ts-ignore
|
||||
this.dataSource.close()
|
||||
}
|
||||
}
|
||||
7
packages/database/src/decorators.ts
Normal file
7
packages/database/src/decorators.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import 'reflect-metadata'
|
||||
|
||||
export function id() {
|
||||
return (target: Object, propertyKey: string | symbol) => void {
|
||||
|
||||
}
|
||||
}
|
||||
6
packages/database/src/index.ts
Normal file
6
packages/database/src/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/spring-jdbc" />
|
||||
|
||||
export * from './database'
|
||||
export * from './manager'
|
||||
53
packages/database/src/manager.ts
Normal file
53
packages/database/src/manager.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { plugin, database } from '@ccms/api'
|
||||
import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
||||
import { DataBase, DataBaseConfig } from './database'
|
||||
|
||||
@provideSingleton(database.DataBaseManager)
|
||||
export class DataBaseManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private instance: any
|
||||
|
||||
private beanFactory: any
|
||||
private mainDatabase: DataBase
|
||||
private databases: { [key: string]: DataBase } = {}
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
try {
|
||||
this.beanFactory = this.instance.getAutowireCapableBeanFactory()
|
||||
let mainDatasource = this.beanFactory.getBean(Packages.javax.sql.DataSource.class)
|
||||
this.mainDatabase = new DataBase({ url: mainDatasource })
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得主数据库
|
||||
* Get MainDatabase
|
||||
*/
|
||||
getMainDatabase() {
|
||||
return this.mainDatabase
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建数据库
|
||||
* Create A Database Instance
|
||||
* @param name 数据库名称 用于代码 database Name use at code
|
||||
* @param config 数据库配置
|
||||
*/
|
||||
createDatabase(name: string, config: DataBaseConfig) {
|
||||
Java.synchronized(() => {
|
||||
if (this.databases[name]) return this.databases[name]
|
||||
return this.databases[name] = new DataBase(config)
|
||||
}, this.databases)()
|
||||
}
|
||||
|
||||
getDatabase(name: string) {
|
||||
return this.databases[name]
|
||||
}
|
||||
|
||||
disable() {
|
||||
Object.values(this.databases).forEach((ds) => ds?.close())
|
||||
}
|
||||
}
|
||||
11
packages/database/src/model.ts
Normal file
11
packages/database/src/model.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { DataBase } from "./database"
|
||||
|
||||
export class Model<T> {
|
||||
constructor(private database: DataBase) {
|
||||
|
||||
}
|
||||
queryForList(): Array<T> {
|
||||
|
||||
return []
|
||||
}
|
||||
}
|
||||
7
packages/database/tsconfig.json
Normal file
7
packages/database/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/i18n",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript i18n package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,14 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/js-yaml": "^3.12.3",
|
||||
"@ccms/nashorn": "^0.8.2",
|
||||
"@types/js-yaml": "^3.12.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.7.0",
|
||||
"js-yaml": "^3.13.1"
|
||||
"js-yaml": "^3.14.0"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
# sponge bukkit jdk bungee nukkit
|
||||
TYPE=nukkit
|
||||
TARGET=../types/dist/typings
|
||||
npx tsc src/build.ts --outDir dist
|
||||
cd dist
|
||||
rm -rf temp
|
||||
mkdir -p temp
|
||||
node build.js ${TYPE}
|
||||
cd ../
|
||||
rm -rf ${TARGET}/${TYPE}
|
||||
mkdir -p ${TARGET}/${TYPE}
|
||||
cp dist/temp/* ${TARGET}/${TYPE}/ -R
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nashorn",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,6 +22,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
import * as fs from "fs";
|
||||
|
||||
function convertJson2TypeDefiend(infile: string, outDir: string) {
|
||||
const file = infile.split(".json")[0];
|
||||
const json = fs.readFileSync(`${inDir}/${file}.json`).toString();
|
||||
const obj = JSON.parse(json);
|
||||
const qnas: string[] = obj.qualifiedName.split(".");
|
||||
let closeBuk = 0;
|
||||
let temp = `declare namespace ${qnas[0]} {\n`;
|
||||
closeBuk++;
|
||||
const nms = qnas.slice(1, qnas.length - 1);
|
||||
for (const nm of nms) {
|
||||
temp += `${' '.repeat(closeBuk)}namespace ${nm.replace('function', 'function$')} {\n`;
|
||||
closeBuk++;
|
||||
}
|
||||
let classModifier = formatClassModifier(obj.modifiers)
|
||||
temp += `${' '.repeat(closeBuk)}// @ts-ignore\n`
|
||||
temp += `${' '.repeat(closeBuk)}${classModifier}${qnas[qnas.length - 1]}`
|
||||
let isInterface = classModifier.includes('interface')
|
||||
let safeInterface = [];
|
||||
for (const ifs of obj.interfaces) {
|
||||
if (!ifs.qualifiedName.startsWith('java')) {
|
||||
safeInterface.push(ifs)
|
||||
}
|
||||
}
|
||||
if (isInterface) {
|
||||
if (safeInterface.length > 0) {
|
||||
temp += ' extends '
|
||||
for (const ifs of safeInterface) {
|
||||
temp += ifs.qualifiedName;
|
||||
temp += ', '
|
||||
}
|
||||
temp = temp.substr(0, temp.length - 2);
|
||||
}
|
||||
} else {
|
||||
temp += `${(obj.superclass) ? (' extends ' + (obj.superclass.qualifiedName == "<any>" ? "object" : obj.superclass.qualifiedName)) : ''}`;
|
||||
if (safeInterface.length > 0) {
|
||||
temp += ' implements '
|
||||
for (const ifs of safeInterface) {
|
||||
temp += ifs.qualifiedName;
|
||||
temp += ', '
|
||||
}
|
||||
temp = temp.substr(0, temp.length - 2);
|
||||
}
|
||||
}
|
||||
temp += ' {\n'
|
||||
closeBuk++;
|
||||
for (const constructor of obj.constructors) {
|
||||
temp += `${formatDoc(constructor.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}constructor(${formatParameters(constructor.parameters)})\n`;
|
||||
}
|
||||
|
||||
let members = [];
|
||||
|
||||
let methods = '';
|
||||
for (const method of obj.methods) {
|
||||
let methodModifier = isInterface ? '' : replaceModifiers(method.modifiers, classModifier.includes('abstract'))
|
||||
if (!whiteKey.includes(method.name)) {
|
||||
if (members[method.name] && methodModifier.includes('abstract')) {
|
||||
continue;
|
||||
}
|
||||
members[method.name] = methodModifier;
|
||||
}
|
||||
methods += `${formatDoc(method.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${methodModifier} ${method.name}(${formatParameters(method.parameters)}): ${mappingType(method.returnType.type)};\n`;
|
||||
}
|
||||
|
||||
let fields = '';
|
||||
for (const field of obj.fields) {
|
||||
if (members[field.name]) {
|
||||
continue;
|
||||
}
|
||||
fields += `${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${isInterface ? '' : replaceModifiers(field.modifiers)} ${field.name}: ${mappingType(field.type ? field.type.type : "any")};\n`;
|
||||
}
|
||||
|
||||
temp += fields + methods;
|
||||
|
||||
for (let index = 0; index < closeBuk; index++) {
|
||||
temp += `${' '.repeat(closeBuk - index - 1)}}\n`;
|
||||
}
|
||||
|
||||
fs.writeFileSync(`${outDir}/${file}.${suffix}`, temp);
|
||||
return `${file}.${suffix}`;
|
||||
}
|
||||
|
||||
function formatClassModifier(modifiers: string) {
|
||||
let tempm = modifiers.replace('public', '').replace('static', '').replace('final', '').trim();
|
||||
if (!modifiers.includes('interface')) { tempm += ' class' }
|
||||
return tempm.length > 0 ? (tempm + ' ') : '';
|
||||
}
|
||||
|
||||
function formatDoc(doc: string, closeBuk: number) {
|
||||
let middleDoc = '';
|
||||
for (const line of doc.split('\n')) {
|
||||
if (line.trim().length != 0) {
|
||||
middleDoc += `${' '.repeat(closeBuk)} * ${line.trim()}\n`
|
||||
}
|
||||
}
|
||||
return middleDoc.length > 0 ? `${' '.repeat(closeBuk)}/**\n${middleDoc}${' '.repeat(closeBuk)} */\n` : '';
|
||||
}
|
||||
|
||||
function replaceModifiers(modifiers: string, absClass = false): string {
|
||||
// modifiers = modifiers.replace(' final', ' readonly');
|
||||
modifiers = modifiers.split(" final")[0];
|
||||
modifiers = modifiers.split(" native")[0];
|
||||
modifiers = modifiers.split(" volatile")[0];
|
||||
modifiers = modifiers.split(" transient")[0];
|
||||
modifiers = modifiers.split(" synchronized")[0];
|
||||
if (!absClass) {
|
||||
modifiers = modifiers.split(" abstract")[0];
|
||||
}
|
||||
return modifiers;
|
||||
}
|
||||
|
||||
function formatParameters(params: any[]) {
|
||||
let tempParam = '';
|
||||
for (const p of params) {
|
||||
tempParam += `${mappingName(p.name)}: ${mappingType(p.type ? p.type.qualifiedName : 'any')}, `
|
||||
}
|
||||
return tempParam.substr(0, tempParam.length - 2);
|
||||
}
|
||||
|
||||
const nameMap = [];
|
||||
nameMap['function'] = 'func'
|
||||
nameMap['in'] = 'input'
|
||||
nameMap['var'] = 'variable'
|
||||
|
||||
function mappingName(name: string) {
|
||||
if (whiteKey.includes(name)) { return name }
|
||||
let outName = nameMap[name] || name || '';
|
||||
return outName;
|
||||
}
|
||||
|
||||
let whiteKey = ['shift', "map", 'filter', 'values', 'valueOf', 'toString', 'length', 'includes', 'entries', 'keys', 'join', 'fill']
|
||||
|
||||
const typeMap = [];
|
||||
typeMap['int'] = 'number';
|
||||
typeMap['int[]'] = 'number[]';
|
||||
typeMap['int[][]'] = 'number[][]';
|
||||
typeMap['byte'] = 'number';
|
||||
typeMap['byte[]'] = 'number[]';
|
||||
typeMap['double'] = 'number';
|
||||
typeMap['double[]'] = 'number[]';
|
||||
typeMap['short'] = 'number';
|
||||
typeMap['short[]'] = 'number[]';
|
||||
typeMap['float'] = 'number';
|
||||
typeMap['float[]'] = 'number[]';
|
||||
typeMap['long'] = 'number';
|
||||
typeMap['long[]'] = 'number[]';
|
||||
typeMap['<any>'] = 'any';
|
||||
typeMap['char'] = 'string';
|
||||
typeMap['char[]'] = 'string[]';
|
||||
typeMap['java.lang.String'] = "string";
|
||||
// typeMap['java.util.Date'] = 'any /*java.util.Date*/'
|
||||
// typeMap['java.util.List'] = 'any[] /*java.util.List*/'
|
||||
// typeMap['java.util.Set'] = 'any[] /*java.util.Set*/'
|
||||
// typeMap['java.util.Collection'] = 'any[] /*java.util.Collection*/'
|
||||
// typeMap['java.util.Map'] = 'Map<any, any> /*java.util.Map*/'
|
||||
// Sponge
|
||||
typeMap['Vectori'] = 'any /*Vector3i*/'
|
||||
typeMap['Vectord'] = 'any /*Vector3d*/'
|
||||
typeMap['Vectorf'] = 'any /*Vector3f*/'
|
||||
typeMap['Vector2i'] = 'any /*Vector2i*/'
|
||||
typeMap['Vector2d'] = 'any /*Vector2d*/'
|
||||
typeMap['Vector2f'] = 'any /*Vector2f*/'
|
||||
typeMap['Vector3i'] = 'any /*Vector3i*/'
|
||||
typeMap['Vector3d'] = 'any /*Vector3d*/'
|
||||
typeMap['Vector3f'] = 'any /*Vector3f*/'
|
||||
typeMap['Type'] = 'any /*Type*/'
|
||||
typeMap['Gson'] = 'any /*Gson*/'
|
||||
typeMap['Logger'] = 'any /*Logger*/'
|
||||
typeMap['MethodVisitor'] = 'any /*MethodVisitor*/'
|
||||
typeMap['ConfigurationNode'] = 'any /*ConfigurationNode*/'
|
||||
typeMap['TypeSerializerCollection'] = 'any /*TypeSerializerCollection*/'
|
||||
typeMap['Quaterniond'] = 'any /*Quaterniond*/'
|
||||
typeMap['Matrix2d'] = 'any /*Matrix2d*/'
|
||||
typeMap['Matrix3d'] = 'any /*Matrix3d*/'
|
||||
typeMap['Matrix4d'] = 'any /*Matrix4d*/'
|
||||
|
||||
function mappingType(type: string): string {
|
||||
let outType = typeMap[type] || type || 'any';
|
||||
if (outType.indexOf('.') != -1) {
|
||||
if (outType.startsWith('java.') || outType.startsWith('org.') || outType.startsWith('net.') || outType.startsWith('cn.')) {
|
||||
|
||||
} else {
|
||||
outType = `any /*${outType}*/`
|
||||
}
|
||||
}
|
||||
return outType.replace('function', 'function$');
|
||||
}
|
||||
|
||||
var args = process.argv.splice(2)
|
||||
|
||||
const suffix = 'd.ts'
|
||||
const inDir = `../docs/${args[0]}`
|
||||
const outDir = "./temp";
|
||||
const files = fs.readdirSync(inDir);
|
||||
let index = '';
|
||||
for (const file of files) {
|
||||
index += `/// <reference path="./${convertJson2TypeDefiend(file, outDir)}" />\n`;
|
||||
}
|
||||
fs.writeFileSync(`${outDir}/index.${suffix}`, index);
|
||||
@@ -1,79 +1,85 @@
|
||||
declare global {
|
||||
const __FILE__: string;
|
||||
const __LINE__: number;
|
||||
const __DIR__: string;
|
||||
let Packages: any;
|
||||
const __FILE__: string
|
||||
const __LINE__: number
|
||||
const __DIR__: string
|
||||
const Packages: any
|
||||
|
||||
function print(...message: any[]): void;
|
||||
function load(script: string | object);
|
||||
function loadWithNewGlobal(script: string | object);
|
||||
function exit(code?: number);
|
||||
function quit(code?: number);
|
||||
function JavaImporter(...className: string[]);
|
||||
function print(...message: any[]): void
|
||||
function load(script: string | object)
|
||||
function loadWithNewGlobal(script: string | object)
|
||||
function exit(code?: number)
|
||||
function quit(code?: number)
|
||||
function JavaImporter(...className: string[])
|
||||
|
||||
namespace Java {
|
||||
function type(clazz: string): any;
|
||||
function from(javaObj: any): any[];
|
||||
function to(array: any[]): any;
|
||||
function extend(...parentTypes: any[]);
|
||||
function type<T = any>(clazz: string): T
|
||||
function from<T = any>(javaObj: T[]): T[]
|
||||
function to<T = any>(array: T[], type?: T): T[]
|
||||
function extend(...parentTypes: any[]): any
|
||||
function synchronized(func: () => void, lock: any): Function
|
||||
function asJSONCompatible<T = any>(obj: T): T
|
||||
//@ts-ignore
|
||||
// function super(type: any);
|
||||
}
|
||||
|
||||
interface Error {
|
||||
readonly lineNumber?: number;
|
||||
readonly columnNumber?: number;
|
||||
readonly fileName?: string;
|
||||
dumpStack?: Function;
|
||||
printStackTrace?: Function;
|
||||
getStackTrace?: () => any[];
|
||||
readonly class?: any
|
||||
readonly lineNumber?: number
|
||||
readonly columnNumber?: number
|
||||
readonly fileName?: string
|
||||
dumpStack?: Function
|
||||
printStackTrace?: Function
|
||||
getStackTrace?: () => any[]
|
||||
}
|
||||
|
||||
interface String {
|
||||
trimLeft(): string;
|
||||
trimRight(): string;
|
||||
trimLeft(): string
|
||||
trimRight(): string
|
||||
}
|
||||
|
||||
interface Object {
|
||||
setPrototypeOf(obj: object, prototype: object): void;
|
||||
bindProperties(to: object, from: object): void;
|
||||
setPrototypeOf(obj: object, prototype: object): void
|
||||
bindProperties(to: object, from: object): void
|
||||
}
|
||||
|
||||
namespace NodeJS {
|
||||
interface Global {
|
||||
scope: string;
|
||||
logger: any;
|
||||
debug: boolean;
|
||||
level: string;
|
||||
eventCenter: EventEmitter;
|
||||
NashornEngineStartTime: number;
|
||||
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void;
|
||||
noop: () => void;
|
||||
console: Console;
|
||||
scope: string
|
||||
logger: any
|
||||
debug: boolean
|
||||
level: string
|
||||
NashornEngineStartTime: number
|
||||
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void
|
||||
noop: () => void
|
||||
console: Console
|
||||
}
|
||||
interface Process {
|
||||
on(event: string, listener: any): this
|
||||
emit(event: string, ...message: any): this
|
||||
}
|
||||
}
|
||||
var root: string;
|
||||
var base: Core;
|
||||
var ScriptEngineContextHolder: any;
|
||||
function engineLoad(str: string): any;
|
||||
const root: string
|
||||
const base: Core
|
||||
const ScriptEngineContextHolder: any
|
||||
function engineLoad(str: string | { script: string, name: string }): any
|
||||
interface Core {
|
||||
getClass(name: String): any;
|
||||
getProxyClass(): any;
|
||||
getInstance(): any;
|
||||
read(path: string): string;
|
||||
save(path: string, content: string): void;
|
||||
delete(path: string): void;
|
||||
getClass(name: String): any
|
||||
getProxyClass(): any
|
||||
getInstance(): any
|
||||
read(path: string): string
|
||||
save(path: string, content: string): void
|
||||
delete(path: string): void
|
||||
}
|
||||
interface Console {
|
||||
ex(err: Error): void;
|
||||
stack(err: Error): string[];
|
||||
sender(...args: any): void;
|
||||
console(...args: any): void;
|
||||
i18n(name: string, ...params: any[]): void;
|
||||
ex(err: Error): void
|
||||
stack(err: Error, color?: boolean): string[]
|
||||
sender(...args: any): void
|
||||
console(...args: any): void
|
||||
i18n(name: string, ...params: any[]): void
|
||||
}
|
||||
interface ProxyConstructor {
|
||||
newProxy<T extends object>(target: T, handler: ProxyHandler<T>): T;
|
||||
newProxy<T extends object>(target: T, handler: ProxyHandler<T>): T
|
||||
}
|
||||
}
|
||||
|
||||
export { };
|
||||
export { }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nodejs",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript nodejs package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,12 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.8.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/nashorn": "^0.7.0"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nukkit",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript nukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/nukkit-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.7.0",
|
||||
"@ccms/common": "^0.7.0",
|
||||
"@ccms/container": "^0.7.0"
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/common": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// <reference types="@ccms/types/dist/typings/nukkit" />
|
||||
/// <reference types="@javatypes/nukkit-api" />
|
||||
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
@@ -21,10 +21,8 @@ export class NukkitTaskManager implements task.TaskManager {
|
||||
}
|
||||
|
||||
export class NukkitTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = new NukkitRunnable({
|
||||
run: () => this.run()
|
||||
})
|
||||
submit(...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);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/ployfill",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript ployfill package",
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
@@ -14,13 +14,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/i18n": "^0.7.0",
|
||||
"@ccms/nashorn": "^0.7.0",
|
||||
"@ccms/i18n": "^0.8.2",
|
||||
"@ccms/nodejs": "^0.8.2",
|
||||
"core-js": "^3.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.8.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
|
||||
import '@ccms/nodejs'
|
||||
import i18n from '@ccms/i18n'
|
||||
let ployfillStartTime = new Date().getTime();
|
||||
i18n.initialize();
|
||||
console.i18n("ms.ployfill.initialize");
|
||||
require('./es5-ext');
|
||||
require('core-js');
|
||||
require('./node-shim');
|
||||
let ployfillStartTime = new Date().getTime()
|
||||
i18n.initialize()
|
||||
console.i18n("ms.ployfill.initialize")
|
||||
require('./es5-ext')
|
||||
require('./node-shim')
|
||||
require('core-js')
|
||||
//@ts-ignore
|
||||
process.on('exit', () => require.disable())
|
||||
global.setGlobal('Proxy', require('./proxy').Proxy)
|
||||
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
|
||||
global.setGlobal('Blob', require('blob-polyfill').Blob)
|
||||
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 });
|
||||
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 })
|
||||
|
||||
@@ -1,8 +1,37 @@
|
||||
global.setGlobal('process', {
|
||||
env: {
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
const ThreadGroup = Java.type("java.lang.ThreadGroup")
|
||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
|
||||
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
|
||||
|
||||
const threadCount = new AtomicInteger(0)
|
||||
const threadGroup = new ThreadGroup("@ccms/ployfill-micro-task")
|
||||
const microTaskPool = new ThreadPoolExecutor(
|
||||
10, 100, 60, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue(500),
|
||||
(run: any) => new Thread(threadGroup, run, "@ccms/micro-task-" + threadCount.incrementAndGet()),
|
||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
||||
)
|
||||
|
||||
class Process extends EventEmitter {
|
||||
env = {
|
||||
__noSuchProperty__: (prop) => {
|
||||
return Packages.java.lang.System.getenv(prop)
|
||||
}
|
||||
},
|
||||
platform: Packages.java.lang.System.getProperty("os.name")
|
||||
}, {})
|
||||
}
|
||||
platform = Packages.java.lang.System.getProperty("os.name")
|
||||
nextTick(func: Function) {
|
||||
microTaskPool.execute(func)
|
||||
}
|
||||
queueMicrotask(func: Function) {
|
||||
microTaskPool.execute(func)
|
||||
}
|
||||
exit(code: number) {
|
||||
process.emit('exit', code)
|
||||
microTaskPool.shutdown()
|
||||
}
|
||||
}
|
||||
global.setGlobal('process', new Process(), {})
|
||||
global.setGlobal('queueMicrotask', (func: any) => microTaskPool.execute(func), {})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/plugin",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,16 +19,16 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/js-yaml": "^3.12.3",
|
||||
"@types/js-yaml": "^3.12.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.7.0",
|
||||
"@ccms/common": "^0.7.0",
|
||||
"@ccms/container": "^0.7.0",
|
||||
"@ccms/i18n": "^0.7.0",
|
||||
"js-yaml": "^3.13.1"
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/common": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2",
|
||||
"@ccms/i18n": "^0.8.2",
|
||||
"js-yaml": "^3.14.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { plugin as pluginApi } from "@ccms/api"
|
||||
import { injectable, decorate } from "@ccms/container"
|
||||
import { interfaces } from './interfaces'
|
||||
import { METADATA_KEY } from './constants'
|
||||
@@ -7,16 +8,16 @@ import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata
|
||||
* MiaoScript plugin
|
||||
* @param metadata PluginMetadata
|
||||
*/
|
||||
export function plugin(metadata: interfaces.PluginMetadata) {
|
||||
export function plugin(metadata: pluginApi.PluginMetadata) {
|
||||
return function (target: any) {
|
||||
metadata.target = target
|
||||
metadata.type = "ioc"
|
||||
decorate(injectable(), target)
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target)
|
||||
const previousMetadata: Map<string, interfaces.PluginMetadata> = getPluginMetadatas()
|
||||
const previousMetadata: Map<string, pluginApi.PluginMetadata> = getPluginMetadatas()
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect)
|
||||
const previousSources: Map<string, interfaces.PluginMetadata> = getPluginSources()
|
||||
const previousSources: Map<string, pluginApi.PluginMetadata> = getPluginSources()
|
||||
previousSources.set(metadata.source.toString(), metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.souece, previousSources, Reflect)
|
||||
}
|
||||
@@ -78,23 +79,16 @@ export function config(metadata: interfaces.ConfigMetadata = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
function stage(metadata: interfaces.ExecMetadata = {}, stage: string) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key
|
||||
metadata.executor = key
|
||||
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
|
||||
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor)
|
||||
function stage(stage: string) {
|
||||
return (metadata: interfaces.ExecMetadata = {}) => {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key
|
||||
metadata.executor = key
|
||||
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
|
||||
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function load(metadata: interfaces.ExecMetadata = {}) {
|
||||
return stage(metadata, 'load')
|
||||
}
|
||||
|
||||
export function enable(metadata: interfaces.ExecMetadata = {}) {
|
||||
return stage(metadata, 'enable')
|
||||
}
|
||||
|
||||
export function disable(metadata: interfaces.ExecMetadata = {}) {
|
||||
return stage(metadata, 'disable')
|
||||
}
|
||||
export const load = stage('load')
|
||||
export const enable = stage('enable')
|
||||
export const disable = stage('disable')
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
import './scanner/file-scanner'
|
||||
import './loader/ioc-loader'
|
||||
import './loader/basic-loader'
|
||||
|
||||
export * from './manager'
|
||||
export * from './decorators'
|
||||
export * from './interfaces'
|
||||
|
||||
export {
|
||||
plugin as JSPlugin,
|
||||
cmd as Cmd,
|
||||
tab as Tab,
|
||||
listener as Listener,
|
||||
config as Config
|
||||
} from './decorators'
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { server, MiaoScriptConsole, event } from "@ccms/api";
|
||||
import { injectable, inject, postConstruct } from "@ccms/container";
|
||||
import { getPluginMetadata } from "./utils";
|
||||
import { server, MiaoScriptConsole, event, plugin } from "@ccms/api"
|
||||
import { injectable, inject, postConstruct } from "@ccms/container"
|
||||
import { getPluginMetadata } from "./utils"
|
||||
|
||||
export namespace interfaces {
|
||||
@injectable()
|
||||
export abstract class Plugin {
|
||||
public description: PluginMetadata;
|
||||
public logger: Console;
|
||||
export abstract class Plugin implements plugin.Plugin {
|
||||
public description: plugin.PluginMetadata
|
||||
public logger: Console
|
||||
@inject(server.Console)
|
||||
private Console: MiaoScriptConsole;
|
||||
private Console: MiaoScriptConsole
|
||||
|
||||
constructor() {
|
||||
this.description = getPluginMetadata(this)
|
||||
@@ -24,86 +24,49 @@ export namespace interfaces {
|
||||
public enable() { }
|
||||
public disable() { }
|
||||
}
|
||||
interface BaseMetadata {
|
||||
/**
|
||||
* 名称 为空则为对象名称
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
* 支持的服务器列表 为空则代表所有
|
||||
*/
|
||||
servers?: string[];
|
||||
}
|
||||
export interface PluginMetadata extends BaseMetadata {
|
||||
/**
|
||||
* 插件名称
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
prefix?: string;
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
version: string;
|
||||
/**
|
||||
* 插件版本
|
||||
*/
|
||||
author: string | string[];
|
||||
/**
|
||||
* 插件源文件 必须指定为 __filename
|
||||
*/
|
||||
source: string;
|
||||
/**
|
||||
* 插件类型 默认为 ioc 执行 MiaoScript 加载逻辑
|
||||
*/
|
||||
type?: string;
|
||||
/**
|
||||
* 插件本体
|
||||
*/
|
||||
target?: any;
|
||||
}
|
||||
export interface ExecMetadata extends BaseMetadata {
|
||||
export interface ExecMetadata extends plugin.BaseMetadata {
|
||||
/**
|
||||
* 执行器
|
||||
*/
|
||||
executor?: string;
|
||||
executor?: string
|
||||
}
|
||||
export interface CommandMetadata extends ExecMetadata {
|
||||
/**
|
||||
* 命令描述
|
||||
*/
|
||||
description?: string
|
||||
/**
|
||||
* 参数列表
|
||||
*/
|
||||
paramtypes?: string[];
|
||||
paramtypes?: string[]
|
||||
}
|
||||
export interface ListenerMetadata extends ExecMetadata {
|
||||
/**
|
||||
* 监听优先级
|
||||
*/
|
||||
priority?: event.EventPriority;
|
||||
priority?: event.EventPriority
|
||||
/**
|
||||
* 是否忽略已取消的事件
|
||||
*/
|
||||
ignoreCancel?: boolean;
|
||||
|
||||
ignoreCancel?: boolean
|
||||
}
|
||||
export interface ConfigMetadata extends BaseMetadata {
|
||||
export interface ConfigMetadata extends plugin.BaseMetadata {
|
||||
/**
|
||||
* 配置文件版本号
|
||||
*/
|
||||
version?: number;
|
||||
version?: number
|
||||
/**
|
||||
* 实体变量名称
|
||||
*/
|
||||
variable?: string;
|
||||
variable?: string
|
||||
/**
|
||||
* 配置文件格式 默认 yml
|
||||
*/
|
||||
format?: string;
|
||||
format?: string
|
||||
/**
|
||||
* 是否为只读(关闭时将不会自动保存)
|
||||
*/
|
||||
readonly?: boolean;
|
||||
readonly?: boolean
|
||||
}
|
||||
export type PluginLike = Plugin | string;
|
||||
export type PluginLike = Plugin | string
|
||||
}
|
||||
|
||||
29
packages/plugin/src/loader/basic-loader.ts
Normal file
29
packages/plugin/src/loader/basic-loader.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { plugin } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
|
||||
@provideSingleton(plugin.PluginLoader)
|
||||
export class BasicLoader implements plugin.PluginLoader {
|
||||
type: string = 'basic'
|
||||
|
||||
private pluginRequireMap: Map<string, any>
|
||||
|
||||
constructor() {
|
||||
this.pluginRequireMap = new Map()
|
||||
}
|
||||
require(loadMetadata: plugin.PluginLoadMetadata) {
|
||||
let metadata = loadMetadata.instance?.description
|
||||
if (metadata?.type == this.type) {
|
||||
loadMetadata.metadata = metadata
|
||||
loadMetadata.loaded = true
|
||||
this.pluginRequireMap.set(metadata.source.toString(), loadMetadata.instance)
|
||||
}
|
||||
return loadMetadata
|
||||
}
|
||||
build(metadata: plugin.PluginMetadata) {
|
||||
return this.pluginRequireMap.get(metadata.source.toString())
|
||||
}
|
||||
load(plugin: plugin.Plugin): void { }
|
||||
enable(plugin: plugin.Plugin): void { }
|
||||
disable(plugin: plugin.Plugin): void { }
|
||||
reload(plugin: plugin.Plugin): void { }
|
||||
}
|
||||
102
packages/plugin/src/loader/ioc-loader.ts
Normal file
102
packages/plugin/src/loader/ioc-loader.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { plugin, server } from "@ccms/api"
|
||||
import { inject, ContainerInstance, Container, provideSingleton } from "@ccms/container"
|
||||
|
||||
import { interfaces } from "../interfaces"
|
||||
import { getPluginStageMetadata, getPluginSources } from "../utils"
|
||||
|
||||
@provideSingleton(plugin.PluginLoader)
|
||||
export class IocLoader implements plugin.PluginLoader {
|
||||
type: string = 'ioc'
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
@inject(server.ServerType)
|
||||
private serverType: string
|
||||
|
||||
private pluginMetadataMap: Map<string, plugin.PluginMetadata>
|
||||
|
||||
constructor() {
|
||||
this.pluginMetadataMap = getPluginSources()
|
||||
}
|
||||
|
||||
require(loadMetadata: plugin.PluginLoadMetadata) {
|
||||
let metadata = this.pluginMetadataMap.get(loadMetadata.file.toString())
|
||||
if (metadata && metadata.type == this.type) {
|
||||
loadMetadata.metadata = metadata
|
||||
loadMetadata.loaded = true
|
||||
}
|
||||
return loadMetadata
|
||||
}
|
||||
|
||||
build(metadata: plugin.PluginMetadata) {
|
||||
if (!this.allowProcess(metadata.servers)) { return }
|
||||
let pluginInstance: plugin.Plugin
|
||||
try {
|
||||
this.bindPlugin(metadata)
|
||||
pluginInstance = this.container.getNamed<plugin.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (!(pluginInstance instanceof interfaces.Plugin)) {
|
||||
console.i18n('ms.plugin.manager.build.not.extends', { source: metadata.source })
|
||||
return
|
||||
}
|
||||
} catch (ex) {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: metadata.name, ex })
|
||||
console.ex(ex)
|
||||
}
|
||||
return pluginInstance
|
||||
}
|
||||
|
||||
load(plugin: plugin.Plugin): void {
|
||||
this.stage(plugin, 'load')
|
||||
}
|
||||
enable(plugin: plugin.Plugin): void {
|
||||
this.stage(plugin, 'enable')
|
||||
}
|
||||
disable(plugin: plugin.Plugin): void {
|
||||
this.stage(plugin, 'disable')
|
||||
}
|
||||
reload(plugin: plugin.Plugin): void {
|
||||
this.disable(plugin)
|
||||
//@ts-ignore
|
||||
require(plugin.description.source, { cache: false })
|
||||
this.load(plugin)
|
||||
this.enable(plugin)
|
||||
}
|
||||
|
||||
private bindPlugin(metadata: plugin.PluginMetadata) {
|
||||
try {
|
||||
let pluginInstance = this.container.getNamed<plugin.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (pluginInstance.description.source + '' !== metadata.source + '') {
|
||||
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{
|
||||
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 }
|
||||
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)
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.stage.exec.error", { plugin: pluginInstance.description.name, executor: stage.executor, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@ import { plugin, server, command, event } from '@ccms/api'
|
||||
import { inject, provideSingleton, Container, ContainerInstance } from '@ccms/container'
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata, getPluginConfigMetadata, getPluginStageMetadata, getPluginSources } from './utils'
|
||||
import { interfaces } from './interfaces'
|
||||
import { getConfigLoader } from './config'
|
||||
import { getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
|
||||
@@ -25,59 +25,129 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
private EventManager: event.Event
|
||||
|
||||
private initialized: boolean = false
|
||||
private pluginRequireMap: Map<string, any>
|
||||
private pluginInstanceMap: Map<string, interfaces.Plugin>
|
||||
private pluginMetadataMap: Map<string, interfaces.PluginMetadata>
|
||||
|
||||
private sacnnerMap: Map<string, plugin.PluginScanner>
|
||||
private loaderMap: Map<string, plugin.PluginLoader>
|
||||
|
||||
private instanceMap: Map<string, plugin.Plugin>
|
||||
private metadataMap: Map<string, plugin.PluginMetadata>
|
||||
|
||||
constructor() {
|
||||
this.sacnnerMap = new Map()
|
||||
this.loaderMap = new Map()
|
||||
|
||||
this.instanceMap = new Map()
|
||||
this.metadataMap = new Map()
|
||||
}
|
||||
|
||||
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 })
|
||||
this.pluginRequireMap = new Map()
|
||||
this.pluginInstanceMap = new Map()
|
||||
this.pluginMetadataMap = getPluginSources()
|
||||
let pluginScanner = this.container.getAll<plugin.PluginScanner>(plugin.PluginScanner)
|
||||
pluginScanner.forEach((scanner) => {
|
||||
console.debug(`loading plugin sacnner ${scanner.type}...`)
|
||||
this.sacnnerMap.set(scanner.type, scanner)
|
||||
})
|
||||
let pluginLoaders = this.container.getAll<plugin.PluginLoader>(plugin.PluginLoader)
|
||||
pluginLoaders.forEach((loader) => {
|
||||
console.debug(`loading plugin loader ${loader.type}...`)
|
||||
this.loaderMap.set(loader.type, loader)
|
||||
})
|
||||
this.initialized = true
|
||||
process.emit('plugin.initialize')
|
||||
}
|
||||
}
|
||||
|
||||
scan(folder: string): void {
|
||||
if (!folder) { throw new Error('plugin scan folder can\'t be empty!') }
|
||||
this.initialize()
|
||||
var plugin = fs.file(root, folder)
|
||||
var files = this.scanFolder(plugin)
|
||||
this.loadPlugins(files)
|
||||
for (const [, scanner] of this.sacnnerMap) {
|
||||
try {
|
||||
scanner.scan(folder).forEach(loadMetadata => {
|
||||
try {
|
||||
this.loadPlugin(scanner.load(loadMetadata))
|
||||
} catch (error) {
|
||||
console.error(`plugin scanner ${scanner.type} load ${loadMetadata.name} occurred error ${error}`)
|
||||
console.ex(error)
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(`plugin scanner ${scanner.type} occurred error ${error}`)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
process.emit('plugin.scan', folder)
|
||||
}
|
||||
|
||||
build(): void {
|
||||
this.buildPlugins()
|
||||
process.emit('plugin.build')
|
||||
}
|
||||
|
||||
private logStage(plugin: interfaces.Plugin, stage: string) {
|
||||
private logStage(plugin: plugin.Plugin, stage: string) {
|
||||
console.i18n("ms.plugin.manager.stage", { stage, plugin: plugin.description.name, version: plugin.description.version, author: plugin.description.author })
|
||||
}
|
||||
|
||||
private runPluginStage(plugin: interfaces.Plugin, stage: string, ext: Function) {
|
||||
this.logStage(plugin, i18n.translate(`ms.plugin.manager.stage.${stage}`))
|
||||
ext()
|
||||
this.runCatch(plugin, stage)
|
||||
this.runCatch(plugin, `${this.serverType}${stage}`)
|
||||
this.execPluginStage(plugin, stage)
|
||||
private runPluginStage(plugin: plugin.Plugin, stage: string, ext: Function) {
|
||||
if (!plugin) { throw new Error(`can't run runPluginStage ${stage} because plugin is ${plugin}`) }
|
||||
try {
|
||||
this.logStage(plugin, i18n.translate(`ms.plugin.manager.stage.${stage}`))
|
||||
ext()
|
||||
this.runCatch(plugin, stage)
|
||||
this.runCatch(plugin, `${this.serverType}${stage}`)
|
||||
plugin.description.loadMetadata.loader[stage](plugin)
|
||||
} catch (ex) {
|
||||
console.i18n("ms.plugin.manager.stage.exec.error", { plugin: plugin.description.name, executor: stage, error: ex })
|
||||
}
|
||||
}
|
||||
|
||||
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}!`) }
|
||||
try {
|
||||
for (const [, loader] of this.loaderMap) {
|
||||
try {
|
||||
if (loader.require(loadMetadata).loaded) {
|
||||
loadMetadata.loader = loader
|
||||
let metadata = loadMetadata.metadata
|
||||
this.metadataMap.set(metadata.name, metadata)
|
||||
metadata.loadMetadata = loadMetadata
|
||||
return metadata
|
||||
}
|
||||
} catch (error) {
|
||||
if (global.debug) {
|
||||
console.console(`§6Loader §b${loader.type} §6load §a${loadMetadata.file} §cerror. §4Err: §c${error}`)
|
||||
console.ex(error)
|
||||
} else {
|
||||
console.warn(`Loader ${loader.type} load ${loadMetadata.file} error. Err: ${error}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: loadMetadata.file, ex: error })
|
||||
console.ex(error)
|
||||
}
|
||||
console.console(`§6scanner: §b${loadMetadata.scanner.type} §ccan\'t load §6file §b${loadMetadata.file}. §eskip!`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件加载插件
|
||||
* @param file java.io.File
|
||||
*/
|
||||
loadFromFile(file: string): interfaces.Plugin {
|
||||
let metadata = this.loadPlugin(file)
|
||||
let plugin = this.buildPlugin(metadata && metadata.description ? metadata.description : this.pluginMetadataMap.get(file.toString()))
|
||||
loadFromFile(file: string, scanner = this.sacnnerMap.get('file')): plugin.Plugin {
|
||||
if (!file) { throw new Error('plugin file can\'t be undefiend!') }
|
||||
if (!scanner) { throw new Error('plugin scanner can\'t be undefiend!') }
|
||||
let metadata = this.loadPlugin(scanner.read(file))
|
||||
let plugin = metadata.loadMetadata.loader.build(metadata)
|
||||
this.load(plugin)
|
||||
this.enable(plugin)
|
||||
return plugin
|
||||
}
|
||||
|
||||
load(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => {
|
||||
this.runPluginStage(plugin, 'load', () => {
|
||||
this.loadConfig(plugin)
|
||||
})
|
||||
@@ -85,7 +155,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
|
||||
enable(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => {
|
||||
this.runPluginStage(plugin, 'enable', () => {
|
||||
this.registryCommand(plugin)
|
||||
this.registryListener(plugin)
|
||||
@@ -94,7 +164,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
|
||||
disable(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||
this.checkAndGet(args[0]).forEach((plugin: plugin.Plugin) => {
|
||||
this.runPluginStage(plugin, 'disable', () => {
|
||||
this.saveConfig(plugin)
|
||||
this.unregistryCommand(plugin)
|
||||
@@ -104,14 +174,18 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
|
||||
reload(...args: any[]): void {
|
||||
this.checkAndGet(args[0]).forEach((pl: interfaces.Plugin) => {
|
||||
this.checkAndGet(args[0]).forEach((pl: plugin.Plugin) => {
|
||||
this.disable(pl)
|
||||
this.loadFromFile(pl.description.source)
|
||||
this.loadFromFile(pl.description.source.toString(), pl.description.loadMetadata.scanner)
|
||||
})
|
||||
}
|
||||
|
||||
getPlugin(name: string) {
|
||||
return this.instanceMap.get(name)
|
||||
}
|
||||
|
||||
getPlugins() {
|
||||
return this.pluginInstanceMap
|
||||
return this.instanceMap
|
||||
}
|
||||
|
||||
private runCatch(pl: any, func: string) {
|
||||
@@ -123,65 +197,15 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private checkAndGet(name: string | interfaces.Plugin | undefined | any): Map<string, interfaces.Plugin> | interfaces.Plugin[] {
|
||||
if (name == this.pluginInstanceMap) { return this.pluginInstanceMap }
|
||||
if (typeof name == 'string' && this.pluginInstanceMap.has(name)) { return [this.pluginInstanceMap.get(name)] }
|
||||
if (name instanceof interfaces.Plugin) { return [name as interfaces.Plugin] }
|
||||
if (name.description || name.description.name) { return [name as interfaces.Plugin] }
|
||||
private checkAndGet(name: string | plugin.Plugin | undefined | any): Map<string, plugin.Plugin> | plugin.Plugin[] {
|
||||
if (name === undefined) throw new Error(`checkAndGet Plugin can't be undefiend!`)
|
||||
if (name == this.instanceMap) { return this.instanceMap }
|
||||
if (typeof name == 'string' && this.instanceMap.has(name)) { return [this.instanceMap.get(name)] }
|
||||
if (name instanceof interfaces.Plugin) { return [name as plugin.Plugin] }
|
||||
if (name.description?.name) { return [name as plugin.Plugin] }
|
||||
throw new Error(`Plugin ${JSON.stringify(name)} not exist!`)
|
||||
}
|
||||
|
||||
private scanFolder(folder: any): string[] {
|
||||
var files = []
|
||||
console.i18n('ms.plugin.manager.scan', { folder })
|
||||
this.checkUpdateFolder(folder)
|
||||
// must check file is exist maybe is a illegal symbolic link file
|
||||
fs.list(folder).forEach((file: any) => file.toFile().exists() ? files.push(file.toFile()) : void 0)
|
||||
return files
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新插件
|
||||
* @param path
|
||||
*/
|
||||
private checkUpdateFolder(path: any) {
|
||||
var update = fs.file(path, "update")
|
||||
if (!update.exists()) {
|
||||
update.mkdirs()
|
||||
}
|
||||
}
|
||||
|
||||
private loadPlugins(files: any[]): void {
|
||||
this.loadJsPlugins(files)
|
||||
}
|
||||
|
||||
/**
|
||||
* JS类型插件预加载
|
||||
*/
|
||||
private loadJsPlugins(files: any[]) {
|
||||
files.filter(file => file.name.endsWith(".js")).forEach(file => {
|
||||
try {
|
||||
this.loadPlugin(file)
|
||||
} catch (ex) {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: file.name, ex })
|
||||
console.ex(ex)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private loadPlugin(file: any) {
|
||||
this.updatePlugin(file)
|
||||
return this.createPlugin(file.toString())
|
||||
}
|
||||
|
||||
private updatePlugin(file: any) {
|
||||
var update = fs.file(fs.file(file.parentFile, 'update'), file.name)
|
||||
if (update.exists()) {
|
||||
console.i18n("ms.plugin.manager.build.update", { name: file.name })
|
||||
fs.move(update, file, true)
|
||||
}
|
||||
}
|
||||
|
||||
private allowProcess(servers: string[]) {
|
||||
// Not set servers -> allow
|
||||
if (!servers || !servers.length) return true
|
||||
@@ -195,63 +219,20 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private createPlugin(file: string) {
|
||||
//@ts-ignore
|
||||
let instance = require(file, { cache: false })
|
||||
this.pluginRequireMap.set(file, instance)
|
||||
return instance
|
||||
}
|
||||
|
||||
private buildPlugins() {
|
||||
let metadatas = []
|
||||
let pluginMetadatas = getPluginMetadatas()
|
||||
for (const [_, metadata] of pluginMetadatas) { metadatas.push(metadata) }
|
||||
for (const [_, instance] of this.pluginRequireMap) { if (instance.description) { this.buildPlugin(instance.description) } }
|
||||
for (const metadata of metadatas) {
|
||||
if (!this.allowProcess(metadata.servers)) { continue }
|
||||
this.buildPlugin(metadata)
|
||||
}
|
||||
}
|
||||
|
||||
private buildPlugin(metadata: interfaces.PluginMetadata) {
|
||||
let pluginInstance: interfaces.Plugin
|
||||
switch (metadata.type) {
|
||||
case "ioc":
|
||||
try {
|
||||
this.bindPlugin(metadata)
|
||||
pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (!(pluginInstance instanceof interfaces.Plugin)) {
|
||||
console.i18n('ms.plugin.manager.build.not.extends', { source: metadata.source })
|
||||
return
|
||||
}
|
||||
} catch (ex) {
|
||||
console.i18n("ms.plugin.manager.initialize.error", { name: metadata.name, ex })
|
||||
console.ex(ex)
|
||||
}
|
||||
break
|
||||
case "basic":
|
||||
pluginInstance = this.pluginRequireMap.get(metadata.source.toString())
|
||||
break
|
||||
default:
|
||||
throw new Error('§4不支持的插件类型 请检查加载器是否正常启用!')
|
||||
}
|
||||
this.pluginInstanceMap.set(metadata.name, pluginInstance)
|
||||
return pluginInstance
|
||||
}
|
||||
|
||||
private bindPlugin(metadata: interfaces.PluginMetadata) {
|
||||
try {
|
||||
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
||||
if (pluginInstance.description.source + '' !== metadata.source + '') {
|
||||
console.i18n('ms.plugin.manager.build.duplicate', { exists: pluginInstance.description.source, source: metadata.source })
|
||||
for (const [, metadata] of this.metadataMap) {
|
||||
let pluginInstance: plugin.Plugin
|
||||
if (!this.loaderMap.has(metadata.type)) {
|
||||
console.error(`§4无法加载插件 §c${metadata.name} §4请检查 §c${metadata.type} §4加载器是否正常启用!`)
|
||||
continue
|
||||
}
|
||||
this.container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
} catch{
|
||||
this.container.bind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
pluginInstance = this.loaderMap.get(metadata.type).build(metadata)
|
||||
if (!pluginInstance) { console.error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`); continue }
|
||||
this.instanceMap.set(metadata.name, pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
private loadConfig(plugin: interfaces.Plugin) {
|
||||
private loadConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
try {
|
||||
@@ -276,7 +257,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private saveConfig(plugin: interfaces.Plugin) {
|
||||
private saveConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
try {
|
||||
@@ -290,7 +271,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private registryCommand(pluginInstance: interfaces.Plugin) {
|
||||
private registryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||
for (const [_, cmd] of cmds) {
|
||||
@@ -303,7 +284,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private registryListener(pluginInstance: interfaces.Plugin) {
|
||||
private registryListener(pluginInstance: plugin.Plugin) {
|
||||
let events = getPluginListenerMetadata(pluginInstance)
|
||||
for (const event of events) {
|
||||
// ignore space listener
|
||||
@@ -313,28 +294,14 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private unregistryCommand(pluginInstance: interfaces.Plugin) {
|
||||
private unregistryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
cmds.forEach(cmd => {
|
||||
this.CommandManager.off(pluginInstance, cmd.name)
|
||||
})
|
||||
}
|
||||
|
||||
private unregistryListener(pluginInstance: interfaces.Plugin) {
|
||||
private unregistryListener(pluginInstance: plugin.Plugin) {
|
||||
this.EventManager.disable(pluginInstance)
|
||||
}
|
||||
|
||||
private execPluginStage(pluginInstance: interfaces.Plugin, stageName: string) {
|
||||
let stages = getPluginStageMetadata(pluginInstance, stageName)
|
||||
for (const stage of stages) {
|
||||
if (!this.allowProcess(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)
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.stage.exec.error", { plugin: pluginInstance.description.name, executor: stage.executor, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
54
packages/plugin/src/scanner/file-scanner.ts
Normal file
54
packages/plugin/src/scanner/file-scanner.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { plugin } from "@ccms/api"
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import { provideSingletonNamed } from "@ccms/container"
|
||||
|
||||
@provideSingletonNamed(plugin.PluginScanner, 'file')
|
||||
export class JSFileScanner implements plugin.PluginScanner {
|
||||
type: string = 'file'
|
||||
|
||||
scan(target: any): plugin.PluginLoadMetadata[] {
|
||||
return this.scanFolder(fs.concat(root, target)).map((file) => this.read(file))
|
||||
}
|
||||
|
||||
read(file: any): plugin.PluginLoadMetadata {
|
||||
return { file, type: this.type, scanner: this, loaded: false }
|
||||
}
|
||||
|
||||
load(metadata: plugin.PluginLoadMetadata): plugin.PluginLoadMetadata {
|
||||
if (metadata.type !== this.type) { return }
|
||||
this.updatePlugin(metadata.file)
|
||||
//@ts-ignore
|
||||
metadata.instance = require(metadata.file.toString(), { cache: false })
|
||||
return metadata
|
||||
}
|
||||
|
||||
private scanFolder(folder: any): string[] {
|
||||
var files = []
|
||||
console.i18n('ms.plugin.manager.scan', { folder })
|
||||
this.checkUpdateFolder(folder)
|
||||
// must check file is exist maybe is a illegal symbolic link file
|
||||
fs.list(folder).forEach((path: any) => {
|
||||
let file = path.toFile()
|
||||
if (file.exists() && file.getName().endsWith(".js")) {
|
||||
files.push(file)
|
||||
}
|
||||
})
|
||||
return files
|
||||
}
|
||||
|
||||
private checkUpdateFolder(path: any) {
|
||||
var update = fs.file(path, "update")
|
||||
if (!update.exists()) {
|
||||
update.mkdirs()
|
||||
}
|
||||
}
|
||||
|
||||
private updatePlugin(file: any) {
|
||||
var update = fs.file(fs.file(file.parentFile, 'update'), file.name)
|
||||
if (update.exists()) {
|
||||
console.i18n("ms.plugin.manager.build.update", { name: file.name })
|
||||
fs.move(update, file, true)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,78 +1,79 @@
|
||||
import { plugin } from '@ccms/api'
|
||||
import { interfaces } from './interfaces'
|
||||
import { METADATA_KEY } from './constants'
|
||||
|
||||
const pluginSourceCache = new Map<string, interfaces.PluginMetadata>();
|
||||
const pluginSourceCache = new Map<string, plugin.PluginMetadata>()
|
||||
|
||||
function getPlugins() {
|
||||
return [...getPluginMetadatas().values()].map((target) => target.target);
|
||||
return [...getPluginMetadatas().values()].map((target) => target.target)
|
||||
}
|
||||
|
||||
function getPlugin(name: string) {
|
||||
return getPluginMetadatas().get(name);
|
||||
return getPluginMetadatas().get(name)
|
||||
}
|
||||
|
||||
function getPluginSources() {
|
||||
let pluginSources: Map<string, interfaces.PluginMetadata> = Reflect.getMetadata(
|
||||
let pluginSources: Map<string, plugin.PluginMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.souece,
|
||||
Reflect
|
||||
) || pluginSourceCache;
|
||||
return pluginSources;
|
||||
) || pluginSourceCache
|
||||
return pluginSources
|
||||
}
|
||||
|
||||
function getPluginMetadatas() {
|
||||
let pluginMetadatas: Map<string, interfaces.PluginMetadata> = Reflect.getMetadata(
|
||||
let pluginMetadatas: Map<string, plugin.PluginMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.plugin,
|
||||
Reflect
|
||||
) || new Map<string, interfaces.PluginMetadata>();
|
||||
return pluginMetadatas;
|
||||
) || new Map<string, plugin.PluginMetadata>()
|
||||
return pluginMetadatas
|
||||
}
|
||||
|
||||
function getPluginMetadata(target: any) {
|
||||
let pluginMetadata: interfaces.PluginMetadata = Reflect.getMetadata(
|
||||
let pluginMetadata: plugin.PluginMetadata = Reflect.getMetadata(
|
||||
METADATA_KEY.plugin,
|
||||
target.constructor
|
||||
) || {};
|
||||
return pluginMetadata;
|
||||
) || {}
|
||||
return pluginMetadata
|
||||
}
|
||||
|
||||
function getPluginCommandMetadata(target: any) {
|
||||
let commandMetadata: Map<string, interfaces.CommandMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.cmd,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.CommandMetadata>();
|
||||
return commandMetadata;
|
||||
) || new Map<string, interfaces.CommandMetadata>()
|
||||
return commandMetadata
|
||||
}
|
||||
|
||||
function getPluginTabCompleterMetadata(target: any) {
|
||||
let tabcompleterMetadata: Map<string, interfaces.CommandMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.tab,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.CommandMetadata>();
|
||||
return tabcompleterMetadata;
|
||||
) || new Map<string, interfaces.CommandMetadata>()
|
||||
return tabcompleterMetadata
|
||||
}
|
||||
|
||||
function getPluginListenerMetadata(target: any) {
|
||||
let listnerMetadata: interfaces.ListenerMetadata[] = Reflect.getMetadata(
|
||||
METADATA_KEY.listener,
|
||||
target.constructor
|
||||
) || [];
|
||||
return listnerMetadata;
|
||||
) || []
|
||||
return listnerMetadata
|
||||
}
|
||||
|
||||
function getPluginConfigMetadata(target: any) {
|
||||
let configMetadata: Map<string, interfaces.ConfigMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.config,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.ConfigMetadata>();
|
||||
return configMetadata;
|
||||
) || new Map<string, interfaces.ConfigMetadata>()
|
||||
return configMetadata
|
||||
}
|
||||
|
||||
function getPluginStageMetadata(target: any, stage: string) {
|
||||
let stageMetadata: interfaces.ExecMetadata[] = Reflect.getMetadata(
|
||||
METADATA_KEY.stage[stage],
|
||||
target.constructor
|
||||
) || [];
|
||||
return stageMetadata;
|
||||
) || []
|
||||
return stageMetadata
|
||||
}
|
||||
|
||||
export {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ccms/plugins",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript plugins package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.7.0",
|
||||
"@ccms/container": "^0.7.0",
|
||||
"@ccms/plugin": "^0.7.0"
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2",
|
||||
"@ccms/plugin": "^0.8.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/// <reference types="@ccms/types/dist/typings/bukkit" />
|
||||
/// <reference types="@ccms/types/dist/typings/sponge" />
|
||||
/// <reference types="@ccms/types/dist/typings/bungee" />
|
||||
/// <reference types="@ccms/types/dist/typings/nukkit" />
|
||||
/// <reference types="@javatypes/bungee-api" />
|
||||
/// <reference types="@javatypes/spigot-api" />
|
||||
/// <reference types="@javatypes/sponge-api" />
|
||||
|
||||
import { server } from '@ccms/api';
|
||||
import { inject } from '@ccms/container';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// <reference types="@ccms/types/dist/typings/bukkit" />
|
||||
/// <reference types="@ccms/types/dist/typings/sponge" />
|
||||
/// <reference types="@ccms/types/dist/typings/bungee" />
|
||||
/// <reference types="@javatypes/bungee-api" />
|
||||
/// <reference types="@javatypes/spigot-api" />
|
||||
/// <reference types="@javatypes/sponge-api" />
|
||||
|
||||
import { server, plugin as pluginApi, channel, constants } from '@ccms/api'
|
||||
import { inject, optional } from '@ccms/container';
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
/// <reference types="@ccms/types/dist/typings/bukkit" />
|
||||
/// <reference types="@ccms/types/dist/typings/sponge" />
|
||||
/// <reference types="@ccms/types/dist/typings/bungee" />
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
|
||||
import { plugin as pluginApi, server, task, constants } from '@ccms/api'
|
||||
import { plugin, interfaces, cmd, tab, enable, config, disable } from '@ccms/plugin'
|
||||
@@ -43,6 +41,8 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
private appender: any
|
||||
private handler: any
|
||||
|
||||
private logCache: string[] = []
|
||||
|
||||
@config()
|
||||
private secret = { token: undefined }
|
||||
|
||||
@@ -54,6 +54,12 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
this.token = Java.type('java.util.UUID').randomUUID().toString()
|
||||
this.logger.console(`§6已生成随机Token: §3${this.token} §c重启后或重新生成后失效!`)
|
||||
}
|
||||
process.on('message', (msg) => {
|
||||
this.logCache.push(msg)
|
||||
if (this.logCache.length > 30) {
|
||||
this.logCache = this.logCache.slice(this.logCache.length - 30, this.logCache.length)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@cmd()
|
||||
@@ -103,13 +109,14 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
wait?.cancel()
|
||||
this.createSocketIOServer()
|
||||
this.startSocketIOServer()
|
||||
return
|
||||
}
|
||||
if (count++ > 30) {
|
||||
if (count++ > 5) {
|
||||
wait?.cancel()
|
||||
this.logger.console('§cNetty通道注入失败 §4所有功能将无法使用!')
|
||||
return
|
||||
}
|
||||
}).later(20).timer(40).submit()
|
||||
}).later(20).timer(20).submit()
|
||||
this.rootLogger = this.server.getRootLogger()
|
||||
}
|
||||
|
||||
@@ -117,8 +124,13 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
addLog4jForward() {
|
||||
if (this.rootLogger) {
|
||||
let AbstractAppender = Java.type('org.apache.logging.log4j.core.appender.AbstractAppender')
|
||||
let Level = Java.type('org.apache.logging.log4j.Level')
|
||||
let ProxyAppender = Java.extend(AbstractAppender, {
|
||||
append: (logEvent) => global.eventCenter.emit('log', logEvent.getMessage().getFormattedMessage())
|
||||
append: (logEvent) => {
|
||||
if (logEvent.level.intLevel() <= Level.INFO.intLevel()) {
|
||||
process.emit('message', logEvent.getMessage().getFormattedMessage())
|
||||
}
|
||||
}
|
||||
})
|
||||
this.appender = new ProxyAppender("ProxyLogger", null, null)
|
||||
this.appender.start()
|
||||
@@ -132,7 +144,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
if (this.rootLogger) {
|
||||
let AbstractHandler = Java.type('java.util.logging.Handler')
|
||||
let ProxyHandler = Java.extend(AbstractHandler, {
|
||||
publish: (record) => global.eventCenter.emit('log', record.getMessage()),
|
||||
publish: (record) => process.emit('message', record.getMessage()),
|
||||
flush: () => { },
|
||||
close: () => { }
|
||||
})
|
||||
@@ -141,15 +153,18 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
private LOGBACK_APPENDER_NAME = "NashornProxyAppender"
|
||||
|
||||
@enable({ servers: [constants.ServerType.Spring] })
|
||||
addLogbackForward() {
|
||||
if (this.rootLogger) {
|
||||
let AppenderBase = Java.type('ch.qos.logback.core.AppenderBase')
|
||||
let ProxyAppender = Java.extend(AppenderBase, {
|
||||
append: (logEvent) => global.eventCenter.emit('log', logEvent.getFormattedMessage())
|
||||
append: (logEvent) => process.emit('message', logEvent.getFormattedMessage())
|
||||
})
|
||||
this.appender = new ProxyAppender()
|
||||
this.appender.setName("NashornProxyAppender")
|
||||
this.appender.start()
|
||||
this.appender.setName(this.LOGBACK_APPENDER_NAME)
|
||||
this.appender.setContext(this.rootLogger.getLoggerContext())
|
||||
this.rootLogger.addAppender(this.appender)
|
||||
}
|
||||
@@ -158,7 +173,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
disable() {
|
||||
if (this.socketIOServer) {
|
||||
this.socketIOServer.close()
|
||||
global.eventCenter.removeAllListeners('log')
|
||||
process.removeAllListeners('message')
|
||||
}
|
||||
if (this.container.isBound(io.Instance)) {
|
||||
this.container.unbind(io.Instance)
|
||||
@@ -187,7 +202,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
@disable({ servers: [constants.ServerType.Spring] })
|
||||
removeLogbackForward() {
|
||||
try {
|
||||
this.rootLogger.detachAppender("NashornProxyAppender")
|
||||
this.rootLogger.detachAppender(this.LOGBACK_APPENDER_NAME)
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
@@ -203,7 +218,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
|
||||
startSocketIOServer() {
|
||||
let namespace = this.socketIOServer.of('/MiaoConsole')
|
||||
global.eventCenter.on('log', (msg) => namespace.emit('log', msg))
|
||||
process.on('message', (msg) => namespace.emit('log', msg))
|
||||
namespace.on('connect', (client: SocketIOSocket) => {
|
||||
if (!this.token) {
|
||||
this.logger.console(`§6客户端 §b${client.id} §a请求连接 §4服务器尚未设置 Token 无法连接!`)
|
||||
@@ -211,72 +226,93 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
client.disconnect(true)
|
||||
return
|
||||
}
|
||||
this.logger.console(`§6客户端 §b${client.id} §a请求连接 §4Token: §c********`)
|
||||
if (this.token != client.handshake.query.token) {
|
||||
this.logger.console(`§6客户端 §b${client.id} §4无效请求 请提供正确Token后再次连接!`)
|
||||
this.logger.console(`§6客户端 §b${client.id} §c无效请求 §4请提供正确Token后再次连接!`)
|
||||
client.emit('unauthorized')
|
||||
client.disconnect(true)
|
||||
return
|
||||
}
|
||||
this.initWebSocketClient(client)
|
||||
this.logCache.forEach(msg => client.emit('log', msg))
|
||||
this.logger.console(`§6客户端 §b${client.id} §a新建连接 ${this.rootLogger ? '启动日志转发' : '§4转发日志启动失败'}...`)
|
||||
client.on('type', (fn) => {
|
||||
fn && fn(this.serverType)
|
||||
client.emit('log', `Currect Server Version is ${this.server.getVersion()}`)
|
||||
})
|
||||
client.on('command', (cmd) => {
|
||||
setTimeout(() => this.server.dispatchConsoleCommand(cmd), 0)
|
||||
client.emit('log', `§6命令: §b${cmd} §a执行成功!`)
|
||||
})
|
||||
client.on('exec', (code) => {
|
||||
try {
|
||||
client.emit('log', this.runCode(code, namespace, client))
|
||||
} catch (ex) {
|
||||
client.emit('log', `§4代码执行异常 错误: ${ex}\n${console.stack(ex).join('\n')}`)
|
||||
}
|
||||
})
|
||||
client.on('edit', (file: string, fn) => {
|
||||
fn && fn(base.read(file), suffixMap[file.split('.', 2)[1]])
|
||||
})
|
||||
client.on('save', (name: string, content: string, fn) => {
|
||||
this.logger.console(`§6客户端 §b${client.id} §6请求更新插件 §a${name} §6...`)
|
||||
let file = fs.concat(root, this.pluginFolder, name + '.js')
|
||||
if (!fs.exists(file)) { return fn('§6插件 §a' + name + ' §6尚未安装 §c请先创建空文件 或安装插件!') }
|
||||
try {
|
||||
base.save(file, content)
|
||||
this.pluginManager.reload(name)
|
||||
fn('§6插件 §a' + name + ' §6更新成功!')
|
||||
} catch (error) {
|
||||
this.logger.error(error)
|
||||
fn('§6插件 §a' + name + ' §4更新异常 错误: ' + error)
|
||||
}
|
||||
})
|
||||
client.on('ls', (file: string, fn) => {
|
||||
let dir = fs.file(file);
|
||||
if (!dir.isDirectory()) {
|
||||
return fn(undefined, `${file} 不是一个目录!`)
|
||||
}
|
||||
fn(fs.list(dir))
|
||||
})
|
||||
client.on('error', (error) => {
|
||||
this.logger.console(`§6客户端 §b${client.id} §c触发异常: ${error}`)
|
||||
})
|
||||
}
|
||||
|
||||
private initWebSocketClient(client: SocketIOSocket) {
|
||||
client.on('type', (fn) => {
|
||||
fn && fn(this.serverType)
|
||||
client.emit('log', `Currect Server Version is ${this.server.getVersion()}`)
|
||||
})
|
||||
client.on('command', (cmd) => {
|
||||
setTimeout(() => this.server.dispatchConsoleCommand(cmd), 0)
|
||||
client.emit('log', `§6命令: §b${cmd} §a执行成功!`)
|
||||
})
|
||||
client.on('tabComplate', (input, index, callback) => {
|
||||
callback && callback(this.server.tabComplete(this.server.getConsoleSender(), input, index))
|
||||
})
|
||||
client.on('exec', (code) => {
|
||||
try {
|
||||
client.emit('log', this.runCode(code, client.nsp, client))
|
||||
} catch (ex) {
|
||||
client.emit('log', `§4代码执行异常 错误: ${ex}\n${console.stack(ex).join('\n')}`)
|
||||
}
|
||||
})
|
||||
client.on('edit', (file: string, fn) => {
|
||||
fn && fn(base.read(file), suffixMap[file.split('.', 2)[1]])
|
||||
})
|
||||
client.on('save', (name: string, content: string, fn) => {
|
||||
this.logger.console(`§6客户端 §b${client.id} §6请求更新插件 §a${name} §6...`)
|
||||
let file = fs.concat(root, this.pluginFolder, name + '.js')
|
||||
if (!fs.exists(file)) { return fn('§6插件 §a' + name + ' §6尚未安装 §c请先创建空文件 或安装插件!') }
|
||||
try {
|
||||
base.save(file, content)
|
||||
this.pluginManager.reload(name)
|
||||
fn('§6插件 §a' + name + ' §6更新成功!')
|
||||
} catch (error) {
|
||||
this.logger.error(error)
|
||||
})
|
||||
client.on('disconnect', () => {
|
||||
this.logger.console(`§6客户端 §b${client.id} §c断开连接...`)
|
||||
})
|
||||
fn('§6插件 §a' + name + ' §4更新异常 错误: ' + error)
|
||||
}
|
||||
})
|
||||
client.on('ls', (file: string, fn) => {
|
||||
let dir = fs.file(file)
|
||||
if (!dir.isDirectory()) {
|
||||
return fn(undefined, `${file} 不是一个目录!`)
|
||||
}
|
||||
fn(fs.list(dir))
|
||||
})
|
||||
client.on('error', (error) => {
|
||||
this.logger.console(`§6客户端 §b${client.id} §c触发异常: ${error}`)
|
||||
this.logger.error(error)
|
||||
})
|
||||
client.on('disconnect', () => {
|
||||
this.logger.console(`§6客户端 §b${client.id} §c断开连接...`)
|
||||
})
|
||||
}
|
||||
|
||||
private runCode(code: string, namespace: any, client: any) {
|
||||
let tfunc = new Function('namespace', 'client', `
|
||||
var reflect = require('@ccms/common/dist/reflect');
|
||||
var tempconcent = '';
|
||||
function print(text) {
|
||||
tempconcent += text + "\\n"
|
||||
}
|
||||
var result = eval(${JSON.stringify(code)});
|
||||
return tempconcent + '§a返回结果: §r'+ result
|
||||
`)
|
||||
return this.task.callSyncMethod(() => tfunc.apply(this, [namespace, client])) + ''
|
||||
let paramNames = [
|
||||
'namespace',
|
||||
'client',
|
||||
'reflect',
|
||||
'container',
|
||||
'pluginManager'
|
||||
]
|
||||
let params = [
|
||||
namespace,
|
||||
client,
|
||||
reflect,
|
||||
this.container,
|
||||
this.pluginManager
|
||||
]
|
||||
let tfunc = new Function(
|
||||
...paramNames,
|
||||
`var api = require('@ccms/api');
|
||||
if (this.serverType == "spring") {
|
||||
var dbm = container.get(api.database.DataBaseManager)
|
||||
var db = dbm.getMainDatabase()
|
||||
var bf = base.getInstance().getAutowireCapableBeanFactory()
|
||||
}
|
||||
return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
||||
return this.task.callSyncMethod(() => tfunc.apply(this, params)) + ''
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// <reference types="@ccms/types" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
|
||||
import { task, server } from "@ccms/api";
|
||||
import { inject } from "@ccms/container";
|
||||
|
||||
30
packages/plugins/src/MiaoProtocol.ts
Normal file
30
packages/plugins/src/MiaoProtocol.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { task, server, constants } from "@ccms/api";
|
||||
import { inject } from "@ccms/container";
|
||||
import { plugin, interfaces, cmd } from "@ccms/plugin";
|
||||
|
||||
import http from '@ccms/common/dist/http'
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
@plugin({ name: 'MiaoProtocol', prefix: 'MPTL', version: '1.0.0', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||
export class MiaoProtocol extends interfaces.Plugin {
|
||||
@inject(server.Server)
|
||||
private server: server.Server;
|
||||
@inject(task.TaskManager)
|
||||
private taskManager: task.TaskManager;
|
||||
|
||||
private pipeline: any
|
||||
|
||||
enable() {
|
||||
let count = 0
|
||||
let wait = this.taskManager.create(() => {
|
||||
this.pipeline = this.server.getNettyPipeline()
|
||||
if (this.pipeline) {
|
||||
wait.cancel()
|
||||
} else if (count++ > 30) {
|
||||
wait.cancel()
|
||||
this.logger.console('§cNetty通道注入失败 §4所有功能将无法使用!')
|
||||
}
|
||||
}).later(20).timer(40).submit()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { plugin as pluginApi, task, server } from '@ccms/api'
|
||||
|
||||
import { Translate } from '@ccms/i18n'
|
||||
import { inject } from '@ccms/container';
|
||||
import { inject, DefaultContainer as container } from '@ccms/container'
|
||||
import { interfaces, plugin, cmd, tab } from '@ccms/plugin'
|
||||
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
import http from '@ccms/common/dist/http'
|
||||
|
||||
let help = [
|
||||
@@ -19,7 +20,7 @@ let help = [
|
||||
'§6/mpm §arun §e<JS代码> §6- §3运行JS代码',
|
||||
'§6/mpm §adeploy §e<插件名称> §6- §3发布插件',
|
||||
'§6/mpm §crestart §6- §4重启MiaoScript脚本引擎'
|
||||
];
|
||||
]
|
||||
|
||||
let langMap = {
|
||||
'main.command.not.exists': '§4未知的子命令: §c{command}',
|
||||
@@ -53,20 +54,20 @@ let fallbackMap = langMap
|
||||
@plugin({ name: 'MiaoScriptPackageManager', prefix: 'PM', version: '1.0.1', author: 'MiaoWoo', source: __filename })
|
||||
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
@inject(pluginApi.PluginManager)
|
||||
private pluginManager: pluginApi.PluginManager;
|
||||
private pluginManager: pluginApi.PluginManager
|
||||
@inject(task.TaskManager)
|
||||
private taskManager: task.TaskManager;
|
||||
private taskManager: task.TaskManager
|
||||
@inject(server.ServerType)
|
||||
private serverType: string;
|
||||
private serverType: string
|
||||
@inject(server.Server)
|
||||
private server: server.Server
|
||||
@inject(pluginApi.PluginFolder)
|
||||
private pluginFolder: string;
|
||||
private pluginFolder: string
|
||||
|
||||
private packageCache: any[] = [];
|
||||
private packageNameCache: string[] = [];
|
||||
|
||||
private translate: Translate;
|
||||
private translate: Translate
|
||||
|
||||
load() {
|
||||
this.translate = new Translate({
|
||||
@@ -78,7 +79,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
|
||||
@cmd()
|
||||
mpm(sender: any, command: string, args: string[]) {
|
||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit();
|
||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit()
|
||||
}
|
||||
|
||||
i18n(sender: any, name: string, params?: any) {
|
||||
@@ -90,64 +91,64 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
if (!this[cmdKey]) {
|
||||
this.i18n(sender, 'main.command.not.exists', { command: args[0] })
|
||||
this.i18n(sender, 'main.command.help.tip', { command })
|
||||
return;
|
||||
return
|
||||
}
|
||||
args.shift()
|
||||
this[cmdKey](sender, ...args);
|
||||
this[cmdKey](sender, ...args)
|
||||
}
|
||||
|
||||
cmdhelp(sender: any) {
|
||||
this.logger.sender(sender, help);
|
||||
this.logger.sender(sender, help)
|
||||
}
|
||||
|
||||
cmdload(sender: any, name: string) {
|
||||
let pluginFile = fs.concat(__dirname + '', name);
|
||||
let pluginFile = fs.concat(__dirname + '', name)
|
||||
if (!fs.exists(pluginFile)) {
|
||||
this.i18n(sender, 'plugin.not.exists', { name: `${name}(${pluginFile})` })
|
||||
return;
|
||||
return
|
||||
}
|
||||
this.pluginManager.loadFromFile(fs.file(pluginFile));
|
||||
this.pluginManager.loadFromFile(fs.file(pluginFile))
|
||||
}
|
||||
|
||||
cmdlist(sender: any, type: string = 'cloud') {
|
||||
if (type == "i" || type == "install") {
|
||||
this.i18n(sender, 'list.install.header')
|
||||
this.pluginManager.getPlugins().forEach((plugin) => {
|
||||
this.i18n(sender, 'list.install.body', plugin.description);
|
||||
this.i18n(sender, 'list.install.body', plugin.description)
|
||||
})
|
||||
} else {
|
||||
this.i18n(sender, 'list.header')
|
||||
for (var pkgName in this.packageCache) {
|
||||
this.i18n(sender, 'list.body', this.packageCache[pkgName]);
|
||||
this.i18n(sender, 'list.body', this.packageCache[pkgName])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cmdinstall(sender: any, name: string) {
|
||||
if (!name) { return this.i18n(sender, 'plugin.name.empty') }
|
||||
this.download(sender, name);
|
||||
this.download(sender, name)
|
||||
}
|
||||
|
||||
cmdupdate(sender: any, name: string) {
|
||||
if (name) {
|
||||
this.update(sender, name);
|
||||
this.update(sender, name)
|
||||
} else {
|
||||
this.updateRepo(sender)
|
||||
}
|
||||
}
|
||||
|
||||
cmdupgrade(sender: any, name: string) {
|
||||
if (!name) { return this.i18n(sender, 'upgrade.confirm'); }
|
||||
if (!name) { return this.i18n(sender, 'upgrade.confirm') }
|
||||
if (name == "comfirm") {
|
||||
let enginePath = fs.path(fs.file(fs.concat(root, 'node_modules', '@ccms')))
|
||||
if (enginePath.startsWith(root)) {
|
||||
base.delete(enginePath);
|
||||
this.cmdrestart(sender);
|
||||
base.delete(enginePath)
|
||||
this.cmdrestart(sender)
|
||||
}
|
||||
}
|
||||
if (this.checkPlugin(sender, name)) {
|
||||
this.update(sender, name);
|
||||
this.pluginManager.reload(name);
|
||||
this.update(sender, name)
|
||||
this.pluginManager.reload(name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +162,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
cmdreload(sender: any, name: string) {
|
||||
name = name || this.description.name
|
||||
if (this.checkPlugin(sender, name)) {
|
||||
this.pluginManager.reload(name);
|
||||
this.pluginManager.reload(name)
|
||||
this.i18n(sender, 'plugin.reload.finish', { name })
|
||||
}
|
||||
}
|
||||
@@ -184,33 +185,58 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
return
|
||||
}
|
||||
try {
|
||||
this.logger.sender(sender, '§6Reloading §3MiaoScript Engine...');
|
||||
ScriptEngineContextHolder.disableEngine();
|
||||
Packages.java.lang.System.gc();
|
||||
ScriptEngineContextHolder.enableEngine();
|
||||
this.logger.sender(sender, '§3MiaoScript Engine §6Reload §aSuccessful...');
|
||||
this.logger.sender(sender, '§6Reloading §3MiaoScript Engine...')
|
||||
ScriptEngineContextHolder.disableEngine()
|
||||
Packages.java.lang.System.gc()
|
||||
ScriptEngineContextHolder.enableEngine()
|
||||
this.logger.sender(sender, '§3MiaoScript Engine §6Reload §aSuccessful...')
|
||||
} catch (ex) {
|
||||
this.logger.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex);
|
||||
this.logger.sender(sender, this.logger.stack(ex));
|
||||
this.logger.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex)
|
||||
this.logger.sender(sender, this.logger.stack(ex))
|
||||
}
|
||||
}
|
||||
|
||||
cmdrun(sender: any, ...args: any[]) {
|
||||
try {
|
||||
let script = args.join(' ');
|
||||
let script = args.join(' ')
|
||||
this.i18n(sender, 'run.script', { script })
|
||||
let result = eval(script);
|
||||
let result = this.runCode(script, sender)
|
||||
this.i18n(sender, 'run.result', { result: result == undefined ? this.translate.translate('run.noresult') : result + '' })
|
||||
} catch (ex) {
|
||||
this.logger.sender(sender, this.logger.stack(ex));
|
||||
this.logger.sender(sender, this.logger.stack(ex))
|
||||
}
|
||||
}
|
||||
|
||||
private runCode(code: string, sender: any) {
|
||||
let paramNames = [
|
||||
'sender',
|
||||
'reflect',
|
||||
'container',
|
||||
'pluginManager'
|
||||
]
|
||||
let params = [
|
||||
sender,
|
||||
reflect,
|
||||
container,
|
||||
this.pluginManager
|
||||
]
|
||||
let tfunc = new Function(
|
||||
...paramNames,
|
||||
`var api = require('@ccms/api');
|
||||
if (this.serverType == "spring") {
|
||||
var dbm = container.get(api.database.DataBaseManager)
|
||||
var db = dbm.getMainDatabase()
|
||||
var df = base.getInstance().getAutowireCapableBeanFactory()
|
||||
}
|
||||
return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
||||
return tfunc.apply(this, params) + ''
|
||||
}
|
||||
|
||||
cmddeploy(sender: any, name: any) {
|
||||
if (!process.env.AccessToken) { return this.i18n(sender, 'deploy.token.not.exists') }
|
||||
this.taskManager.create(() => {
|
||||
if (this.checkPlugin(sender, name)) {
|
||||
let plugin: interfaces.Plugin = this.pluginManager.getPlugins().get(name);
|
||||
let plugin: pluginApi.Plugin = this.pluginManager.getPlugins().get(name)
|
||||
let result = http.post("http://ms.yumc.pw/api/plugin/deploy?access_token=" + process.env.AccessToken, {
|
||||
name,
|
||||
author: plugin.description.author,
|
||||
@@ -224,7 +250,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
|
||||
update(sender: any, name: string) {
|
||||
if (this.checkCloudPlugin(sender, name)) {
|
||||
this.download(sender, name, true);
|
||||
this.download(sender, name, true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,25 +262,25 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
case "list":
|
||||
return ["install", "cloud"]
|
||||
case "install":
|
||||
return this.packageNameCache;
|
||||
return this.packageNameCache
|
||||
case "update":
|
||||
case "upgrade":
|
||||
case "load":
|
||||
case "unload":
|
||||
case "reload":
|
||||
case "deploy":
|
||||
return [...this.pluginManager.getPlugins().keys()];
|
||||
return [...this.pluginManager.getPlugins().keys()]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateRepo(sender: any) {
|
||||
this.taskManager.create(() => {
|
||||
let result = http.get('http://ms.yumc.pw/api/plugin/list');
|
||||
for (const pl of result.data) { this.packageCache[pl.name] = pl; }
|
||||
this.packageNameCache = Object.keys(this.packageCache);
|
||||
let result = http.get('http://ms.yumc.pw/api/plugin/list')
|
||||
for (const pl of result.data) { this.packageCache[pl.name] = pl }
|
||||
this.packageNameCache = Object.keys(this.packageCache)
|
||||
this.i18n(sender, 'cloud.update.finish', { length: this.packageNameCache.length })
|
||||
}).async().submit();
|
||||
}).async().submit()
|
||||
}
|
||||
|
||||
download(sender: any, name: string, update: boolean = false) {
|
||||
|
||||
232
packages/plugins/src/MiaoSpring.ts
Normal file
232
packages/plugins/src/MiaoSpring.ts
Normal file
@@ -0,0 +1,232 @@
|
||||
/// <reference types="@javatypes/tomcat" />
|
||||
/// <reference types="@javatypes/spring-web" />
|
||||
|
||||
import { constants, database, plugin, web } from "@ccms/api"
|
||||
import { inject, ContainerInstance, Container, JSClass, postConstruct } from "@ccms/container"
|
||||
import { JSPlugin, interfaces, cmd } from "@ccms/plugin"
|
||||
import { DataBase, DataBaseManager } from '@ccms/database'
|
||||
import { Server, Context, RequestHandler, Controller, Get, Post, Param, Body } from '@ccms/web'
|
||||
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
|
||||
@JSPlugin({ name: 'MiaoSpring', prefix: 'MSpring', version: '1.0.1', author: 'MiaoWoo', servers: [constants.ServerType.Spring], source: __filename })
|
||||
export class MiaoSpring extends interfaces.Plugin {
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
@inject(plugin.PluginManager)
|
||||
private pluginManager: plugin.PluginManager
|
||||
@inject(database.DataBaseManager)
|
||||
private databaseManager: DataBaseManager
|
||||
@inject(web.Server)
|
||||
private webServer: Server
|
||||
|
||||
@JSClass('org.springframework.http.HttpStatus')
|
||||
private HttpStatus: org.springframework.http.HttpStatus
|
||||
|
||||
private ResponseEntity = org.springframework.http.ResponseEntity
|
||||
|
||||
private mainDatabase: DataBase
|
||||
private mappings: Set<string>
|
||||
|
||||
@cmd()
|
||||
mspring(sender: any) {
|
||||
this.pluginManager.reload(this)
|
||||
this.logger.sender(sender, "§a插件重载完成!")
|
||||
}
|
||||
|
||||
load() {
|
||||
this.mainDatabase = this.databaseManager.getMainDatabase()
|
||||
this.mappings = new Set()
|
||||
}
|
||||
|
||||
enable() {
|
||||
this.registryDefault()
|
||||
this.registryPages()
|
||||
this.registryDatabase()
|
||||
}
|
||||
|
||||
registryMapping(path: string, handler: RequestHandler) {
|
||||
this.mappings.add(path)
|
||||
this.webServer.registryMapping(path, handler)
|
||||
}
|
||||
|
||||
registryDefault() {
|
||||
const foundMap = ["/node_modules/amis/sdk/sdk.js", 'https://houtai.baidu.com/v2/jssdk', "/node_modules/amis/sdk/sdk.css", 'https://houtai.baidu.com/v2/csssdk']
|
||||
this.webServer.registryInterceptor({
|
||||
name: 'RedirectHandle',
|
||||
preHandle: (ctx: Context) => {
|
||||
const index = foundMap.indexOf(ctx.request.getRequestURI())
|
||||
if (index != -1) {
|
||||
return this.ResponseEntity.status(this.HttpStatus.FOUND).header('Location', foundMap[index + 1]).build()
|
||||
}
|
||||
}
|
||||
})
|
||||
this.webServer.registryInterceptor({
|
||||
name: 'StaticHandle',
|
||||
preHandle: (ctx: Context) => {
|
||||
let type = ctx.headers['Accept'] || ''
|
||||
if (type == '*/*' || type.includes('text/css') || type.includes('text/html')) {
|
||||
let filePath = fs.concat(root, 'wwwroot', (ctx.request.getRequestURI() == '/' ? 'index.html' : ctx.request.getRequestURI()))
|
||||
let fileType = 'text/html;charset=utf-8'
|
||||
if (!fs.exists(filePath)) { filePath = filePath + '.html' }
|
||||
if (fs.exists(filePath)) {
|
||||
if (filePath.endsWith('.js')) { fileType = 'application/javascript' }
|
||||
if (filePath.endsWith('.css')) { fileType = 'text/css' }
|
||||
return this.ResponseEntity.ok().header('Content-Type', fileType).body(base.read(filePath))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
this.registryMapping('/api/eval', (ctx: Context) => {
|
||||
try {
|
||||
return { status: 200, data: this.runCode(ctx.body + ''), msg: '代码执行成功!' }
|
||||
} catch (error) {
|
||||
return { status: 500, data: console.stack(error, false), msg: '代码执行异常!' }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private registryPages() {
|
||||
this.registryMapping('/api/page/list', () => {
|
||||
return { status: 0, data: { rows: this.mainDatabase.query('SELECT `id`, `type`, `name`, `content` FROM `pages` WHERE `deleted` = 0') } }
|
||||
})
|
||||
this.registryMapping('/api/page/get', (ctx: Context) => {
|
||||
let name = decodeURIComponent(`${ctx.params.name}`)
|
||||
let varable = undefined
|
||||
if (!name) { return { status: 400, msg: '名称不能为空!' } }
|
||||
if (name.includes('|')) {
|
||||
const temp = `${name}`.split('|')
|
||||
name = temp[0]
|
||||
varable = temp[1].replace(/'/ig, '"')
|
||||
}
|
||||
let result = this.mainDatabase.query<any>('SELECT content FROM `pages` WHERE name = ?', name)
|
||||
if (!result.length) { return { status: 404, msg: `'页面配置 ${name} 不存在!` } }
|
||||
let content = result[0].content
|
||||
if (varable) {
|
||||
let varObj = JSON.parse(varable)
|
||||
for (const key in varObj) {
|
||||
content = content.replace(new RegExp(`{{${key}}}`, 'ig'), varObj[key])
|
||||
}
|
||||
}
|
||||
return { status: 0, data: JSON.parse(content) }
|
||||
})
|
||||
this.registryMapping('/api/page/add', (ctx: Context) => {
|
||||
let body = ctx.body
|
||||
if (typeof body.content !== "string") { body.content = JSON.stringify(body.content) }
|
||||
this.mainDatabase.update("INSERT INTO `pages`(`type`, `name`, `content`) VALUES (?, ?, ?)", body.type || 1, body.name, body.content)
|
||||
return { status: 0, msg: `${body.name} 新增成功!` }
|
||||
})
|
||||
this.registryMapping('/api/page/update', (ctx: Context) => {
|
||||
if (!ctx.params.id) { return { status: 400, msg: 'ID 不能为空!' } }
|
||||
const body = ctx.body
|
||||
if (typeof body.content !== "string") { body.content = JSON.stringify(body.content) }
|
||||
this.mainDatabase.update("UPDATE `pages` SET `name` = ?, `content` = ? WHERE id = ?", body.name, body.content, ctx.params.id)
|
||||
return { status: 0, msg: `${body.name} 更新成功!` }
|
||||
})
|
||||
this.registryMapping('/api/page/delete', (ctx: Context) => {
|
||||
if (!ctx.params.name) { return { status: 400, msg: '页面 名称 不能为空!' } }
|
||||
this.mainDatabase.update("UPDATE `pages` SET `name` = CONCAT(name, '_deleted'), deleted = 1 WHERE name = ?", ctx.params.name)
|
||||
return { status: 0, msg: `${ctx.params.name} 删除成功!` }
|
||||
})
|
||||
}
|
||||
|
||||
private configTable = "config"
|
||||
|
||||
private registryDatabase() {
|
||||
this.registryMapping('/api/config/list', (ctx: Context) => {
|
||||
return { status: 0, data: this.mainDatabase.query('SELECT id, name, label, url, driver, username, password FROM `' + this.configTable + '` WHERE deleted = 0 AND type = ?', ctx.params.type || 0) }
|
||||
})
|
||||
this.registryMapping('/api/config/get', (ctx: Context) => {
|
||||
let name = ctx.params.name
|
||||
if (!name) { return { status: 400, msg: '名称不能为空!' } }
|
||||
let result = this.mainDatabase.query('SELECT id, name, label, url, driver, username, password FROM `' + this.configTable + '` WHERE `name` = ?', name)
|
||||
if (!result.length) { return { status: 404, msg: `配置 ${name} 不存在!` } }
|
||||
return { status: 0, data: result[0] }
|
||||
})
|
||||
this.registryMapping('/api/config/add', (ctx: Context) => {
|
||||
let body = ctx.body
|
||||
if (!body.name) { return { status: 400, msg: '名称不能为空!' } }
|
||||
this.mainDatabase.update(
|
||||
'INSERT INTO `' + this.configTable + '`(`type`, `name`, `label`, `url`, `driver`, `username`, `password`) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
ctx.params.type || 0, body.name, body.label || '', body.url, body.driver || '', body.username || '', body.password || ''
|
||||
)
|
||||
return { status: 0, msg: `配置 ${body.name} 新增成功!` }
|
||||
})
|
||||
this.registryMapping('/api/config/update', (ctx: Context) => {
|
||||
if (!ctx.params.id) { return { status: 400, msg: 'ID 不能为空!' } }
|
||||
let body = ctx.body
|
||||
this.mainDatabase.update(
|
||||
'UPDATE `' + this.configTable + '` SET `name` = ?, `label` = ?, `url` = ?, `driver` = ?, `username` = ?, `password` = ? WHERE `id` = ?',
|
||||
body.name, body.label || '', body.url, body.driver || '', body.username || '', body.password || '', ctx.params.id
|
||||
)
|
||||
return { status: 0, msg: `配置 ${body.name} 更新成功!` }
|
||||
})
|
||||
}
|
||||
|
||||
private runCode(code: string) {
|
||||
let paramNames = [
|
||||
'beanFactory',
|
||||
'mainDatabase',
|
||||
'reflect',
|
||||
'container',
|
||||
'pluginManager'
|
||||
]
|
||||
let params = [
|
||||
this.mainDatabase,
|
||||
reflect,
|
||||
this.container,
|
||||
this.pluginManager
|
||||
]
|
||||
let tfunc = new Function(
|
||||
...paramNames,
|
||||
`var api = require('@ccms/api');
|
||||
return eval(${JSON.stringify(code)});`)
|
||||
return tfunc.apply(this, params)
|
||||
}
|
||||
|
||||
disable() {
|
||||
Object.keys(this.mappings).forEach((r) => this.webServer.unregistryMapping(r))
|
||||
}
|
||||
}
|
||||
|
||||
class Plugin {
|
||||
id: number
|
||||
name: string
|
||||
source: string
|
||||
}
|
||||
|
||||
@Controller()
|
||||
class PluginController {
|
||||
@inject(plugin.PluginManager)
|
||||
private pluginManager: plugin.PluginManager
|
||||
@inject(database.DataBaseManager)
|
||||
private databaseManager: DataBaseManager
|
||||
|
||||
private mainDB: DataBase
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
this.mainDB = this.databaseManager.getMainDatabase()
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(@Param('install') install: boolean) {
|
||||
if (install) {
|
||||
return { status: 200, data: [...this.pluginManager.getPlugins().values()].map((plugin) => plugin.description), msg: '插件列表获取成功!' }
|
||||
} else {
|
||||
return { status: 200, data: this.mainDB.query<Plugin>("SELECT name FROM plugins WHERE deleted = 0") }
|
||||
}
|
||||
}
|
||||
@Post()
|
||||
deploy(@Body() info: Plugin) {
|
||||
let plugin = this.mainDB.query<Plugin>("SELECT name FROM plugins WHERE name = ?", info.name)
|
||||
if (plugin.length == 0) {
|
||||
this.mainDB.update("INSERT INTO `plugins`(`name`, `source`) VALUES (?, ?)", info.name, info.source)
|
||||
return { status: 200, msg: `插件 ${info.name} 新增成功!` }
|
||||
} else {
|
||||
this.mainDB.update("UPDATE `plugins` SET `source` = ? WHERE id = ?", info.source, plugin[0].id)
|
||||
return { status: 200, msg: `插件 ${info.name} 更新成功!` }
|
||||
}
|
||||
}
|
||||
}
|
||||
39
packages/plugins/src/MiaoWeb.ts
Normal file
39
packages/plugins/src/MiaoWeb.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { constants, web } from "@ccms/api"
|
||||
import { inject } from "@ccms/container"
|
||||
import { plugin, interfaces } from "@ccms/plugin"
|
||||
import { Controller, Get, Server, Body, Post, Cookie, Header, Param } from "@ccms/web"
|
||||
|
||||
@plugin({ name: 'MiaoWeb', version: '1.0.0', author: 'MiaoWoo', servers: [constants.ServerType.Spring], source: __filename })
|
||||
export class MiaoWeb extends interfaces.Plugin {
|
||||
@inject(web.Server)
|
||||
private webServer: Server
|
||||
|
||||
enable() {
|
||||
this.webServer.registryController(TestController)
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.webServer.unregistryController(TestController)
|
||||
}
|
||||
}
|
||||
|
||||
@Controller()
|
||||
export class TestController {
|
||||
@Get()
|
||||
public get() {
|
||||
return 'test'
|
||||
}
|
||||
@Post()
|
||||
public post(@Body() body: any,
|
||||
@Cookie('test') testCookie,
|
||||
@Header('Accept') testHeader,
|
||||
@Param("name") param) {
|
||||
return {
|
||||
body,
|
||||
testCookie,
|
||||
testHeader,
|
||||
param
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
215
packages/plugins/src/SearchRanking.ts
Normal file
215
packages/plugins/src/SearchRanking.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
/// <reference types="@javatypes/spring-data-redis" />
|
||||
|
||||
import { constants, plugin as pluginApi, amqp, server, web } from '@ccms/api'
|
||||
import { plugin, interfaces, cmd } from '@ccms/plugin'
|
||||
import { AmqpAdmin, ConnectionFactoryAdapter, AmqpManager } from '@ccms/amqp'
|
||||
import { inject, Autowired, ContainerInstance, Container } from '@ccms/container'
|
||||
import { Server, Controller, Get, Param, METADATA_KEY } from '@ccms/web'
|
||||
|
||||
const SearchRankingAmqpAdmin = Symbol('SearchRanking-AmqpAdmin')
|
||||
|
||||
const EXCHANGE_NAME = `search.ranking.${process.env.SPRING_CLOUD_CONFIG_PROFILE || 'dev'}`
|
||||
const QUEUE_NAME = `search.ranking.${process.env.SPRING_CLOUD_CONFIG_PROFILE || 'dev'}`
|
||||
const ROUTER_KEY = `search.ranking.${process.env.SPRING_CLOUD_CONFIG_PROFILE || 'dev'}`
|
||||
|
||||
@plugin({ name: SearchRanking.name, version: SearchRanking.version, author: SearchRanking.author, servers: SearchRanking.servers, source: __filename })
|
||||
export class SearchRanking extends interfaces.Plugin {
|
||||
public static version = '1.0.0'
|
||||
public static author = 'MiaoWoo'
|
||||
public static servers = [constants.ServerType.Spring]
|
||||
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
@inject(pluginApi.PluginManager)
|
||||
private pluginManager: pluginApi.PluginManager
|
||||
@inject(amqp.Manager)
|
||||
private amqpManager: AmqpManager
|
||||
@inject(server.Server)
|
||||
private Server: server.Server
|
||||
@inject(web.Server)
|
||||
private webServer: Server
|
||||
|
||||
@Autowired()
|
||||
private redisTemplate: org.springframework.data.redis.core.RedisTemplate<string, any>
|
||||
|
||||
private amqpAdmin: AmqpAdmin
|
||||
private listener: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
|
||||
load() {
|
||||
let connection = new ConnectionFactoryAdapter({
|
||||
url: 'amqp://rabbitmq.c.sixi.com:5672',
|
||||
username: 'root',
|
||||
password: 'SixiMQ2018@'
|
||||
})
|
||||
let template = this.amqpManager.createTemplate(connection)
|
||||
this.amqpAdmin = this.amqpManager.createAdmin(template)
|
||||
}
|
||||
|
||||
enable() {
|
||||
this.amqpAdmin.declareQueueAndBindExchange(QUEUE_NAME, EXCHANGE_NAME, ROUTER_KEY)
|
||||
this.amqpAdmin.declareBinding(QUEUE_NAME, 'client.topic.exchange', `cmd_res.${ROUTER_KEY}`)
|
||||
this.listener = this.amqpAdmin.createContainer<string>(QUEUE_NAME, (content, _message, _channel) => {
|
||||
let searchResult = JSON.parse(content)
|
||||
if (searchResult.type == "company") {
|
||||
this.logger.info(content)
|
||||
return
|
||||
}
|
||||
this.redisTemplate.opsForValue().set(searchResult.reqData.cacheKey, searchResult)
|
||||
this.logger.sender(this.Server.getConsoleSender(), `§6查询任务完成! §b关键词: §r${searchResult.reqData.keywords}`)
|
||||
})
|
||||
this.container.bind(SearchRankingAmqpAdmin).toConstantValue(this.amqpAdmin)
|
||||
this.listener.start()
|
||||
this.webServer.registryController(SearchRankingController)
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.container.unbind(SearchRankingAmqpAdmin)
|
||||
this.listener.stop()
|
||||
this.webServer.unregistryController(SearchRankingController)
|
||||
}
|
||||
|
||||
@cmd()
|
||||
sr(sender: any, cmd: string, args: string[]) {
|
||||
let cmdKey = 'cmd' + (args[0] || 'help')
|
||||
if (!this[cmdKey]) {
|
||||
this.logger.sender(sender, `§4子命令 ${args[0]} 不存在!`)
|
||||
return
|
||||
}
|
||||
args.shift()
|
||||
this[cmdKey](sender, ...args)
|
||||
}
|
||||
|
||||
cmdrun(sender: any, ...args: string[]) {
|
||||
sender.sendMessage(eval(args.join(' ')))
|
||||
}
|
||||
|
||||
cmdreload() {
|
||||
this.pluginManager.reload(this)
|
||||
}
|
||||
|
||||
cmdsearch(sender: any, keyword: string, type: "sale" | "normal" = "sale", time: number) {
|
||||
this.logger.sender(sender, this.container.getNamed<SearchRankingController>(METADATA_KEY.Controller, SearchRankingController.name).cacheAndSearch(keyword, type, time)?.msg)
|
||||
}
|
||||
}
|
||||
|
||||
@Controller({ path: '/api', name: SearchRankingController.name })
|
||||
class SearchRankingController {
|
||||
@Autowired()
|
||||
private redisTemplate: org.springframework.data.redis.core.RedisTemplate<string, any>
|
||||
|
||||
@inject(SearchRankingAmqpAdmin)
|
||||
private amqpAdmin: AmqpAdmin
|
||||
|
||||
@Get()
|
||||
public search(
|
||||
@Param({ name: 'keyword', require: true, message: '查询关键词不得为空!' }) keyword: string,
|
||||
@Param("type") type: string = 'normal',
|
||||
@Param('time') time: number = 60 * 60 * 24 * 15
|
||||
) {
|
||||
return this.cacheAndSearch(keyword, type as any, time * 1000)
|
||||
}
|
||||
|
||||
@Get("/search/ranking")
|
||||
public searchRanking(
|
||||
@Param({ name: 'keyword', require: true, message: '查询关键词不得为空!' }) keyword: string,
|
||||
@Param("shopName") shopName: string = 'normal',
|
||||
@Param("type") type: string = 'normal',
|
||||
@Param('time') time: number = 60 * 60 * 24 * 15
|
||||
) {
|
||||
return this.sendSearchRankingCmd(keyword, shopName, type as any, time * 1000)
|
||||
}
|
||||
|
||||
@Get('/search/company')
|
||||
public searchCompany(
|
||||
@Param('url') url: string
|
||||
) {
|
||||
this.amqpAdmin.getTemplate().convertAndSend('client.topic.exchange', 'cmd_req', {
|
||||
cmd: 'scout._1688CompanyInfo',
|
||||
data: {
|
||||
type: 'company',
|
||||
url: url,
|
||||
cacheKey: 'SearchRanking:company'
|
||||
},
|
||||
resRouteSuffix: ROUTER_KEY,
|
||||
target: {}
|
||||
})
|
||||
}
|
||||
|
||||
public cacheAndSearch(keyword: string, type: string = "sale", time: number = 15 * 24 * 60 * 60 * 1000) {
|
||||
let cacheKey = this.getCacheKey(keyword, type)
|
||||
if (this.redisTemplate.hasKey(cacheKey)) {
|
||||
let lastSearchTime = this.redisTemplate.opsForValue().get(cacheKey)
|
||||
if (Date.now() - lastSearchTime > time) {
|
||||
return this.createKeyworkSearch(keyword, type)
|
||||
}
|
||||
let lastSearchKey = this.getResultCacheKey(keyword, type, lastSearchTime)
|
||||
if (!this.redisTemplate.hasKey(lastSearchKey)) {
|
||||
return { status: 202, msg: `关键词: ${keyword} 排名类型: ${type} 缓存Key: ${lastSearchKey} 查询任务尚未完成...` }
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
msg: `关键词: ${keyword} 排名类型: ${type} 查询时间: ${new Date(lastSearchTime).toLocaleString()} 查询已完成!`,
|
||||
data: this.redisTemplate.opsForValue().get(lastSearchKey)
|
||||
}
|
||||
}
|
||||
return this.createKeyworkSearch(keyword, type)
|
||||
}
|
||||
|
||||
private createKeyworkSearch(keyword: string, type: string) {
|
||||
let cacheDate = Date.now()
|
||||
this.redisTemplate.opsForValue().set(this.getCacheKey(keyword, type), cacheDate)
|
||||
this.sendSearchCmd(keyword, type, cacheDate)
|
||||
return { status: 201, msg: `关键词: ${keyword} 排名类型: ${type} 查询任务以创建...`, createTime: cacheDate }
|
||||
}
|
||||
|
||||
private createRankingSearch(keyword: string, shopName: string, type: string) {
|
||||
let cacheDate = Date.now()
|
||||
this.redisTemplate.opsForValue().set(this.getCacheKey(keyword, type), cacheDate)
|
||||
this.sendSearchRankingCmd(keyword, shopName, type, cacheDate)
|
||||
return { status: 201, msg: `关键词: ${keyword} 店铺名称: ${shopName} 排名类型: ${type} 查询任务以创建...`, createTime: cacheDate }
|
||||
}
|
||||
|
||||
private sendSearchCmd(keywords: string, type: string, dateCache: number) {
|
||||
this.amqpAdmin.getTemplate().convertAndSend('client.topic.exchange', 'cmd_req', {
|
||||
cmd: 'scout._1688Search',
|
||||
data: {
|
||||
keywords: keywords,
|
||||
parameter: type == "sale" ? {
|
||||
descendOrder: true,
|
||||
sortType: 'va_rmdarkgmv30rt',
|
||||
button_click: 'top'
|
||||
} : {},
|
||||
cacheKey: this.getResultCacheKey(keywords, type, dateCache)
|
||||
},
|
||||
resRouteSuffix: ROUTER_KEY,
|
||||
target: {}
|
||||
})
|
||||
}
|
||||
|
||||
private sendSearchRankingCmd(keywords: string, shopName: string, type: string, cacheTime: number) {
|
||||
this.amqpAdmin.getTemplate().convertAndSend('client.topic.exchange', 'cmd_req', {
|
||||
cmd: 'scout._1688Ranking',
|
||||
data: {
|
||||
keywords: keywords,
|
||||
selector: {
|
||||
shopName
|
||||
},
|
||||
cacheKey: this.getResultCacheKey(keywords, type, cacheTime),
|
||||
cacheTime
|
||||
},
|
||||
resRouteSuffix: ROUTER_KEY,
|
||||
target: {}
|
||||
})
|
||||
}
|
||||
/**
|
||||
* 获得关键词+类型的上次查询时间
|
||||
* @param keywords 关键词
|
||||
* @param type 类型
|
||||
*/
|
||||
private getCacheKey(keywords: string, type: string) {
|
||||
return `SearchRanking:${keywords}:${type}`
|
||||
}
|
||||
private getResultCacheKey(keywords: string, type: string, date: number) {
|
||||
return `SearchRanking:${keywords}:${type}:${date}`
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/sponge",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,13 +19,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/sponge-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.7.0",
|
||||
"@ccms/common": "^0.7.0",
|
||||
"@ccms/container": "^0.7.0"
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/common": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,80 +1,80 @@
|
||||
import { command, plugin } from "@ccms/api";
|
||||
import { inject, provideSingleton } from "@ccms/container";
|
||||
import { command, plugin } from "@ccms/api"
|
||||
import { inject, provideSingleton } from "@ccms/container"
|
||||
|
||||
let Sponge = Java.type('org.spongepowered.api.Sponge');
|
||||
let Text = Java.type('org.spongepowered.api.text.Text');
|
||||
var CommandCallable = Java.type('org.spongepowered.api.command.CommandCallable');
|
||||
var CommandResult = Java.type('org.spongepowered.api.command.CommandResult');
|
||||
var Optional = Java.type('java.util.Optional');
|
||||
let Sponge = Java.type('org.spongepowered.api.Sponge')
|
||||
let Text = Java.type('org.spongepowered.api.text.Text')
|
||||
var CommandCallable = Java.type('org.spongepowered.api.command.CommandCallable')
|
||||
var CommandResult = Java.type('org.spongepowered.api.command.CommandResult')
|
||||
var Optional = Java.type('java.util.Optional')
|
||||
|
||||
@provideSingleton(command.Command)
|
||||
export class SpongeCommand extends command.Command {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
private commandMapping: any[] = [];
|
||||
private commandMapping: any[] = []
|
||||
|
||||
create(plugin: any, command: string) {
|
||||
let commandKey = this.getCommandKey(plugin, command);
|
||||
let commandCallable = new SimpleCommandCallable(command);
|
||||
this.commandMapping[commandKey] = Sponge.getCommandManager().register(this.pluginInstance, commandCallable.callable, command, commandKey).orElse(null);
|
||||
return commandCallable;
|
||||
let commandKey = this.getCommandKey(plugin, command)
|
||||
let commandCallable = new SimpleCommandCallable(command)
|
||||
this.commandMapping[commandKey] = Sponge.getCommandManager().register(this.pluginInstance, commandCallable.callable, command, commandKey).orElse(null)
|
||||
return commandCallable
|
||||
}
|
||||
remove(plugin: any, command: string) {
|
||||
var commandKey = this.getCommandKey(plugin, command);
|
||||
var commandKey = this.getCommandKey(plugin, command)
|
||||
if (this.commandMapping[commandKey]) {
|
||||
Sponge.getCommandManager().removeMapping(this.commandMapping[commandKey]);
|
||||
delete this.commandMapping[commandKey];
|
||||
Sponge.getCommandManager().removeMapping(this.commandMapping[commandKey])
|
||||
delete this.commandMapping[commandKey]
|
||||
}
|
||||
}
|
||||
onCommand(plugin: any, command: any, executor: Function) {
|
||||
command.setExecutor(super.setExecutor(plugin, command, executor));
|
||||
onCommand(plugin: plugin.Plugin, command: any, executor: Function) {
|
||||
command.setExecutor(super.setExecutor(plugin, command, executor))
|
||||
}
|
||||
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||
command.setTabCompleter(super.setTabCompleter(plugin, command, tabCompleter));
|
||||
onTabComplete(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
|
||||
command.setTabCompleter(super.setTabCompleter(plugin, command, tabCompleter))
|
||||
}
|
||||
|
||||
private getCommandKey(plugin: any, command: string) {
|
||||
return plugin.description.name.toLowerCase() + ":" + command;
|
||||
return plugin.description.name.toLowerCase() + ":" + command
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleCommandCallable {
|
||||
public callable: any;
|
||||
private name: string;
|
||||
private executor: Function;
|
||||
private tabCompleter: Function;
|
||||
public callable: any
|
||||
private name: string
|
||||
private executor: Function
|
||||
private tabCompleter: Function
|
||||
|
||||
constructor(command: string, description: string = '暂无描述!') {
|
||||
this.name = command;
|
||||
this.name = command
|
||||
this.callable = new CommandCallable({
|
||||
//CommandResult process(CommandSource source, String arguments) throws CommandException;
|
||||
//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(" ").filter(e => e))) ? CommandResult.success() : CommandResult.empty()
|
||||
},
|
||||
//List<String> getSuggestions(CommandSource source, String arguments, @Nullable Location<World> targetPosition) throws CommandException;
|
||||
//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(" ").filter(e => e)))
|
||||
},
|
||||
//boolean testPermission(CommandSource source);
|
||||
//boolean testPermission(CommandSource source)
|
||||
testPermission: () => {
|
||||
return true;
|
||||
return true
|
||||
},
|
||||
//Optional<Text> getShortDescription(CommandSource source);
|
||||
//Optional<Text> getShortDescription(CommandSource source)
|
||||
getShortDescription: () => {
|
||||
return Optional.of(Text.of(description));
|
||||
return Optional.of(Text.of(description))
|
||||
},
|
||||
//Optional<Text> getHelp(CommandSource source);
|
||||
//Optional<Text> getHelp(CommandSource source)
|
||||
getHelp: () => {
|
||||
return Optional.of(Text.of(""));
|
||||
return Optional.of(Text.of(""))
|
||||
},
|
||||
//Text getUsage(CommandSource source);
|
||||
//Text getUsage(CommandSource source)
|
||||
getUsage: () => {
|
||||
return Text.of('');
|
||||
return Text.of('')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
setExecutor = (executor: Function) => this.executor = executor;
|
||||
setTabCompleter = (tabCompleter: Function) => this.tabCompleter = tabCompleter;
|
||||
setExecutor = (executor: Function) => this.executor = executor
|
||||
setTabCompleter = (tabCompleter: Function) => this.tabCompleter = tabCompleter
|
||||
toString = () => `Sponge SimpleCommandCallable(${this.name})`
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/// <reference types="@ccms/types/dist/typings/sponge" />
|
||||
/// <reference types="@javatypes/sponge-api" />
|
||||
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
import { server, constants } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container';
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
|
||||
const Sponge = org.spongepowered.api.Sponge;
|
||||
const TextSerializers = org.spongepowered.api.text.serializer.TextSerializers;
|
||||
const File = Java.type("java.io.File");
|
||||
const Sponge = org.spongepowered.api.Sponge
|
||||
const TextSerializers = org.spongepowered.api.text.serializer.TextSerializers
|
||||
const File = Java.type("java.io.File")
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
export class SpongeServer implements server.Server {
|
||||
private pluginsFolder: string;
|
||||
private pipeline: any;
|
||||
private rootLogger: any;
|
||||
export class SpongeServer extends server.ReflectServer {
|
||||
private pluginsFolder: string
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this.pluginsFolder = new File(base.getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getCanonicalPath()
|
||||
this.reflect()
|
||||
}
|
||||
|
||||
getPlayer(name: string) {
|
||||
@@ -37,22 +35,25 @@ export class SpongeServer implements server.Server {
|
||||
if (typeof sender === 'string') {
|
||||
sender = this.getPlayer(sender)
|
||||
}
|
||||
return Sponge.getCommandManager().process(sender, command).getQueryResult()
|
||||
return Sponge.getCommandManager().process(sender, command).getQueryResult().get() != 0
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getQueryResult()
|
||||
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getQueryResult().get() != 0
|
||||
}
|
||||
getPluginsFolder(): string {
|
||||
return this.pluginsFolder;
|
||||
return this.pluginsFolder
|
||||
}
|
||||
getNativePluginManager() {
|
||||
return Sponge.getPluginManager() as any;
|
||||
return Sponge.getPluginManager() as any
|
||||
}
|
||||
getDedicatedServer() {
|
||||
return reflect.on(Sponge.getServer()).get()
|
||||
}
|
||||
getNettyPipeline() {
|
||||
return this.pipeline;
|
||||
return this.pipeline
|
||||
}
|
||||
getRootLogger() {
|
||||
return this.rootLogger;
|
||||
return this.rootLogger
|
||||
}
|
||||
sendJson(sender: string | any, json: string): void {
|
||||
if (typeof sender === "string") {
|
||||
@@ -60,37 +61,4 @@ export class SpongeServer implements server.Server {
|
||||
}
|
||||
sender.sendMessage(TextSerializers.JSON.deserialize(json))
|
||||
}
|
||||
private reflect() {
|
||||
let consoleServer = reflect.on(Sponge.getServer()).get()
|
||||
this.reflectPipeline(consoleServer)
|
||||
this.reflectRootLogger(consoleServer)
|
||||
}
|
||||
private reflectPipeline(consoleServer: any) {
|
||||
let connection: any;
|
||||
let promise: any;
|
||||
for (const method of constants.Reflect.Method.getServerConnection) {
|
||||
try {
|
||||
connection = reflect.on(consoleServer).call(method).get()
|
||||
if (connection.class.name.indexOf('NetworkSystem') !== -1) { break; }
|
||||
connection = undefined;
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||
try {
|
||||
promise = reflect.on(connection).get(field).get().get(0);
|
||||
if (promise.class.name.indexOf('Promise') !== -1) { break; }
|
||||
promise = undefined;
|
||||
} catch (error) { }
|
||||
}
|
||||
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||
}
|
||||
private reflectRootLogger(consoleServer: any) {
|
||||
try {
|
||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
||||
} catch (error) {
|
||||
console.error("Can't found rootLogger!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton, postConstruct } from '@ccms/container';
|
||||
import { inject, provideSingleton, postConstruct } from '@ccms/container'
|
||||
|
||||
const Sponge = Java.type("org.spongepowered.api.Sponge");
|
||||
const Task = Java.type("org.spongepowered.api.scheduler.Task");
|
||||
const Consumer = Java.type('java.util.function.Consumer');
|
||||
const Callable = Java.type('java.util.concurrent.Callable');
|
||||
const TimeUnit = Java.type('java.util.concurrent.TimeUnit');
|
||||
const Sponge = Java.type("org.spongepowered.api.Sponge")
|
||||
const Task = Java.type("org.spongepowered.api.scheduler.Task")
|
||||
const Consumer = Java.type('java.util.function.Consumer')
|
||||
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 {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private syncExecutor: any;
|
||||
private pluginInstance: any
|
||||
private syncExecutor: any
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
@@ -19,8 +19,8 @@ export class SpongeTaskManager implements task.TaskManager {
|
||||
}
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new SpongeTask(this.pluginInstance, func);
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') }
|
||||
return new SpongeTask(this.pluginInstance, func)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
// @ts-ignore
|
||||
@@ -32,10 +32,8 @@ export class SpongeTaskManager implements task.TaskManager {
|
||||
}
|
||||
|
||||
export class SpongeTask extends task.Task {
|
||||
submit(): task.Cancelable {
|
||||
let run = Task.builder().execute(new Consumer({
|
||||
accept: () => this.run()
|
||||
}));
|
||||
submit(...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) }
|
||||
if (this.interval) { run.intervalTicks(this.interval) }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/spring",
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.2",
|
||||
"description": "MiaoScript spring package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,12 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.2"
|
||||
"typescript": "^3.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.7.0",
|
||||
"@ccms/common": "^0.7.0",
|
||||
"@ccms/container": "^0.7.0"
|
||||
"@ccms/api": "^0.8.2",
|
||||
"@ccms/common": "^0.8.2",
|
||||
"@ccms/container": "^0.8.2",
|
||||
"@ccms/database": "^0.8.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,21 +3,25 @@ import '@ccms/nashorn'
|
||||
import { command, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton, postConstruct } from '@ccms/container'
|
||||
|
||||
import { CommandMap } from './internal/command'
|
||||
|
||||
@provideSingleton(command.Command)
|
||||
export class SpringCommand extends command.Command {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
@inject(CommandMap)
|
||||
private commandMap: CommandMap = new CommandMap()
|
||||
|
||||
protected create(plugin: any, command: string) {
|
||||
console.console('§4Spring暂不支持create命令!')
|
||||
return this.commandMap.register(plugin, command)
|
||||
}
|
||||
protected remove(plugin: any, command: string) {
|
||||
console.console('§4Spring暂不支持remove命令!')
|
||||
this.commandMap.unregister(plugin, command)
|
||||
}
|
||||
protected onCommand(plugin: any, command: any, executor: Function) {
|
||||
console.console('§4Spring暂不支持onCommand!')
|
||||
command.setExecutor(super.setExecutor(plugin, command, executor))
|
||||
}
|
||||
protected onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||
console.console('§4Spring暂不支持onTabComplete!')
|
||||
command.setTabCompleter(super.setExecutor(plugin, command, tabCompleter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,12 +28,29 @@ function mcColor2ANSI(str: string) {
|
||||
for (const regex in regexMap) {
|
||||
str = str.replace(regexMap[regex], `\u001b[${regex}m`)
|
||||
}
|
||||
return str;
|
||||
return str
|
||||
}
|
||||
|
||||
export class SpringConsole extends MiaoScriptConsole {
|
||||
error(...args: any[]) {
|
||||
this.logger.error(args.join(' '))
|
||||
}
|
||||
warn(...args: any[]) {
|
||||
this.logger.warn(args.join(' '))
|
||||
}
|
||||
sender(sender: any, ...args: any[]) {
|
||||
this.console(args.join(' '))
|
||||
sender = sender || {
|
||||
sendMessage: (message: string) => console.console(message)
|
||||
}
|
||||
if (!sender.sendMessage) {
|
||||
this.error('第一个参数未实现 sendMessage 无法发送消息!')
|
||||
return
|
||||
}
|
||||
if (Object.prototype.toString.call(args[0]) === '[object Array]') {
|
||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||
} else {
|
||||
sender.sendMessage(this.prefix + args.join(' '))
|
||||
}
|
||||
}
|
||||
console(...args: string[]): void {
|
||||
this.logger.info(mcColor2ANSI(args.join(' ') + '§r'))
|
||||
|
||||
@@ -1,14 +1,29 @@
|
||||
import { server, plugin } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
import { server } from '@ccms/api'
|
||||
import { ioc, Container, reduceMetadata } from '@ccms/container'
|
||||
|
||||
import { SpringConsole } from './console';
|
||||
import './event';
|
||||
import './server';
|
||||
import './command';
|
||||
import './task';
|
||||
import { SpringConsole } from './console'
|
||||
import './event'
|
||||
import './server'
|
||||
import './command'
|
||||
import './task'
|
||||
|
||||
const BeanKit = Java.type('com.sixi.micro.common.kits.BeanKit')
|
||||
const toString = {}.toString
|
||||
|
||||
export default function SpringImpl(container: Container) {
|
||||
try {
|
||||
require('@ccms/web')
|
||||
require('@ccms/amqp')
|
||||
require('@ccms/database')
|
||||
require('./internal/scanner/mysql-scanner')
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
container.bind(server.Console).toConstantValue(SpringConsole)
|
||||
container.bind(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 }
|
||||
return beanFactory.getBean(metadata.named)
|
||||
})
|
||||
}
|
||||
|
||||
79
packages/spring/src/internal/command.ts
Normal file
79
packages/spring/src/internal/command.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
import { plugin } from "@ccms/api"
|
||||
|
||||
type CommandExec = (sender: any, _: any, command: string, args: string[]) => boolean
|
||||
type TabCompleter = (sender: any, _: any, command: string, args: string[]) => string[]
|
||||
type CommandStore = { [key: string]: SpringCommand }
|
||||
|
||||
@provideSingleton(CommandMap)
|
||||
export class CommandMap {
|
||||
private commands: CommandStore = {}
|
||||
private pluginCommands: { [key: string]: CommandStore } = {}
|
||||
|
||||
register(plugin: plugin.Plugin, command: string) {
|
||||
let springCommand = new SpringCommand(plugin, command)
|
||||
this.commands[command] = springCommand
|
||||
if (!this.pluginCommands[plugin.description.name]) { this.pluginCommands[plugin.description.name] = {} }
|
||||
this.pluginCommands[plugin.description.name][command] = springCommand
|
||||
return springCommand
|
||||
}
|
||||
|
||||
unregister(plugin: plugin.Plugin, command: string) {
|
||||
delete this.commands[command]
|
||||
delete this.pluginCommands[plugin.description.name][command]
|
||||
}
|
||||
|
||||
dispatch(sender: any, command: string, args: string[]): boolean {
|
||||
if (command === "help") {
|
||||
sender.sendMessage('§e--------- §rHelp: Index §e---------------------------')
|
||||
sender.sendMessage('Use /help [n] to get page n of help.')
|
||||
for (const cmdName of Object.getOwnPropertyNames(this.commands)) {
|
||||
sender.sendMessage(`§6/${cmdName}: §rA command provided by plugin §b${this.commands[cmdName].plugin.description.name}§r.`)
|
||||
}
|
||||
return
|
||||
}
|
||||
let exists = this.commands[command]
|
||||
if (exists) {
|
||||
try {
|
||||
return exists.executor(sender, '', command, Java.to(args))
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
sender.sendMessage && sender.sendMessage(`Unknown command. Type "/help" for help.`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
tabComplate(sender: any, input: string, index?: number): string[] {
|
||||
if (index == 0) { return Object.keys(this.commands).concat('help') }
|
||||
let [command, ...args] = input.split(' ')
|
||||
let exists = this.commands[command]
|
||||
if (exists && exists.tabCompleter) {
|
||||
try {
|
||||
if (args.length !== index) { args.push('') }
|
||||
return exists.tabCompleter(sender, '', command, Java.to(args))
|
||||
} catch (error) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export class SpringCommand {
|
||||
public plugin: plugin.Plugin
|
||||
public name: string
|
||||
public executor: CommandExec
|
||||
public tabCompleter: TabCompleter
|
||||
|
||||
constructor(plugin: plugin.Plugin, command: string, description: string = '暂无描述!') {
|
||||
this.plugin = plugin
|
||||
this.name = command
|
||||
}
|
||||
|
||||
setExecutor = (executor: CommandExec) => this.executor = executor
|
||||
setTabCompleter = (tabCompleter: TabCompleter) => this.tabCompleter = tabCompleter
|
||||
toString = () => `SpringCommand(${this.name})`
|
||||
}
|
||||
48
packages/spring/src/internal/scanner/mysql-scanner.ts
Normal file
48
packages/spring/src/internal/scanner/mysql-scanner.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { plugin, database } from '@ccms/api'
|
||||
import { DataBaseManager } from '@ccms/database'
|
||||
import { provideSingleton, inject } from '@ccms/container'
|
||||
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
interface MySQLPlugin {
|
||||
name: string
|
||||
source: string
|
||||
}
|
||||
|
||||
@provideSingleton(plugin.PluginScanner)
|
||||
export class MySQLScanner implements plugin.PluginScanner {
|
||||
type: string = "mysql"
|
||||
|
||||
private cacheDir = 'mysql-plugin-cache'
|
||||
private cacheFileMap: Map<string, MySQLPlugin> = new Map()
|
||||
private target: string
|
||||
|
||||
@inject(database.DataBaseManager)
|
||||
private databaseManager: DataBaseManager
|
||||
|
||||
scan(target: any): plugin.PluginLoadMetadata[] {
|
||||
this.target = target
|
||||
let plugins = this.databaseManager.getMainDatabase().query<MySQLPlugin>(`SELECT name FROM ${this.target} WHERE LENGTH(source) != 0 AND deleted = 0`)
|
||||
return plugins.map(p => this.read(p))
|
||||
}
|
||||
read(mysqlPlugin: MySQLPlugin): plugin.PluginLoadMetadata {
|
||||
// if invoke this function from loadFromFile mysqlPlugin is a string need read from cache
|
||||
if (typeof mysqlPlugin == "string") {
|
||||
if (!this.cacheFileMap.has(mysqlPlugin)) { throw new Error(`this file ${mysqlPlugin} is not read from mysql-scanner. can't reload from this scanner!`) }
|
||||
mysqlPlugin = this.cacheFileMap.get(mysqlPlugin)
|
||||
}
|
||||
let cacheFile = fs.concat(root, this.cacheDir, `${mysqlPlugin.name}.js`)
|
||||
this.cacheFileMap.set(cacheFile, mysqlPlugin)
|
||||
return { name: mysqlPlugin.name, file: cacheFile, type: this.type, mysqlPlugin, scanner: this }
|
||||
}
|
||||
load(metadata: plugin.PluginLoadMetadata) {
|
||||
if (metadata.type !== this.type) { return }
|
||||
var plugin: any = this.databaseManager.getMainDatabase().query<MySQLPlugin>(`SELECT source FROM ${this.target} WHERE name = ? AND deleted = 0`, metadata.name)
|
||||
if (plugin.length == 0) { throw new Error(`[MySQLScanner] plugin ${metadata.name} not found at mysql database...`) }; plugin = plugin[0]
|
||||
if (!plugin.source) { throw new Error(`[MySQLScanner] plugin ${metadata.name} source can\'t be undefiend or empty...`) }
|
||||
base.save(metadata.file, plugin.source)
|
||||
//@ts-ignore
|
||||
metadata.instance = require(metadata.file, { cache: false })
|
||||
return metadata
|
||||
}
|
||||
}
|
||||
@@ -1,50 +1,56 @@
|
||||
import { server } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container';
|
||||
import { NativePluginManager } from '@ccms/api/dist/interfaces/server/native_plugin';
|
||||
import { provideSingleton, inject } from '@ccms/container'
|
||||
import { NativePluginManager } from '@ccms/api/dist/interfaces/server/native_plugin'
|
||||
import { CommandMap } from './internal/command'
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
export class SpringServer implements server.Server {
|
||||
@inject(CommandMap)
|
||||
private commandMap: CommandMap
|
||||
|
||||
constructor() {
|
||||
}
|
||||
getVersion(): string {
|
||||
return "SpringFramework"
|
||||
}
|
||||
getPlayer(name: string) {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getOnlinePlayers(): any[] {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getConsoleSender() {
|
||||
return undefined;
|
||||
return {
|
||||
name: 'CONSOLE',
|
||||
sendMessage: (message: string) => console.console(message)
|
||||
}
|
||||
}
|
||||
getService(service: string) {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchCommand(sender: any, command: string): boolean {
|
||||
console.console('§4Spring暂不支持dispatchCommand!')
|
||||
return false;
|
||||
let cmd_args = command.split(" ")
|
||||
return this.commandMap.dispatch(sender, cmd_args.shift(), cmd_args || [])
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
console.console('§4Spring暂不支持dispatchConsoleCommand!')
|
||||
return false;
|
||||
return this.dispatchCommand(this.getConsoleSender(), command)
|
||||
}
|
||||
getPluginsFolder(): string {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getNativePluginManager(): NativePluginManager {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getNettyPipeline() {
|
||||
return base.getInstance().getAutowireCapableBeanFactory()
|
||||
}
|
||||
getRootLogger() {
|
||||
return global.logger
|
||||
return Packages.org.slf4j.LoggerFactory.getLogger("root") || global.logger
|
||||
}
|
||||
sendJson(sender: any, json: string | object): void {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
tabComplete(sender: any, input: string, index?: number) {
|
||||
throw new Error("Method not implemented.");
|
||||
return this.commandMap.tabComplate(sender, input, index)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,30 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
import thread_pool from '@ccms/common/dist/thread-pool'
|
||||
|
||||
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 ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
|
||||
const ThreadPoolTaskExecutor = Java.type('org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor')
|
||||
|
||||
let executor: any
|
||||
let tasks: { [key: number]: task.Cancelable } = {}
|
||||
let taskId = 0
|
||||
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 {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
private innerTaskId: any
|
||||
private innerTasks: { [s: string]: task.Cancelable }
|
||||
private innerExecutor: java.util.concurrent.ThreadPoolExecutor
|
||||
|
||||
constructor() {
|
||||
executor = new ThreadPoolTaskExecutor()
|
||||
executor.setCorePoolSize(10)
|
||||
executor.setMaxPoolSize(100)
|
||||
executor.setQueueCapacity(500)
|
||||
executor.setKeepAliveSeconds(60)
|
||||
executor.setThreadNamePrefix("@ccms/spring-")
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
|
||||
executor.initialize()
|
||||
this.innerTaskId = taskId
|
||||
this.innerTasks = tasks
|
||||
this.innerExecutor = executor
|
||||
}
|
||||
|
||||
create(func: Function): task.Task {
|
||||
@@ -34,16 +35,16 @@ export class SpringTaskManager implements task.TaskManager {
|
||||
return func()
|
||||
}
|
||||
disable() {
|
||||
Object.values(tasks).forEach((task) => task.cancel())
|
||||
executor.shutdown();
|
||||
Object.values(this.innerTasks).forEach((task) => task?.cancel())
|
||||
this.innerExecutor.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
export class SpringTask extends task.Task {
|
||||
public id = taskId++
|
||||
public id = taskId.incrementAndGet()
|
||||
private running = new AtomicBoolean(true)
|
||||
|
||||
run() {
|
||||
run(...args: any[]) {
|
||||
if (this.laterTime > 0) {
|
||||
try {
|
||||
Thread.sleep(this.laterTime)
|
||||
@@ -53,7 +54,7 @@ export class SpringTask extends task.Task {
|
||||
}
|
||||
while (this.running.get()) {
|
||||
try {
|
||||
this.func()
|
||||
this.func(...args)
|
||||
} catch (t) {
|
||||
console.error("Task exec error:", t)
|
||||
console.ex(t)
|
||||
@@ -72,13 +73,13 @@ export class SpringTask extends task.Task {
|
||||
cancel(): any {
|
||||
var wasRunning = this.running.getAndSet(false)
|
||||
if (wasRunning) {
|
||||
tasks[this.id] = undefined
|
||||
delete tasks[this.id]
|
||||
}
|
||||
}
|
||||
|
||||
submit(): task.Cancelable {
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
tasks[this.id] = this
|
||||
executor.execute(this.run.bind(this))
|
||||
executor.execute((() => this.run(...args)) as any)
|
||||
return {
|
||||
cancel: () => {
|
||||
return this.cancel()
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
test
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
.theia
|
||||
type_definitions
|
||||
tsconfig.tsbuildinfo
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user