Compare commits
347 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cd6a2023dc | |||
| 498b0ee017 | |||
| 9bfaf984c1 | |||
| 3c33ebf4e6 | |||
| 8af69c98f3 | |||
| 72277f4d1a | |||
| d85f75ba1f | |||
| ed14d317f4 | |||
| fb8a11ea05 | |||
| eae80fa30b | |||
| 3e69fc42d9 | |||
| c5595a65fb | |||
| df266905f2 | |||
| f8046e38be | |||
| 51fb5aece3 | |||
| 7a1dd3e7b3 | |||
| 8f3c799531 | |||
| 3389dbd566 | |||
| 54604e10b8 | |||
| d7247bae19 | |||
| 3ee2dcad0b | |||
| bc19021c63 | |||
| e9a4f2f351 | |||
| 9be9c400ad | |||
| 8eaf789bce | |||
| 7d6f6124b1 | |||
| e06fcc29e9 | |||
| 79ece8db63 | |||
| 66c1d25888 | |||
| ca8d4778bb | |||
| 7dcc5ed45a | |||
| 91d2d836fc | |||
| e5e1bb70a1 | |||
| e93a53aa9f | |||
| e3bceda06b | |||
| 9367e8c2c9 | |||
| 31c7ea2a29 | |||
| 2589633069 | |||
| bc17e2f376 | |||
| 20749d3381 | |||
| 6261b85413 | |||
| da9d590374 | |||
| 0af3ca8c79 | |||
| 561d5b60e8 | |||
| 878a5368af | |||
| 018b972aea | |||
| 4138cf9448 | |||
| 646176b43c | |||
| 506184a104 | |||
| 392f01d509 | |||
| 75b892e1c0 | |||
| c2d825eed0 | |||
| 393e63c017 | |||
| 46d6748f31 | |||
| b6803ed01c | |||
| bbfc70fdd6 | |||
| e28af3fbbc | |||
| 14eef46e67 | |||
| 1c4f512c89 | |||
| a8ae60625b | |||
| e7bc14294e | |||
| 4750f31b6e | |||
| 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 | |||
| 9fa3ed704a | |||
| a76858d626 | |||
| 55a6b33110 | |||
| b87b94aade | |||
| 4110ed2c20 | |||
| 3cbc101eff | |||
| 221b821085 | |||
| 7331cfaa55 | |||
| 40d020ef67 | |||
| eea2a225e8 | |||
| 48f7f0fdbb | |||
| 99ed76f9bb | |||
| 7f21fa67ee | |||
| 8584709828 | |||
| d1f58e7482 | |||
| 1bd35aef6d | |||
| fdf1088564 | |||
| 7bb4d1f6a3 | |||
| b8c3d0d19d | |||
| a616a07553 | |||
| 781524f83e | |||
| c7a812c003 | |||
| 325f2c8cf9 | |||
| 562e2d0017 | |||
| b7871e8d33 | |||
| 060cffd8e7 | |||
| 4b1fb07cc9 | |||
| 0931d69188 | |||
| 7d33368ebd | |||
| c95fc5fcff | |||
| a7479f60c8 | |||
| ac75356778 | |||
| 7f32382dbc | |||
| b3c2def36d | |||
| 1ea93dfb9f | |||
| e5ffa70ed9 | |||
| 2a60b36e23 | |||
| c4c2c0ab0f | |||
| bf5628a646 | |||
| 13e9f0a5af | |||
| cdd5f2d250 | |||
| dfd7182008 | |||
| 533859808f | |||
| 15cea1dfc8 | |||
| dfa43d58f0 | |||
| 2bf239d8ea | |||
| cbe87cc378 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,4 +1,8 @@
|
|||||||
|
.vscode
|
||||||
|
.theia
|
||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
package-lock.json
|
package-lock.json
|
||||||
yarn.lock
|
yarn.lock
|
||||||
|
packages/nashorn/docs
|
||||||
|
!packages/types/dist
|
||||||
|
|||||||
10
.gitpod.Dockerfile
vendored
Normal file
10
.gitpod.Dockerfile
vendored
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
FROM gitpod/workspace-full
|
||||||
|
|
||||||
|
USER gitpod
|
||||||
|
|
||||||
|
# Install custom tools, runtime, etc. using apt-get
|
||||||
|
# For example, the command below would install "bastet" - a command line tetris clone:
|
||||||
|
#
|
||||||
|
# RUN sudo apt-get -q update && # sudo apt-get install -yq bastet && # sudo rm -rf /var/lib/apt/lists/*
|
||||||
|
#
|
||||||
|
# More information: https://www.gitpod.io/docs/config-docker/
|
||||||
5
.gitpod.yml
Normal file
5
.gitpod.yml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
tasks:
|
||||||
|
- init: yarn && yarn bs && yarn build
|
||||||
|
command: yarn watch
|
||||||
|
# image:
|
||||||
|
# file: .gitpod.Dockerfile
|
||||||
24
.npmignore
Normal file
24
.npmignore
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
test
|
||||||
|
typings
|
||||||
|
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
|
||||||
|
*.tsbuildinfo
|
||||||
34
README.MD
Normal file
34
README.MD
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# MiaoScript implement
|
||||||
|
|
||||||
|
## MiaoScript JS 实现
|
||||||
|
|
||||||
|
项目 由 TypeScript 进行编写 然后编译至 `es5` 用于兼容 Java8 的 `Nashorn`
|
||||||
|
|
||||||
|
### Project Path
|
||||||
|
|
||||||
|
```txt
|
||||||
|
└─packages
|
||||||
|
├─api 全平台兼容的接口
|
||||||
|
├─core 核心代码 用于引导加载
|
||||||
|
├─common 公共类库代码 例如 http reflect 模块
|
||||||
|
├─client NodeJS的Minecraft客户端 用于调试插件
|
||||||
|
├─container IOC容器 用于注入具体实现
|
||||||
|
├─ployfill Nashorn 的一些自定义增强
|
||||||
|
├─nashorn Nashorn 的类型定义
|
||||||
|
├─bungee BungeeCordAPI内部实现
|
||||||
|
├─bukkit BukkitAPI内部实现
|
||||||
|
├─sponge SpongeAPI内部实现
|
||||||
|
├─nukkit NukkitAPI内部实现
|
||||||
|
├─plugin 插件管理器
|
||||||
|
├─websocket Netty的WebSocket注入
|
||||||
|
├─type Java的类型定义
|
||||||
|
| ├─bungee BungeeCord类型定义
|
||||||
|
| ├─bukkit Bukkit类型定义
|
||||||
|
| ├─sponge Sponge类型定义
|
||||||
|
| └─nukkit Nukkit类型定义
|
||||||
|
└─plugins 这里当然是插件啦
|
||||||
|
├─bungee 只兼容BungeeCord的插件
|
||||||
|
├─bukkit 只兼容Bukkit的插件
|
||||||
|
├─sponge 只兼容Sponge的插件
|
||||||
|
└─nukkit 只兼容Nukkit的插件
|
||||||
|
```
|
||||||
11
doc/MCBBS.MD
Normal file
11
doc/MCBBS.MD
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
- 构建状态 [](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/)
|
||||||
|
- 当前版本 
|
||||||
|
- 下载地址 [](http://w.yumc.pw/free.html#MiaoScript-download)
|
||||||
|
- 更新日志 [](https://docs.yumc.pw/MiaoScript/CHANGELOG.html)
|
||||||
|
- 安装文档 [](https://docs.yumc.pw/MiaoScript/1-user/1.1-check-env.html)
|
||||||
|
- 开发文档 [](https://docs.yumc.pw/MiaoScript/2-develop/1.1-check-env.html)
|
||||||
|
- 兼容服务端 Spigot CatServer Sponge BungeeCord Nukkit(没错 他还兼容Nukkit)
|
||||||
|
|
||||||
|
### 腐竹版本(开发中)
|
||||||
|
|
||||||
|
- 先上几张图
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"version": "0.0.0",
|
"version": "0.9.7",
|
||||||
"useWorkspaces": true,
|
"useWorkspaces": true,
|
||||||
"npmClient": "yarn",
|
"npmClient": "yarn",
|
||||||
"packages": [
|
"packages": [
|
||||||
@@ -10,7 +10,8 @@
|
|||||||
"stream": true
|
"stream": true
|
||||||
},
|
},
|
||||||
"publish": {
|
"publish": {
|
||||||
|
"access": "public",
|
||||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
15
package.json
15
package.json
@@ -6,15 +6,20 @@
|
|||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "npx lerna run clean",
|
"bs": "lerna bootstrap",
|
||||||
"watch": "npx lerna run watch --parallel",
|
"clean": "lerna run clean",
|
||||||
"build": "npx lerna run build",
|
"watch": "lerna run watch --parallel",
|
||||||
"lp": "npx lerna publish"
|
"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 --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": [
|
"workspaces": [
|
||||||
"packages/*"
|
"packages/*"
|
||||||
],
|
],
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"lerna": "^3.16.4"
|
"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.9.5",
|
||||||
|
"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.9.5",
|
||||||
|
"@ccms/common": "^0.9.4",
|
||||||
|
"@ccms/container": "^0.9.4"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@ccms/nashorn": "^0.9.4",
|
||||||
|
"@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": "^4.0.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
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"
|
||||||
|
}
|
||||||
|
}
|
||||||
4
packages/api/.gitignore
vendored
4
packages/api/.gitignore
vendored
@@ -1,4 +0,0 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
|
||||||
/package-lock.json
|
|
||||||
/yarn.lock
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
src
|
|
||||||
test
|
|
||||||
typings
|
|
||||||
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
|
|
||||||
type_definitions
|
|
||||||
1
packages/api/.npmignore
Symbolic link
1
packages/api/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../../.npmignore
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/api",
|
"name": "@ccms/api",
|
||||||
"version": "0.0.0",
|
"version": "0.9.5",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,22 +12,23 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"publishConfig": {
|
|
||||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
|
||||||
},
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/common": "^0.0.0",
|
"@ccms/common": "^0.9.4",
|
||||||
"@ms/container": "^0.0.0"
|
"@ccms/container": "^0.9.4",
|
||||||
|
"@ccms/ployfill": "^0.9.4",
|
||||||
|
"base64-js": "^1.3.1",
|
||||||
|
"source-map-builder": "^0.0.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/base64-js": "^1.3.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^4.0.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
66
packages/api/src/channel.ts
Normal file
66
packages/api/src/channel.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import { injectable } from "@ccms/container"
|
||||||
|
|
||||||
|
export namespace channel {
|
||||||
|
/**
|
||||||
|
* handle plugin message
|
||||||
|
* @param data byte[]
|
||||||
|
*/
|
||||||
|
export type ChannelListener = (data: any, exts?: any) => void
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export abstract class Channel {
|
||||||
|
private listenerMap = [];
|
||||||
|
/**
|
||||||
|
* 注册通道
|
||||||
|
* @param plugin 插件
|
||||||
|
* @param channel 通道
|
||||||
|
* @param exec 执行器
|
||||||
|
*/
|
||||||
|
listen(plugin: any, channel: string, exec: ChannelListener) {
|
||||||
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!')
|
||||||
|
let name = plugin.description.name
|
||||||
|
let listener = this.register(channel, exec)
|
||||||
|
if (!this.listenerMap[name]) this.listenerMap[name] = []
|
||||||
|
let offExec = () => {
|
||||||
|
this.unregister(channel, listener)
|
||||||
|
console.debug(`[${name}] unregister channel ${channel}`)
|
||||||
|
}
|
||||||
|
var off = {
|
||||||
|
channel,
|
||||||
|
listener,
|
||||||
|
off: offExec
|
||||||
|
}
|
||||||
|
this.listenerMap[name].push(off)
|
||||||
|
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`)
|
||||||
|
return off
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 关闭插件注册的通道
|
||||||
|
* @param plugin 插件
|
||||||
|
*/
|
||||||
|
disable(plugin: any) {
|
||||||
|
var channelCache = this.listenerMap[plugin.description.name]
|
||||||
|
if (channelCache) {
|
||||||
|
channelCache.forEach(t => t.off())
|
||||||
|
delete this.listenerMap[plugin.description.name]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Send Channel Message
|
||||||
|
* @param player recover target
|
||||||
|
* @param channel ChannelName
|
||||||
|
* @param data byte[]
|
||||||
|
*/
|
||||||
|
abstract send(player: any, channel: string, data: any)
|
||||||
|
/**
|
||||||
|
* register channel
|
||||||
|
* @param channel ChannelName
|
||||||
|
*/
|
||||||
|
abstract register(channel: string, listener: ChannelListener): any
|
||||||
|
/**
|
||||||
|
* unregister channel
|
||||||
|
* @param channel ChannelName
|
||||||
|
*/
|
||||||
|
abstract unregister(channel: string, listener?: any): void
|
||||||
|
}
|
||||||
|
}
|
||||||
31
packages/api/src/chat.ts
Normal file
31
packages/api/src/chat.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { injectable } from '@ccms/container'
|
||||||
|
|
||||||
|
export namespace chat {
|
||||||
|
@injectable()
|
||||||
|
export abstract class Chat {
|
||||||
|
/**
|
||||||
|
* sendJsonChat
|
||||||
|
* @param sender reciver
|
||||||
|
* @param json json
|
||||||
|
* @param type chat Type 0: chat 1: system 2: actionBar
|
||||||
|
*/
|
||||||
|
sendJson(sender: any, json: string | object, type = 0) {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
sendMessage(sender: any, message: string) {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
sendActionBar(sender: any, message: string) {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
clearActionBar(sender: any) {
|
||||||
|
this.sendActionBar(sender, '')
|
||||||
|
}
|
||||||
|
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
clearTitle(sender: any) {
|
||||||
|
this.sendTitle(sender, '', '', 0, 0, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,25 +1,82 @@
|
|||||||
import { injectable } from "@ms/container";
|
import i18n from '@ccms/i18n'
|
||||||
|
import { injectable } from "@ccms/container"
|
||||||
|
import { plugin } from './interfaces'
|
||||||
|
|
||||||
export namespace command {
|
export namespace command {
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Command {
|
export abstract class Command {
|
||||||
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
/**
|
||||||
var cmd = this.create(plugin, { name: name });
|
* 注册插件命令
|
||||||
console.debug(`插件 ${plugin.description.name} 创建命令 ${name}(${cmd})...`)
|
* @param plugin 插件
|
||||||
|
* @param name 命令
|
||||||
|
* @param exec 执行器
|
||||||
|
*/
|
||||||
|
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||||
|
var cmd = this.create(plugin, name)
|
||||||
|
if (!cmd) { throw Error(`Plugin ${plugin.description.name} can't create Command ${name}!`) }
|
||||||
|
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
||||||
if (exec.cmd && typeof exec.cmd === "function") {
|
if (exec.cmd && typeof exec.cmd === "function") {
|
||||||
this.onCommand(plugin, cmd, exec.cmd)
|
this.onCommand(plugin, cmd, exec.cmd)
|
||||||
} else {
|
} else {
|
||||||
throw Error("CommandExec Must be a function... Input: " + exec.cmd)
|
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
|
||||||
}
|
}
|
||||||
if (exec.tab && typeof exec.tab === "function") {
|
if (exec.tab && typeof exec.tab === "function") {
|
||||||
this.onTabComplete(plugin, cmd, exec.tab)
|
this.onTabComplete(plugin, cmd, exec.tab)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
public tabComplete(sender: any, input: string, index?: number): string[] {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Create Server Command Object
|
* 取消命令注册
|
||||||
|
* @param plugin 插件
|
||||||
|
* @param name 命令
|
||||||
*/
|
*/
|
||||||
abstract create(plugin: object, opts: { name: string });
|
off(plugin: plugin.Plugin, name: string) {
|
||||||
abstract onCommand(plugin: object, command: any, opts: { name: string });
|
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
||||||
abstract onTabComplete(plugin: object, command: any, opts: { name: string });
|
this.remove(plugin, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
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))
|
||||||
|
} 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)
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
} catch (ex) {
|
||||||
|
console.i18n("ms.api.command.tab.completer.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||||
|
console.ex(ex)
|
||||||
|
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
|
||||||
|
if (!token) { return complete }
|
||||||
|
complete.forEach(function (e) {
|
||||||
|
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
||||||
|
array.push(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return array
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,148 +1,232 @@
|
|||||||
let Arrays = Java.type('java.util.Arrays');
|
import i18m from '@ccms/i18n'
|
||||||
let Level = Java.type('java.util.logging.Level');
|
import { SourceMapBuilder } from 'source-map-builder'
|
||||||
let ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.'];
|
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.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||||
|
|
||||||
|
enum LogLevel {
|
||||||
|
ALL,
|
||||||
|
TRACE,
|
||||||
|
DEBUG,
|
||||||
|
INFO,
|
||||||
|
WARN,
|
||||||
|
ERROR,
|
||||||
|
FATAL,
|
||||||
|
OFF
|
||||||
|
}
|
||||||
|
|
||||||
export class MiaoScriptConsole implements Console {
|
export class MiaoScriptConsole implements Console {
|
||||||
Console: NodeJS.ConsoleConstructor;
|
Console: NodeJS.ConsoleConstructor
|
||||||
|
|
||||||
private _name: string = '';
|
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||||
|
private static sourceFileMaps: { [key: string]: string } = {}
|
||||||
|
private _name: string = ''
|
||||||
|
private _level: LogLevel = LogLevel.INFO
|
||||||
|
|
||||||
protected logger: any;
|
protected logger: any
|
||||||
protected prefix: string = '§6[§bMiaoScript§6]§r ';
|
protected prefix: string = '§6[§bMiaoScript§6]§r '
|
||||||
|
|
||||||
constructor(name?: string) {
|
constructor(name?: string) {
|
||||||
this.name = name;
|
this.name = name
|
||||||
this.logger = global.logger;
|
this.logger = global.logger
|
||||||
|
if (global.debug) {
|
||||||
|
this._level = LogLevel.DEBUG
|
||||||
|
}
|
||||||
|
if (global.level?.toUpperCase() === "TRACE") {
|
||||||
|
this._level = LogLevel.TRACE
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
get name() {
|
get name() {
|
||||||
return this._name;
|
return this._name
|
||||||
}
|
}
|
||||||
|
|
||||||
set name(name: string) {
|
set name(name: string) {
|
||||||
if (name) {
|
if (name) {
|
||||||
this._name = `[${name}] `;
|
this._name = `[${name}] `
|
||||||
// noinspection JSUnusedGlobalSymbols
|
// noinspection JSUnusedGlobalSymbols
|
||||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
|
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log(...args): void {
|
log(...args: any[]): void {
|
||||||
this.logger.info(this.name + args.join(' '));
|
this.logger.info(this.name + args.join(' '))
|
||||||
}
|
}
|
||||||
info(...args) {
|
info(...args: any[]) {
|
||||||
this.logger.info(this.name + args.join(' '));
|
this.logger.info(this.name + args.join(' '))
|
||||||
};
|
}
|
||||||
warn(...args) {
|
warn(...args: any[]) {
|
||||||
this.logger.warning(this.name + args.join(' '));
|
this.logger.warning(this.name + args.join(' '))
|
||||||
};
|
}
|
||||||
error(...args) {
|
error(...args: any[]) {
|
||||||
this.logger.log(Level.SEVERE, this.name + args.join(' '));
|
this.logger.log(Level.SEVERE, this.name + args.join(' '))
|
||||||
};
|
}
|
||||||
debug(...args) {
|
debug(...args: any[]) {
|
||||||
if (global.debug) {
|
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(' '))
|
||||||
|
}
|
||||||
|
}
|
||||||
sender(...args) {
|
sender(...args) {
|
||||||
this.info(args)
|
this.info(args)
|
||||||
}
|
}
|
||||||
console(...args) {
|
console(...args) {
|
||||||
this.info(args)
|
this.info(args)
|
||||||
}
|
}
|
||||||
|
i18n(name: string, param?: { [key: string]: any }) {
|
||||||
|
this.console(i18m.translate(name, param))
|
||||||
|
}
|
||||||
object(obj) {
|
object(obj) {
|
||||||
for (var i in obj) {
|
for (const i in obj) {
|
||||||
this.logger(i, '=>', obj[i])
|
this.info(i, '=>', obj[i])
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
ex(ex: Error) {
|
ex(ex: Error) {
|
||||||
this.stack(ex).forEach(line => this.console(line))
|
this.stack(ex).forEach(line => this.console(line))
|
||||||
};
|
}
|
||||||
stack(ex: Error | any): string[] {
|
readSourceMap(fileName: string, lineNumber: number) {
|
||||||
var stack = ex.getStackTrace();
|
try {
|
||||||
var cache = ['§4' + ex];
|
if (fileName.endsWith('js')) {
|
||||||
if (stack.class) {
|
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
||||||
stack = Arrays.asList(stack)
|
MiaoScriptConsole.sourceMaps[fileName] = null
|
||||||
}
|
let sourceLine = base.read(fileName).split('\n')
|
||||||
stack.forEach(function(trace) {
|
let lastLine = sourceLine[sourceLine.length - 1]
|
||||||
if (trace.className.startsWith('<')) {
|
// lastLine is similar //# sourceMappingURL=data:application/json;base64,
|
||||||
var fileName = trace.fileName
|
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
let sourceContent = null
|
||||||
if (fileName.startsWith('/runtime')) { fileName = fileName.split('/runtime')[1] }
|
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
||||||
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${trace.lineNumber}`)
|
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||||
} else {
|
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||||
var className = trace.className;
|
} else if (sourceMappingURL.startsWith('http')) {
|
||||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
// TODO
|
||||||
className = className.substr(className.lastIndexOf('$') + 1)
|
} else {
|
||||||
} else {
|
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
||||||
for (var prefix in ignoreLogPrefix) {
|
if (file.exists()) { sourceContent = base.read(file) }
|
||||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
}
|
||||||
return;
|
if (sourceContent) {
|
||||||
|
MiaoScriptConsole.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||||
|
MiaoScriptConsole.sourceFileMaps[fileName] = Paths.get(fileName, '..', MiaoScriptConsole.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${trace.fileName}:${trace.lineNumber}§c)`);
|
if (MiaoScriptConsole.sourceMaps[fileName]) {
|
||||||
|
let sourceMapping = MiaoScriptConsole.sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
||||||
|
fileName = MiaoScriptConsole.sourceFileMaps[fileName]
|
||||||
|
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
} catch (error) {
|
||||||
return cache;
|
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||||
|
if (global.debug) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
fileName,
|
||||||
|
lineNumber
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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:') || 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] }
|
||||||
|
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
|
||||||
|
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
||||||
|
className = className.substr(className.lastIndexOf('$') + 1)
|
||||||
|
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||||
|
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||||
|
} else {
|
||||||
|
for (let prefix in ignoreLogPrefix) {
|
||||||
|
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (color) {
|
||||||
|
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||||
|
} else {
|
||||||
|
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return cache
|
||||||
}
|
}
|
||||||
assert(value: any, message?: string, ...optionalParams: any[]): void {
|
assert(value: any, message?: string, ...optionalParams: any[]): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
clear(): void {
|
clear(): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
count(label?: string): void {
|
count(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
countReset(label?: string): void {
|
countReset(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
dir(obj: any, options?: NodeJS.InspectOptions): void {
|
dir(obj: any, options?: NodeJS.InspectOptions): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
dirxml(...data: any[]): void {
|
dirxml(...data: any[]): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
group(...label: any[]): void {
|
group(...label: any[]): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
groupCollapsed(...label: any[]): void {
|
groupCollapsed(...label: any[]): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
groupEnd(): void {
|
groupEnd(): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
table(tabularData: any, properties?: string[]): void {
|
table(tabularData: any, properties?: string[]): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
time(label?: string): void {
|
time(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
timeEnd(label?: string): void {
|
timeEnd(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
timeLog(label?: string, ...data: any[]): void {
|
timeLog(label?: string, ...data: any[]): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
|
||||||
trace(message?: any, ...optionalParams: any[]): void {
|
|
||||||
throw new Error("Method not implemented.");
|
|
||||||
}
|
}
|
||||||
markTimeline(label?: string): void {
|
markTimeline(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
profile(label?: string): void {
|
profile(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
profileEnd(label?: string): void {
|
profileEnd(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
timeStamp(label?: string): void {
|
timeStamp(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
timeline(label?: string): void {
|
timeline(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
timelineEnd(label?: string): void {
|
timelineEnd(label?: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
17
packages/api/src/constants.ts
Normal file
17
packages/api/src/constants.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
export namespace constants {
|
||||||
|
export namespace Reflect {
|
||||||
|
export const Method = {
|
||||||
|
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
|
||||||
|
}
|
||||||
|
export const Field = {
|
||||||
|
listeningChannels: [/*spigot 1.8.8-1.12.2*/'g', /*spigot 1.14.4*/'f', /*spigot 1.15.2+*/'listeningChannels', /*catserver 1.12.2*/'field_151274_e']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export enum ServerType {
|
||||||
|
Bukkit = 'bukkit',
|
||||||
|
Sponge = 'sponge',
|
||||||
|
Nukkit = 'nukkit',
|
||||||
|
Bungee = 'bungee',
|
||||||
|
Spring = 'spring'
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,150 +1,184 @@
|
|||||||
'use strict';
|
|
||||||
/**
|
/**
|
||||||
* MiaoScript Event处理类
|
* MiaoScript Event处理类
|
||||||
*/
|
*/
|
||||||
import '@ms/core'
|
import i18n from '@ccms/i18n'
|
||||||
import '@ms/nashorn'
|
import { injectable, unmanaged } from '@ccms/container'
|
||||||
import { injectable } from '@ms/container'
|
|
||||||
|
|
||||||
const Thread = Java.type("java.lang.Thread");
|
const Thread = Java.type('java.lang.Thread')
|
||||||
|
|
||||||
export namespace event {
|
export namespace event {
|
||||||
|
/**
|
||||||
|
* 事件监听优先级
|
||||||
|
*/
|
||||||
|
export enum EventPriority {
|
||||||
|
LOWEST = "LOWEST",
|
||||||
|
LOW = "LOW",
|
||||||
|
NORMAL = "NORMAL",
|
||||||
|
HIGH = "HIGH",
|
||||||
|
HIGHEST = "HIGHEST",
|
||||||
|
MONITOR = "MONITOR",
|
||||||
|
}
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Event {
|
export abstract class Event {
|
||||||
|
// export EventPriority to blockly
|
||||||
|
public EventPriority = EventPriority;
|
||||||
|
|
||||||
private mapEvent = [];
|
private mapEvent = [];
|
||||||
private listenerMap = [];
|
private listenerMap = [];
|
||||||
private baseEventDir = '';
|
|
||||||
|
|
||||||
constructor(baseEventDir: string) {
|
protected baseEventDir = '';
|
||||||
this.baseEventDir = baseEventDir;
|
|
||||||
|
constructor(@unmanaged() baseEventDir: string) {
|
||||||
|
this.baseEventDir = baseEventDir
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 扫描包 org.bukkit.event 下的所有事件
|
* abstract event map function
|
||||||
* 映射简写名称 org.bukkit.event.player.PlayerLoginEvent => playerloginevent
|
* ig: org.bukkit.event.player.PlayerLoginEvent => playerloginevent
|
||||||
|
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
|
||||||
*/
|
*/
|
||||||
mapEventName() {
|
mapEventName() {
|
||||||
if (this.baseEventDir === "") {
|
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')) }
|
||||||
throw new Error("事件基础包名为空 无法进行事件映射!");
|
let count = 0
|
||||||
}
|
let jar = this.getJarFile(this.baseEventDir)
|
||||||
var count = 0;
|
let entries = jar.entries()
|
||||||
var dirs = Thread.currentThread().getContextClassLoader().getResources(this.baseEventDir);
|
while (entries.hasMoreElements()) {
|
||||||
while (dirs.hasMoreElements()) {
|
let entry = entries.nextElement()
|
||||||
var url = dirs.nextElement();
|
let name = entry.name
|
||||||
var protocol = url.protocol;
|
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
||||||
if (protocol === "jar") {
|
// replace name to qualifiedName
|
||||||
// noinspection JSUnresolvedVariable
|
let qualifiedName = name.replaceAll('/', '.')
|
||||||
var jar = url.openConnection().jarFile;
|
try {
|
||||||
var entries = jar.entries();
|
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6))
|
||||||
while (entries.hasMoreElements()) {
|
if (this.isValidEvent(clazz)) {
|
||||||
var entry = entries.nextElement();
|
let simpleName = this.class2Name(clazz).toLowerCase()
|
||||||
var name = entry.name;
|
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }))
|
||||||
// 以 org/bukkit/event 开头 并且以 .class 结尾
|
this.mapEvent[simpleName] = clazz
|
||||||
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
count++
|
||||||
var i = name.replaceAll('/', '.');
|
|
||||||
try {
|
|
||||||
var clz = base.getClass(i.substring(0, i.length - 6));
|
|
||||||
// 继承于 org.bukkit.event.Event 访问符为Public
|
|
||||||
if (this.isValidEvent(clz)) {
|
|
||||||
var simpleName = this.class2Name(clz).toLowerCase();
|
|
||||||
console.debug(`Mapping Event [${clz.canonicalName}] => ${simpleName}`);
|
|
||||||
this.mapEvent[simpleName] = clz;
|
|
||||||
count++;
|
|
||||||
}
|
|
||||||
} catch (ex) {
|
|
||||||
//ignore already loaded class
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
} catch (ex) {
|
||||||
|
//ignore already loaded class
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return count;
|
return count
|
||||||
};
|
}
|
||||||
|
|
||||||
class2Name(clazz) {
|
getJarFile(resource: string, loader?: any) {
|
||||||
return clazz.simpleName;
|
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource)
|
||||||
};
|
if (dirs.hasMoreElements()) {
|
||||||
|
let url = dirs.nextElement()
|
||||||
|
if (url.protocol === "jar") { return url.openConnection().jarFile }
|
||||||
|
}
|
||||||
|
throw new Error(i18n.translate("ms.api.event.resource.not.found", { resource }))
|
||||||
|
}
|
||||||
|
|
||||||
name2Class(name, event) {
|
class2Name(clazz: any) {
|
||||||
var eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
|
return clazz.simpleName
|
||||||
|
}
|
||||||
|
|
||||||
|
name2Class(name: any, event: string) {
|
||||||
|
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']
|
||||||
if (!eventCls) {
|
if (!eventCls) {
|
||||||
try {
|
try {
|
||||||
eventCls = base.getClass(eventCls);
|
eventCls = base.getClass(eventCls)
|
||||||
this.mapEvent[event] = eventCls;
|
this.mapEvent[event] = eventCls
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console(`§6插件 §b${name} §6注册事件 §c${event} §6失败 §4事件未找到!`);
|
console.i18n("ms.api.event.not.found", { name, event })
|
||||||
console.ex(new Error(`插件 ${name} 注册事件 ${event} 失败 事件未找到!`));
|
return
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return eventCls;
|
return eventCls
|
||||||
};
|
}
|
||||||
|
|
||||||
execute(name, exec, eventCls) {
|
execute(name, exec, eventCls) {
|
||||||
return (...args) => {
|
return (...args: any[]) => {
|
||||||
try {
|
try {
|
||||||
var time = new Date().getTime()
|
let event = args[args.length - 1]
|
||||||
exec(args[args.length - 1]);
|
if (eventCls.isAssignableFrom(event.getClass())) {
|
||||||
var cost = new Date().getTime() - time;
|
let time = Date.now()
|
||||||
if (cost > 20) {
|
exec(event)
|
||||||
console.console(`§c注意! §6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件 §c耗时 §4${cost}ms !`)
|
let cost = Date.now() - time
|
||||||
|
if (cost > 20) {
|
||||||
|
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console(`§6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件时发生异常 §4${ex}`);
|
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
||||||
console.ex(ex);
|
console.ex(ex)
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 添加事件监听
|
* 添加事件监听
|
||||||
* @param jsp
|
* @param plugin {any}
|
||||||
* @param event
|
* @param event {string}
|
||||||
* @param exec {function}
|
* @param exec {function}
|
||||||
* @param priority [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
||||||
* @param ignoreCancel
|
* @param ignoreCancel
|
||||||
*/
|
*/
|
||||||
listen(jsp, event, exec, priority, ignoreCancel) {
|
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
|
||||||
if (!jsp || !jsp.description || !jsp.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"))
|
||||||
var name = jsp.description.name;
|
var name = plugin.description.name
|
||||||
var eventCls = this.name2Class(name, event);
|
var eventCls = this.name2Class(name, event)
|
||||||
if (!eventCls) { return; }
|
if (!eventCls) { return }
|
||||||
if (typeof priority === 'boolean') {
|
if (typeof priority === 'boolean') {
|
||||||
ignoreCancel = priority;
|
ignoreCancel = priority
|
||||||
priority = 'NORMAL';
|
priority = EventPriority.NORMAL
|
||||||
}
|
}
|
||||||
priority = priority || 'NORMAL';
|
priority = priority || EventPriority.NORMAL
|
||||||
ignoreCancel = ignoreCancel || false;
|
ignoreCancel = ignoreCancel || false
|
||||||
|
// @ts-ignore
|
||||||
|
let executor = exec.name || exec.executor || '[anonymous]'
|
||||||
// noinspection JSUnusedGlobalSymbols
|
// noinspection JSUnusedGlobalSymbols
|
||||||
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
|
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel)
|
||||||
var listenerMap = this.listenerMap;
|
var listenerMap = this.listenerMap
|
||||||
// 添加到缓存 用于关闭插件的时候关闭事件
|
// add to cache Be used for close plugin to close event
|
||||||
if (!listenerMap[name]) listenerMap[name] = [];
|
if (!listenerMap[name]) listenerMap[name] = []
|
||||||
var offExec = () => {
|
var off = () => {
|
||||||
this.unregister(eventCls, listener);
|
if (off['offed']) return
|
||||||
console.debug(`插件 ${name} 注销事件 ${this.class2Name(eventCls)}`);
|
off['offed'] = true
|
||||||
};
|
this.unregister(eventCls, listener)
|
||||||
var off = {
|
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls), exec: executor }))
|
||||||
event: eventCls,
|
}
|
||||||
listener: listener,
|
listenerMap[name].push(off)
|
||||||
off: offExec
|
|
||||||
};
|
|
||||||
listenerMap[name].push(off);
|
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
console.debug(`插件 ${name} 注册事件 ${this.class2Name(eventCls)} => ${exec.name || '匿名方法'}`);
|
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls), exec: executor }))
|
||||||
return off;
|
return off
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭插件监听任务
|
||||||
|
* @param plugin 插件
|
||||||
|
*/
|
||||||
disable(plugin: any) {
|
disable(plugin: any) {
|
||||||
var eventCache = this.listenerMap[plugin.description.name];
|
var eventCache = this.listenerMap[plugin.description.name]
|
||||||
if (eventCache) {
|
if (eventCache) {
|
||||||
eventCache.forEach(t => t.off());
|
eventCache.forEach(off => off())
|
||||||
delete this.listenerMap[plugin.description.name];
|
delete this.listenerMap[plugin.description.name]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract isValidEvent(clazz: any): boolean;
|
/**
|
||||||
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
|
* 判断
|
||||||
abstract unregister(event: any, listener: any): void;
|
* @param clazz 事件类
|
||||||
|
*/
|
||||||
|
abstract isValidEvent(clazz: any): boolean
|
||||||
|
/**
|
||||||
|
* 注册事件
|
||||||
|
* @param eventCls 事件类
|
||||||
|
* @param exec 执行器
|
||||||
|
* @param priority 优先级
|
||||||
|
* @param ignoreCancel 是否忽略已取消的事件
|
||||||
|
*/
|
||||||
|
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any
|
||||||
|
/**
|
||||||
|
* 取消监听事件
|
||||||
|
* @param event 事件
|
||||||
|
* @param listener 监听器
|
||||||
|
*/
|
||||||
|
abstract unregister(event: any, listener: any): void
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import './typings/global'
|
import "@ccms/nashorn"
|
||||||
|
|
||||||
|
export * from './chat'
|
||||||
|
export * from './task'
|
||||||
export * from './event'
|
export * from './event'
|
||||||
|
export * from './proxy'
|
||||||
export * from './console'
|
export * from './console'
|
||||||
|
export * from './channel'
|
||||||
export * from './command'
|
export * from './command'
|
||||||
|
export * from './constants'
|
||||||
export * from './interfaces'
|
export * from './interfaces'
|
||||||
|
|||||||
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 './plugin'
|
||||||
export * from './server'
|
export * from './server'
|
||||||
|
export * from './database'
|
||||||
|
|||||||
@@ -1,25 +1,182 @@
|
|||||||
import { Container } from "inversify";
|
import { injectable } from '@ccms/container'
|
||||||
|
|
||||||
export namespace plugin {
|
export namespace plugin {
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin
|
* MiaoScript Plugin
|
||||||
*/
|
*/
|
||||||
export const Plugin = Symbol("Plugin");
|
export const Plugin = Symbol("Plugin")
|
||||||
|
/**
|
||||||
|
* MiaoScript Plugin Folder
|
||||||
|
*/
|
||||||
|
export const PluginFolder = Symbol("PluginFolder")
|
||||||
/**
|
/**
|
||||||
* Runtime Plugin Instance
|
* Runtime Plugin Instance
|
||||||
*/
|
*/
|
||||||
export const PluginInstance = Symbol("PluginInstance");
|
export const PluginInstance = Symbol("PluginInstance")
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin Manager
|
* MiaoScript Plugin Manager Interface
|
||||||
*/
|
*/
|
||||||
export const PluginManager = Symbol("PluginManager");
|
@injectable()
|
||||||
|
export abstract class PluginManager {
|
||||||
|
abstract scan(folder: string): void
|
||||||
|
abstract build(): void
|
||||||
|
abstract loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
|
||||||
|
abstract load(...args: any[]): void
|
||||||
|
abstract enable(...args: any[]): void
|
||||||
|
abstract disable(...args: any[]): void
|
||||||
|
abstract reload(...args: any[]): void
|
||||||
|
abstract getPlugin(name: string): plugin.Plugin
|
||||||
|
abstract getPlugins(): Map<string, plugin.Plugin>
|
||||||
|
}
|
||||||
|
export const PluginScanner = Symbol("PluginScanner")
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin Manager
|
* 插件加载元信息
|
||||||
*/
|
*/
|
||||||
export interface PluginManager {
|
export interface PluginLoadMetadata {
|
||||||
scan(folder: string): void;
|
/**
|
||||||
load(container: Container): void;
|
* 插件加载类型
|
||||||
enable(): void;
|
*/
|
||||||
disable(): void;
|
type: 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
|
||||||
|
}
|
||||||
|
export interface BaseMetadata {
|
||||||
|
/**
|
||||||
|
* 名称 为空则为对象名称
|
||||||
|
*/
|
||||||
|
name?: string
|
||||||
|
/**
|
||||||
|
* 支持的服务器列表 为空则代表所有
|
||||||
|
*/
|
||||||
|
servers?: string[]
|
||||||
|
}
|
||||||
|
export interface PluginMetadata extends BaseMetadata {
|
||||||
|
/**
|
||||||
|
* 插件名称 不填默认为类名
|
||||||
|
*/
|
||||||
|
name?: string
|
||||||
|
/**
|
||||||
|
* 前缀
|
||||||
|
*/
|
||||||
|
prefix?: string
|
||||||
|
/**
|
||||||
|
* 插件版本 不填默认为 1.0.0
|
||||||
|
*/
|
||||||
|
version?: string
|
||||||
|
/**
|
||||||
|
* 插件作者 不填默认为 Unknow
|
||||||
|
*/
|
||||||
|
author?: string | string[]
|
||||||
|
/**
|
||||||
|
* 插件源文件 必须指定为 __filename
|
||||||
|
*/
|
||||||
|
source: string
|
||||||
|
/**
|
||||||
|
* 插件类型 默认为 ioc 执行 MiaoScript 加载逻辑
|
||||||
|
*/
|
||||||
|
type?: string
|
||||||
|
/**
|
||||||
|
* 插件加载信息
|
||||||
|
*/
|
||||||
|
loadMetadata?: PluginLoadMetadata
|
||||||
|
/**
|
||||||
|
* 插件本体
|
||||||
|
*/
|
||||||
|
target?: any
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
export namespace server {
|
|
||||||
export const ServerType = Symbol("ServerType");
|
|
||||||
export const Console = Symbol("Console");
|
|
||||||
}
|
|
||||||
140
packages/api/src/interfaces/server/index.ts
Normal file
140
packages/api/src/interfaces/server/index.ts
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
import { injectable, inject } from '@ccms/container'
|
||||||
|
|
||||||
|
import { NativePluginManager } from './native_plugin'
|
||||||
|
import { constants } from '../../constants'
|
||||||
|
|
||||||
|
export { NativePluginManager } from './native_plugin'
|
||||||
|
|
||||||
|
export namespace server {
|
||||||
|
/**
|
||||||
|
* Runtime ServerType
|
||||||
|
*/
|
||||||
|
export const ServerType = Symbol("ServerType")
|
||||||
|
/**
|
||||||
|
* Runtime Console
|
||||||
|
*/
|
||||||
|
export const Console = Symbol("Console")
|
||||||
|
/**
|
||||||
|
* Runtime Server Instance
|
||||||
|
*/
|
||||||
|
export const ServerInstance = Symbol("ServerInstance")
|
||||||
|
/**
|
||||||
|
* MiaoScript Server
|
||||||
|
*/
|
||||||
|
@injectable()
|
||||||
|
export abstract class Server {
|
||||||
|
getVersion(): string {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
getPlayer(name: string): any {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
getOnlinePlayers(): any[] {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
getConsoleSender(): any {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
getService(service: string): any {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
dispatchCommand(sender: string | any, command: string): boolean {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
getPluginsFolder(): string {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
getNativePluginManager(): NativePluginManager {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
getDedicatedServer?(): any {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
getNettyPipeline(): any {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
getRootLogger(): any {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@injectable()
|
||||||
|
export class ServerChecker {
|
||||||
|
@inject(ServerType)
|
||||||
|
private serverType: string
|
||||||
|
check(servers: string[]) {
|
||||||
|
// Not set servers -> allow
|
||||||
|
if (!servers || !servers.length) return true
|
||||||
|
// include !type -> deny
|
||||||
|
let denyServers = servers.filter(svr => svr.startsWith("!"))
|
||||||
|
if (denyServers.length !== 0) {
|
||||||
|
return !denyServers.includes(`!${this.serverType}`)
|
||||||
|
} else {
|
||||||
|
// only include -> allow
|
||||||
|
return servers.includes(this.serverType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@injectable()
|
||||||
|
export abstract class ReflectServer extends server.Server {
|
||||||
|
protected pipeline: any
|
||||||
|
protected rootLogger: any
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
this.reflect()
|
||||||
|
}
|
||||||
|
|
||||||
|
protected reflect() {
|
||||||
|
try {
|
||||||
|
let consoleServer = this.getDedicatedServer()
|
||||||
|
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!") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
6
packages/api/src/interfaces/server/native_plugin.ts
Normal file
6
packages/api/src/interfaces/server/native_plugin.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export interface NativePluginManager {
|
||||||
|
load(name: string): boolean;
|
||||||
|
unload(name: string): boolean;
|
||||||
|
reload(name: string): boolean;
|
||||||
|
delete(name: string): boolean;
|
||||||
|
}
|
||||||
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')
|
||||||
|
}
|
||||||
160
packages/api/src/proxy.ts
Normal file
160
packages/api/src/proxy.ts
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
import { provideSingleton, Autowired } from '@ccms/container'
|
||||||
|
import { channel } from './channel'
|
||||||
|
|
||||||
|
export namespace proxy {
|
||||||
|
const ByteArrayOutputStream = Java.type('java.io.ByteArrayOutputStream')
|
||||||
|
const DataOutputStream = Java.type('java.io.DataOutputStream')
|
||||||
|
namespace bungeecord {
|
||||||
|
const CHANNEL_NAME = "BungeeCord"
|
||||||
|
export class SubChannelBuilder {
|
||||||
|
private channel: channel.Channel
|
||||||
|
private player: any
|
||||||
|
private params: string[]
|
||||||
|
constructor(channel: channel.Channel, player: any) {
|
||||||
|
this.channel = channel
|
||||||
|
this.player = player
|
||||||
|
this.params = []
|
||||||
|
}
|
||||||
|
connect(server: string) {
|
||||||
|
this.params.push("Connect")
|
||||||
|
this.params.push(server)
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
connectOther(player: string, server: string) {
|
||||||
|
this.params.push("ConnectOther")
|
||||||
|
this.params.push(player)
|
||||||
|
this.params.push(server)
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
ip() {
|
||||||
|
this.params.push("IP")
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
ipOther(player: string) {
|
||||||
|
this.params.push("IPOther")
|
||||||
|
this.params.push(player)
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
playerCount(server: string | "ALL") {
|
||||||
|
this.params.push("PlayerCount")
|
||||||
|
this.params.push(server)
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Get a list of players connected on a certain server, or on ALL the servers.
|
||||||
|
* @param server count server
|
||||||
|
* Response:
|
||||||
|
* String server = in.readUTF(); // The name of the server you got the player list of, as given in args.
|
||||||
|
* String[] playerList = in.readUTF().split(", ");
|
||||||
|
*/
|
||||||
|
playerList(server: string | "ALL") {
|
||||||
|
this.params.push("PlayerList")
|
||||||
|
this.params.push(server)
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Get a list of server name strings, as defined in BungeeCord's config.yml
|
||||||
|
* Response:
|
||||||
|
* String[] serverList = in.readUTF().split(", ");
|
||||||
|
*/
|
||||||
|
getServers() {
|
||||||
|
this.params.push("GetServers")
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Get this server's name, as defined in BungeeCord's config.yml
|
||||||
|
*/
|
||||||
|
getServer() {
|
||||||
|
this.params.push("GetServer")
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
broadcast(message: string) {
|
||||||
|
this.message("ALL", message)
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Send a message (as in, a chat message) to the specified player.
|
||||||
|
* @param player who reciver message
|
||||||
|
* @param message message content
|
||||||
|
*/
|
||||||
|
message(player: string | "ALL", message: string) {
|
||||||
|
this.params.push("Message")
|
||||||
|
this.params.push(player)
|
||||||
|
this.params.push(message)
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Send a raw message (as in, a chat message) to the specified player. The advantage of this method over Message is that you can include click events and hover events.
|
||||||
|
* @param player who reciver message
|
||||||
|
* @param message message content
|
||||||
|
*/
|
||||||
|
messageRaw(player: string | "ALL", json: string) {
|
||||||
|
this.params.push("MessageRaw")
|
||||||
|
this.params.push(player)
|
||||||
|
this.params.push(json)
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
forwardAll(channel: string, data: any) {
|
||||||
|
return this.forward("ALL", channel, data)
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||||
|
* Remember, the sending and receiving server(s) need to have a player online.
|
||||||
|
* @param server reciver
|
||||||
|
* @param channel channelName
|
||||||
|
* @param data data
|
||||||
|
*/
|
||||||
|
forward(server: string | "ALL", channel: string, data: any) {
|
||||||
|
this.params.push("Forward")
|
||||||
|
this.params.push(server)
|
||||||
|
this.params.push(channel)
|
||||||
|
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||||
|
* Remember, the sending and receiving server(s) need to have a player online.
|
||||||
|
* @param server reciver
|
||||||
|
* @param channel channelName
|
||||||
|
* @param data data
|
||||||
|
*/
|
||||||
|
forwardToPlayer(server: string | "ALL", channel: string, data: any) {
|
||||||
|
this.params.push("Forward")
|
||||||
|
this.params.push(server)
|
||||||
|
this.params.push(channel)
|
||||||
|
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
generic(...args: string[]) {
|
||||||
|
args && this.params.concat(...args)
|
||||||
|
return this.finalSend()
|
||||||
|
}
|
||||||
|
private send(...middlewares: ((out: java.io.DataOutputStream) => void)[]) {
|
||||||
|
let byteArray = new ByteArrayOutputStream()
|
||||||
|
let out = new DataOutputStream(byteArray)
|
||||||
|
this.params.forEach(utf => out.writeUTF(utf))
|
||||||
|
for (let middleware of middlewares) {
|
||||||
|
middleware(out)
|
||||||
|
}
|
||||||
|
return this.channel.send(this.player, CHANNEL_NAME, byteArray.toByteArray())
|
||||||
|
}
|
||||||
|
private finalSend() {
|
||||||
|
return {
|
||||||
|
send: this.send.bind(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@provideSingleton(BungeeCord)
|
||||||
|
export class BungeeCord {
|
||||||
|
@Autowired()
|
||||||
|
private channel: channel.Channel
|
||||||
|
/**
|
||||||
|
* 获得代理
|
||||||
|
* @param player 玩家
|
||||||
|
*/
|
||||||
|
for(player: any): bungeecord.SubChannelBuilder {
|
||||||
|
return new bungeecord.SubChannelBuilder(this.channel, player)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
127
packages/api/src/task.ts
Normal file
127
packages/api/src/task.ts
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
import { plugin } from './index'
|
||||||
|
import { injectable } from '@ccms/container'
|
||||||
|
|
||||||
|
export namespace task {
|
||||||
|
@injectable()
|
||||||
|
export abstract class TaskManager {
|
||||||
|
protected cacheTasks = new Map<string, task.Task[]>()
|
||||||
|
|
||||||
|
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
||||||
|
if (!this.cacheTasks.has(plugin.description.name)) {
|
||||||
|
this.cacheTasks.set(plugin.description.name, [])
|
||||||
|
}
|
||||||
|
this.cacheTasks.get(plugin.description.name).push(task)
|
||||||
|
return task
|
||||||
|
}
|
||||||
|
protected pluginDisable(plugin: plugin.Plugin) {
|
||||||
|
if (this.cacheTasks.has(plugin.description.name)) {
|
||||||
|
this.cacheTasks.get(plugin.description.name).forEach(task => task.cancel())
|
||||||
|
this.cacheTasks.delete(plugin.description.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 创建任务
|
||||||
|
* @param func 任务内容
|
||||||
|
*/
|
||||||
|
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
||||||
|
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
||||||
|
let task = this.create0(func)
|
||||||
|
if (plugin) { return this.pluginCreate(plugin, task) }
|
||||||
|
return task
|
||||||
|
}
|
||||||
|
abstract create0(func: Function): task.Task
|
||||||
|
/**
|
||||||
|
* 在主线程执行代码
|
||||||
|
* @param func 执行内容
|
||||||
|
*/
|
||||||
|
abstract callSyncMethod(func: Function): any
|
||||||
|
/**
|
||||||
|
* 关闭任务管理器
|
||||||
|
*/
|
||||||
|
disable(plugin?: plugin.Plugin) {
|
||||||
|
if (plugin) { return this.pluginDisable(plugin) }
|
||||||
|
this.disable0()
|
||||||
|
}
|
||||||
|
abstract disable0()
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 任务抽象
|
||||||
|
*/
|
||||||
|
export abstract class Task {
|
||||||
|
protected plugin: any
|
||||||
|
protected func: Function
|
||||||
|
protected isAsync: boolean = false;
|
||||||
|
protected laterTime: number = 0;
|
||||||
|
protected interval: number = 0;
|
||||||
|
|
||||||
|
constructor(plugin: any, func: Function) {
|
||||||
|
this.plugin = plugin
|
||||||
|
this.func = func
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置任务异步执行
|
||||||
|
* @param isAsync 是否异步
|
||||||
|
*/
|
||||||
|
async(isAsync: boolean = true): task.Task {
|
||||||
|
this.isAsync = isAsync
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置任务延时执行
|
||||||
|
* @param tick 延时 Tick
|
||||||
|
*/
|
||||||
|
later(tick: number): task.Task {
|
||||||
|
this.laterTime = tick
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置任务循环执行
|
||||||
|
* @param tick 循环时间 Tick
|
||||||
|
*/
|
||||||
|
timer(tick: number): task.Task {
|
||||||
|
this.interval = tick
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消任务
|
||||||
|
*/
|
||||||
|
cancel(): boolean {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
|
||||||
|
protected run(...args: any[]): void {
|
||||||
|
try {
|
||||||
|
this.func(...args)
|
||||||
|
} catch (ex) {
|
||||||
|
console.console('§4插件执行任务时发生错误', ex)
|
||||||
|
console.ex(ex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交任务
|
||||||
|
* @param args 任务参数
|
||||||
|
*/
|
||||||
|
submit(...args: any[]): Cancelable {
|
||||||
|
let cancelable = this.submit0(...args)
|
||||||
|
this.cancel = cancelable.cancel
|
||||||
|
return cancelable
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交任务
|
||||||
|
* @param args 任务参数
|
||||||
|
*/
|
||||||
|
abstract submit0(...args: any[]): Cancelable
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 返可取消的对象
|
||||||
|
*/
|
||||||
|
export interface Cancelable {
|
||||||
|
cancel(): boolean
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
declare global {
|
|
||||||
namespace NodeJS {
|
|
||||||
interface Global {
|
|
||||||
logger: any;
|
|
||||||
debug: boolean;
|
|
||||||
noop: Function;
|
|
||||||
console: Console;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var root: string;
|
|
||||||
var base: Core;
|
|
||||||
var ScriptEngineContextHolder: any;
|
|
||||||
function engineLoad(str: string): any;
|
|
||||||
interface Core {
|
|
||||||
getClass(name: String);
|
|
||||||
}
|
|
||||||
interface Console {
|
|
||||||
ex(err: Error): void;
|
|
||||||
stack(err: Error): string[];
|
|
||||||
sender(...args: any): void;
|
|
||||||
console(...args: any): void;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export { }
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
export interface CommandInfo {
|
|
||||||
aliases: string[];
|
|
||||||
description: string;
|
|
||||||
}
|
|
||||||
export interface PluginInfo {
|
|
||||||
description: PluginDescription;
|
|
||||||
}
|
|
||||||
export interface PluginDescription {
|
|
||||||
name: string;
|
|
||||||
version: string;
|
|
||||||
author: string;
|
|
||||||
commands: { [key: string]: CommandInfo };
|
|
||||||
}
|
|
||||||
4
packages/bukkit/.gitignore
vendored
4
packages/bukkit/.gitignore
vendored
@@ -1,4 +0,0 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
|
||||||
/package-lock.json
|
|
||||||
/yarn.lock
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
src
|
|
||||||
test
|
|
||||||
typings
|
|
||||||
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
|
|
||||||
type_definitions
|
|
||||||
1
packages/bukkit/.npmignore
Symbolic link
1
packages/bukkit/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../../.npmignore
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/bukkit",
|
"name": "@ccms/bukkit",
|
||||||
"version": "0.0.0",
|
"version": "0.9.5",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript bukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
"minecraft",
|
"minecraft",
|
||||||
@@ -12,23 +12,21 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"publishConfig": {
|
|
||||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
|
||||||
},
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@javatypes/spigot-api": "^0.0.2",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^4.0.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.0.0",
|
"@ccms/api": "^0.9.5",
|
||||||
"@ms/common": "^0.0.0",
|
"@ccms/common": "^0.9.4",
|
||||||
"@ms/container": "^0.0.0"
|
"@ccms/container": "^0.9.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
54
packages/bukkit/src/channel.ts
Normal file
54
packages/bukkit/src/channel.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import { channel, plugin } from '@ccms/api'
|
||||||
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
|
const Bukkit = org.bukkit.Bukkit
|
||||||
|
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
|
||||||
|
const Messenger = Bukkit.getMessenger()
|
||||||
|
|
||||||
|
@provideSingleton(channel.Channel)
|
||||||
|
export class BukkitChannel extends channel.Channel {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any
|
||||||
|
private cacheChannel = new Map<string, any[]>()
|
||||||
|
/**
|
||||||
|
* 给玩家发送通道消息
|
||||||
|
* @param player 接受消息的玩家
|
||||||
|
* @param channel 通道
|
||||||
|
* @param data 数据
|
||||||
|
*/
|
||||||
|
send(player: any, channel: string, data: number[]) {
|
||||||
|
player.sendPluginMessage(this.pluginInstance, channel, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册通道监听器
|
||||||
|
* @param channel 通道
|
||||||
|
* @param listener 监听器
|
||||||
|
*/
|
||||||
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
|
if (!this.cacheChannel.has(channel)) this.cacheChannel.set(channel, [])
|
||||||
|
this.cacheChannel.get(channel).push(listener)
|
||||||
|
let pluginMessageListener = new PluginMessageListener({
|
||||||
|
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
||||||
|
try {
|
||||||
|
listener(data, { channel, player, data })
|
||||||
|
} catch (error) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, pluginMessageListener)
|
||||||
|
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel)
|
||||||
|
return pluginMessageListener
|
||||||
|
}
|
||||||
|
unregister(channel: string, listener: any) {
|
||||||
|
if (!this.cacheChannel.has(channel)) return
|
||||||
|
let cacheListener = this.cacheChannel.get(channel)
|
||||||
|
cacheListener = cacheListener.filter(l => l != listener)
|
||||||
|
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel, listener)
|
||||||
|
if (cacheListener.length == 0) {
|
||||||
|
this.cacheChannel.delete(channel)
|
||||||
|
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
23
packages/bukkit/src/chat.ts
Normal file
23
packages/bukkit/src/chat.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { chat } from '@ccms/api'
|
||||||
|
import { provideSingleton } from '@ccms/container'
|
||||||
|
import bukkitChat from './enhance/chat'
|
||||||
|
|
||||||
|
@provideSingleton(chat.Chat)
|
||||||
|
export class BukkitChat extends chat.Chat {
|
||||||
|
sendJson(sender: any, json: string | object, type = 0) {
|
||||||
|
bukkitChat.send(sender, typeof json === "string" ? json : JSON.stringify(json), type)
|
||||||
|
}
|
||||||
|
sendMessage(sender: any, message: string) {
|
||||||
|
this.sendJson(sender, { text: message }, 0)
|
||||||
|
}
|
||||||
|
sendActionBar(sender: any, message: string) {
|
||||||
|
this.sendJson(sender, { text: message }, 2)
|
||||||
|
}
|
||||||
|
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
||||||
|
try {
|
||||||
|
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
|
||||||
|
} catch (error) {
|
||||||
|
sender.sendTitle(title, subtitle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,92 +1,50 @@
|
|||||||
import '@ms/nashorn'
|
import '@ccms/nashorn'
|
||||||
|
|
||||||
import { command, plugin } from '@ms/api'
|
import { command, plugin } from '@ccms/api'
|
||||||
import * as reflect from '@ms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
import { injectable, postConstruct, inject } from '@ms/container'
|
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||||
|
|
||||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
let Bukkit = org.bukkit.Bukkit
|
||||||
let Arrays = Java.type('java.util.Arrays');
|
let TabCompleter = Java.type('org.bukkit.command.TabCompleter')
|
||||||
let TabCompleter = Java.type('org.bukkit.command.TabCompleter');
|
let PluginCommand = Java.type('org.bukkit.command.PluginCommand')
|
||||||
let PluginCommand = Java.type('org.bukkit.command.PluginCommand');
|
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor')
|
||||||
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor');
|
|
||||||
|
|
||||||
@injectable()
|
@provideSingleton(command.Command)
|
||||||
export class BukkitCommand extends command.Command {
|
export class BukkitCommand extends command.Command {
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
private commandMap: any;
|
private commandMap: any
|
||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
init() {
|
init() {
|
||||||
this.commandMap = reflect.on(Bukkit.pluginManager).get('commandMap').get();
|
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get()
|
||||||
}
|
}
|
||||||
|
create(plugin: any, command: string) {
|
||||||
enable(jsp) {
|
var cmd = this.commandMap.getCommand(command)
|
||||||
var commands = jsp.description.commands;
|
|
||||||
if (commands) {
|
|
||||||
var pluginCommands = [];
|
|
||||||
for (var name in commands) {
|
|
||||||
var command = commands[name];
|
|
||||||
if (typeof command !== 'object') continue;
|
|
||||||
command.name = name;
|
|
||||||
var newCmd = this.create(jsp, command);
|
|
||||||
if (command.description) newCmd.setDescription(command.description);
|
|
||||||
if (command.usage) newCmd.setUsage(command.usage);
|
|
||||||
if (command.aliases) newCmd.setAliases(Arrays.asList(command.aliases));
|
|
||||||
if (command.permission) newCmd.setPermission(command.permission);
|
|
||||||
if (command['permission-message']) newCmd.setPermissionMessage(command['permission-message']);
|
|
||||||
pluginCommands.push(newCmd);
|
|
||||||
console.debug(`插件 ${jsp.description.name} 注册命令 ${name} ...`);
|
|
||||||
}
|
|
||||||
this.commandMap.registerAll(jsp.description.name, Arrays.asList(pluginCommands));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
disable(jsp) {
|
|
||||||
var commands = jsp.description.commands;
|
|
||||||
if (commands) {
|
|
||||||
for (var name in commands) {
|
|
||||||
//TODO 删除插件命令
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
create(jsp, command) {
|
|
||||||
var cmd = this.commandMap.getCommand(command.name)
|
|
||||||
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
||||||
cmd = reflect.on(PluginCommand).create(command.name, this.pluginInstance).get();
|
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get()
|
||||||
this.commandMap.register(jsp.description.name, cmd);
|
this.commandMap.register(plugin.description.name, cmd)
|
||||||
return cmd;
|
return cmd
|
||||||
}
|
}
|
||||||
|
remove(plugin: any, command: string) {
|
||||||
onCommand(jsp, c, cmd) {
|
var cmd = this.commandMap.getCommand(command)
|
||||||
|
if (cmd && cmd instanceof PluginCommand) {
|
||||||
|
cmd.unregister(this.commandMap)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tabComplete(sender: any, input: string, index?: number): string[] {
|
||||||
|
return Java.from(this.commandMap.tabComplete(sender, input))
|
||||||
|
}
|
||||||
|
onCommand(plugin: any, command: any, executor: Function) {
|
||||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||||
c.setExecutor(new CommandExecutor({
|
command.setExecutor(new CommandExecutor({
|
||||||
onCommand: function(sender, _, command, args) {
|
onCommand: super.setExecutor(plugin, command, executor)
|
||||||
try {
|
}))
|
||||||
return cmd(sender, command, Java.from(args));
|
|
||||||
} catch (ex) {
|
|
||||||
console.console(`§6玩家 §a${sender.name} §6执行 §b${jsp.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常 §4${ex}`);
|
|
||||||
console.ex(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||||
onTabComplete(jsp, c, tab) {
|
|
||||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||||
// noinspection JSUnusedGlobalSymbols
|
command.setTabCompleter(new TabCompleter({
|
||||||
c.setTabCompleter(new TabCompleter({
|
onTabComplete: super.setTabCompleter(plugin, command, tabCompleter)
|
||||||
onTabComplete: function(sender, _, command, args) {
|
}))
|
||||||
try {
|
|
||||||
var token = args[args.length - 1];
|
|
||||||
var complete = tab(sender, command, Java.from(args)) || [];
|
|
||||||
return Arrays.asList(complete.copyPartialMatches(token, []));
|
|
||||||
} catch (ex) {
|
|
||||||
console.console(`§6玩家 §a${sender.name} §6执行 §b${jsp.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6补全时发生异常 §4${ex}`);
|
|
||||||
console.ex(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,20 @@
|
|||||||
import { MiaoScriptConsole } from '@ms/api'
|
import { MiaoScriptConsole } from '@ccms/api'
|
||||||
|
|
||||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
let Bukkit = org.bukkit.Bukkit;
|
||||||
let CommandSender = Java.type("org.bukkit.command.CommandSender");
|
|
||||||
|
|
||||||
export class BukkitConsole extends MiaoScriptConsole {
|
export class BukkitConsole extends MiaoScriptConsole {
|
||||||
sender(sender, ...args) {
|
sender(sender, ...args) {
|
||||||
if (!(sender instanceof CommandSender)) {
|
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
|
||||||
this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
|
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (args[0].toString() === "[object Array]") {
|
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
||||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||||
} else {
|
} else {
|
||||||
sender.sendMessage(this.prefix + args.join(' '));
|
sender.sendMessage(this.prefix + args.join(' '));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console(...args): void {
|
console(...args: string[]): void {
|
||||||
this.sender(Bukkit.consoleSender, args.join(' '));
|
this.sender(Bukkit.getConsoleSender(), args.join(' '));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
118
packages/bukkit/src/enhance/chat.ts
Normal file
118
packages/bukkit/src/enhance/chat.ts
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
/*global Java, base, module, exports, require*/
|
||||||
|
let ChatSerializer: any
|
||||||
|
let nmsChatSerializerMethodName: string
|
||||||
|
let PacketPlayOutChat: any
|
||||||
|
let chatMessageTypes: any
|
||||||
|
|
||||||
|
let RemapUtils: any
|
||||||
|
|
||||||
|
let playerConnectionFieldName: string
|
||||||
|
let sendPacketMethodName: string
|
||||||
|
|
||||||
|
let above_1_16 = false
|
||||||
|
let downgrade = false
|
||||||
|
/**
|
||||||
|
* 获取NMS版本
|
||||||
|
*/
|
||||||
|
let nmsVersion = undefined
|
||||||
|
/**
|
||||||
|
* 获取NMS类
|
||||||
|
*/
|
||||||
|
function nmsCls(name: string) {
|
||||||
|
return base.getClass(['net.minecraft.server', nmsVersion, name].join('.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
function remapMethod(clazz: any, origin: string, test: string, params: any) {
|
||||||
|
try {
|
||||||
|
return clazz.getMethod(origin, params)
|
||||||
|
} catch (ex) {
|
||||||
|
if (RemapUtils) {
|
||||||
|
return clazz.getMethod(RemapUtils.mapMethod(clazz, origin, params), params)
|
||||||
|
} else {
|
||||||
|
return clazz.getMethod(test, params)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function remapFieldName(clazz: any, origin: string, test: string) {
|
||||||
|
try {
|
||||||
|
return clazz.getField(origin)
|
||||||
|
} catch (ex) {
|
||||||
|
if (RemapUtils) {
|
||||||
|
return clazz.getField(RemapUtils.mapFieldName(clazz, origin))
|
||||||
|
} else {
|
||||||
|
return clazz.getField(test)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
//@ts-ignore
|
||||||
|
nmsVersion = org.bukkit.Bukkit.server.class.name.split('.')[3]
|
||||||
|
try {
|
||||||
|
RemapUtils = Java.type('catserver.server.remapper.RemapUtils')
|
||||||
|
} catch (ex) {
|
||||||
|
}
|
||||||
|
let nmsChatSerializerClass = nmsCls(nmsVersion.split("_")[1] > 7 ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer")
|
||||||
|
let nmsChatSerializerMethod = remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||||
|
nmsChatSerializerMethodName = nmsChatSerializerMethod.getName()
|
||||||
|
ChatSerializer = Java.type(nmsChatSerializerClass.getName())
|
||||||
|
let packetTypeClass = nmsCls("PacketPlayOutChat")
|
||||||
|
PacketPlayOutChat = Java.type(packetTypeClass.getName())
|
||||||
|
let packetTypeConstructor: { parameterTypes: any[] }
|
||||||
|
let constructors = packetTypeClass.constructors
|
||||||
|
Java.from(constructors).forEach(function (c) {
|
||||||
|
if (c.parameterTypes.length === 2) {
|
||||||
|
packetTypeConstructor = c
|
||||||
|
}
|
||||||
|
if (c.parameterTypes.length === 3) {
|
||||||
|
packetTypeConstructor = c
|
||||||
|
above_1_16 = true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
let parameterTypes = packetTypeConstructor.parameterTypes
|
||||||
|
let nmsChatMessageTypeClass = parameterTypes[1]
|
||||||
|
if (nmsChatMessageTypeClass.isEnum()) {
|
||||||
|
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
|
||||||
|
}
|
||||||
|
let playerConnectionField = remapFieldName(nmsCls('EntityPlayer'), 'playerConnection', 'field_71135_a')
|
||||||
|
playerConnectionFieldName = playerConnectionField.getName()
|
||||||
|
sendPacketMethodName = remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', nmsCls('Packet')).getName()
|
||||||
|
}
|
||||||
|
|
||||||
|
function json(sender: { name: string }, json: string) {
|
||||||
|
if (downgrade) {
|
||||||
|
return '/tellraw ' + sender.name + ' ' + json
|
||||||
|
} else {
|
||||||
|
send(sender, json, 0)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(sender: any, json: any, type: number) {
|
||||||
|
let packet
|
||||||
|
if (above_1_16) {
|
||||||
|
packet = new PacketPlayOutChat(ChatSerializer[nmsChatSerializerMethodName](json), chatMessageTypes == null ? type : chatMessageTypes[type], sender.getUniqueId())
|
||||||
|
} else {
|
||||||
|
packet = new PacketPlayOutChat(ChatSerializer[nmsChatSerializerMethodName](json), chatMessageTypes == null ? type : chatMessageTypes[type])
|
||||||
|
}
|
||||||
|
sendPacket(sender, packet)
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendPacket(player: { handle: { [x: string]: { [x: string]: (arg0: any) => void } } }, p: any) {
|
||||||
|
player.handle[playerConnectionFieldName][sendPacketMethodName](p)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
init()
|
||||||
|
} catch (ex) {
|
||||||
|
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
||||||
|
downgrade = true
|
||||||
|
}
|
||||||
|
|
||||||
|
let chat = {
|
||||||
|
json,
|
||||||
|
send
|
||||||
|
}
|
||||||
|
|
||||||
|
export default chat
|
||||||
48
packages/bukkit/src/event.ts
Normal file
48
packages/bukkit/src/event.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { event, plugin } from '@ccms/api'
|
||||||
|
import { inject, provideSingleton } from '@ccms/container';
|
||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
|
const Bukkit = Java.type("org.bukkit.Bukkit");
|
||||||
|
const Event = Java.type("org.bukkit.event.Event");
|
||||||
|
const Modifier = Java.type("java.lang.reflect.Modifier");
|
||||||
|
const Listener = Java.type("org.bukkit.event.Listener");
|
||||||
|
const EventPriority = Java.type("org.bukkit.event.EventPriority");
|
||||||
|
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
|
||||||
|
|
||||||
|
@provideSingleton(event.Event)
|
||||||
|
export class BukkitEvent extends event.Event {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super('org/bukkit/event');
|
||||||
|
}
|
||||||
|
|
||||||
|
getJarFile(resource: string) {
|
||||||
|
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
|
||||||
|
}
|
||||||
|
isValidEvent(clazz: any): boolean {
|
||||||
|
// 继承于 org.bukkit.event.Event
|
||||||
|
return Event.class.isAssignableFrom(clazz) &&
|
||||||
|
// 访问符为Public
|
||||||
|
Modifier.isPublic(clazz.getModifiers()) &&
|
||||||
|
// 不是抽象类
|
||||||
|
!Modifier.isAbstract(clazz.getModifiers());
|
||||||
|
}
|
||||||
|
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
|
||||||
|
let listener = new Listener({});
|
||||||
|
Bukkit.pluginManager.registerEvent(
|
||||||
|
eventCls,
|
||||||
|
listener,
|
||||||
|
EventPriority[priority],
|
||||||
|
new EventExecutor({
|
||||||
|
execute: exec
|
||||||
|
}),
|
||||||
|
this.pluginInstance,
|
||||||
|
ignoreCancel);
|
||||||
|
return listener;
|
||||||
|
}
|
||||||
|
unregister(event: any, listener: any): void {
|
||||||
|
reflect.on(event).call('getHandlerList').get().unregister(listener);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,16 @@
|
|||||||
import { server, plugin, command } from '@ms/api'
|
/// <reference types="@javatypes/spigot-api" />
|
||||||
import { DefaultContainer as container } from '@ms/container'
|
|
||||||
|
import { server } from '@ccms/api'
|
||||||
|
import { Container } from '@ccms/container'
|
||||||
|
|
||||||
import { BukkitConsole } from './console'
|
import { BukkitConsole } from './console'
|
||||||
import { BukkitCommand } from './command';
|
import './chat'
|
||||||
|
import './task'
|
||||||
|
import './event'
|
||||||
|
import './server'
|
||||||
|
import './command'
|
||||||
|
import './channel'
|
||||||
|
|
||||||
let BukkitServerType = 'bukkit';
|
export default function BukkitImpl(container: Container) {
|
||||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
container.bind(server.Console).toConstantValue(BukkitConsole)
|
||||||
|
}
|
||||||
container.bind(server.Console).toConstantValue(BukkitConsole);
|
|
||||||
container.bind(server.ServerType).toConstantValue(BukkitServerType);
|
|
||||||
container.bind(plugin.PluginInstance).toConstantValue(Bukkit.pluginManager.getPlugin('MiaoScript'));
|
|
||||||
|
|
||||||
container.bind(command.Command).to(BukkitCommand).inSingletonScope();
|
|
||||||
|
|||||||
57
packages/bukkit/src/server.ts
Normal file
57
packages/bukkit/src/server.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { server, constants } from '@ccms/api'
|
||||||
|
import { provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
import chat from './enhance/chat'
|
||||||
|
|
||||||
|
let Bukkit = org.bukkit.Bukkit
|
||||||
|
|
||||||
|
@provideSingleton(server.Server)
|
||||||
|
export class BukkitServer extends server.ReflectServer {
|
||||||
|
private pluginsFolder: string
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath()
|
||||||
|
}
|
||||||
|
|
||||||
|
getPlayer(name: string) {
|
||||||
|
return Bukkit.getPlayer(name)
|
||||||
|
}
|
||||||
|
getVersion(): string {
|
||||||
|
return Bukkit.getVersion()
|
||||||
|
}
|
||||||
|
getOnlinePlayers() {
|
||||||
|
return Bukkit.getOnlinePlayers() as unknown as any[]
|
||||||
|
}
|
||||||
|
getConsoleSender() {
|
||||||
|
return Bukkit.getConsoleSender()
|
||||||
|
}
|
||||||
|
getService(service: string) {
|
||||||
|
return Bukkit.getServicesManager().getRegistration(base.getClass(service))?.getProvider()
|
||||||
|
}
|
||||||
|
dispatchCommand(sender: string | any, command: string): boolean {
|
||||||
|
if (typeof sender === 'string') {
|
||||||
|
sender = this.getPlayer(sender)
|
||||||
|
}
|
||||||
|
return Bukkit.dispatchCommand(sender, command)
|
||||||
|
}
|
||||||
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
|
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
|
||||||
|
}
|
||||||
|
getPluginsFolder(): string {
|
||||||
|
return this.pluginsFolder
|
||||||
|
}
|
||||||
|
getNativePluginManager() {
|
||||||
|
return Bukkit.getPluginManager() as any
|
||||||
|
}
|
||||||
|
getDedicatedServer() {
|
||||||
|
return reflect.on(Bukkit.getServer()).get('console').get()
|
||||||
|
}
|
||||||
|
getNettyPipeline() {
|
||||||
|
return this.pipeline
|
||||||
|
}
|
||||||
|
getRootLogger() {
|
||||||
|
return this.rootLogger
|
||||||
|
}
|
||||||
|
}
|
||||||
34
packages/bukkit/src/task.ts
Normal file
34
packages/bukkit/src/task.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { task, plugin } from '@ccms/api'
|
||||||
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
|
const Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
|
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable')
|
||||||
|
const Callable = Java.type('java.util.concurrent.Callable')
|
||||||
|
|
||||||
|
@provideSingleton(task.TaskManager)
|
||||||
|
export class BukkitTaskManager extends task.TaskManager {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any
|
||||||
|
|
||||||
|
create0(func: Function): task.Task {
|
||||||
|
return new BukkitTask(this.pluginInstance, func)
|
||||||
|
}
|
||||||
|
callSyncMethod(func: Function): any {
|
||||||
|
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
||||||
|
}
|
||||||
|
disable0() {
|
||||||
|
Bukkit.getScheduler().cancelTasks(this.pluginInstance)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BukkitTask extends task.Task {
|
||||||
|
submit0(...args: any[]): task.Cancelable {
|
||||||
|
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
||||||
|
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||||
|
if (this.interval) {
|
||||||
|
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||||
|
} else {
|
||||||
|
return run[funcName](this.plugin, this.laterTime)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
1
packages/bungee/.npmignore
Symbolic link
1
packages/bungee/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../../.npmignore
|
||||||
32
packages/bungee/package.json
Normal file
32
packages/bungee/package.json
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"name": "@ccms/bungee",
|
||||||
|
"version": "0.9.5",
|
||||||
|
"description": "MiaoScript bungee 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/bungee-api": "^0.0.2",
|
||||||
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^4.0.3"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@ccms/api": "^0.9.5",
|
||||||
|
"@ccms/common": "^0.9.4",
|
||||||
|
"@ccms/container": "^0.9.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
25
packages/bungee/src/channel.ts
Normal file
25
packages/bungee/src/channel.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { channel, event } from '@ccms/api'
|
||||||
|
import { provideSingleton, inject } from '@ccms/container'
|
||||||
|
|
||||||
|
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||||
|
|
||||||
|
@provideSingleton(channel.Channel)
|
||||||
|
export class BungeeChannel extends channel.Channel {
|
||||||
|
@inject(event.Event)
|
||||||
|
private eventManager: event.Event
|
||||||
|
|
||||||
|
send(player: any, channel: string, data: any) {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
|
Bungee.registerChannel(channel)
|
||||||
|
// console.console('§6[§eWARN§6] §eMiaoScript channel in BungeeCord only register. you need self hanler PluginMessageEvent!')
|
||||||
|
return this.eventManager.listen({ description: { name: channel } }, "PluginMessageEvent", (event: net.md_5.bungee.api.event.PluginMessageEvent) => {
|
||||||
|
listener(event.getData(), event)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
unregister(channel: string, off: any) {
|
||||||
|
Bungee.unregisterChannel(channel)
|
||||||
|
off()
|
||||||
|
}
|
||||||
|
}
|
||||||
65
packages/bungee/src/command.ts
Normal file
65
packages/bungee/src/command.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { command, plugin } from "@ccms/api";
|
||||||
|
import { inject, provideSingleton } from "@ccms/container";
|
||||||
|
|
||||||
|
const Arrays = Java.type('java.util.Arrays')
|
||||||
|
const Command = Java.extend(Java.type('net.md_5.bungee.api.plugin.Command'), Java.type('net.md_5.bungee.api.plugin.TabExecutor'));
|
||||||
|
const createCommand = eval(`
|
||||||
|
function(cls, name, exec, tab){
|
||||||
|
return new cls(name) {
|
||||||
|
execute: exec,
|
||||||
|
onTabComplete: tab
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
|
||||||
|
@provideSingleton(command.Command)
|
||||||
|
export class BungeeCommand extends command.Command {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any;
|
||||||
|
private pluginManager: net.md_5.bungee.api.plugin.PluginManager = base.getInstance().getProxy().getPluginManager();
|
||||||
|
private commandMapping: any[] = [];
|
||||||
|
|
||||||
|
create(plugin: any, command: string) {
|
||||||
|
let commandKey = this.getCommandKey(plugin, command);
|
||||||
|
let commandCallable = new SimpleCommand(command);
|
||||||
|
this.pluginManager.registerCommand(this.pluginInstance, commandCallable.callable)
|
||||||
|
this.commandMapping[commandKey] = commandCallable.callable;
|
||||||
|
return commandCallable;
|
||||||
|
}
|
||||||
|
remove(plugin: any, command: string) {
|
||||||
|
var commandKey = this.getCommandKey(plugin, command);
|
||||||
|
if (this.commandMapping[commandKey]) {
|
||||||
|
this.pluginManager.unregisterCommand(this.commandMapping[commandKey])
|
||||||
|
delete this.commandMapping[commandKey];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onCommand(plugin: any, command: any, executor: Function) {
|
||||||
|
command.setExecutor(super.setExecutor(plugin, command, executor));
|
||||||
|
}
|
||||||
|
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||||
|
command.setTabComplete(super.setTabCompleter(plugin, command, tabCompleter))
|
||||||
|
}
|
||||||
|
|
||||||
|
private getCommandKey(plugin: any, command: string) {
|
||||||
|
return plugin.description.name.toLowerCase() + ":" + command;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SimpleCommand {
|
||||||
|
public callable: any;
|
||||||
|
private name: string;
|
||||||
|
private executor: Function;
|
||||||
|
private tabComplete: Function = () => [];
|
||||||
|
|
||||||
|
constructor(command: string) {
|
||||||
|
this.name = command;
|
||||||
|
this.callable = createCommand(Command, command,
|
||||||
|
(sender, args) => this.executor(sender, '', command, args),
|
||||||
|
(sender, args) => Arrays.asList(this.tabComplete(sender, '', command, args))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setExecutor = (executor: Function) => this.executor = executor;
|
||||||
|
setTabComplete = (tabComplete: Function) => this.tabComplete = tabComplete;
|
||||||
|
toString = () => `Bungee SimpleCommand(${this.name})`
|
||||||
|
}
|
||||||
27
packages/bungee/src/console.ts
Normal file
27
packages/bungee/src/console.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import '@ccms/nashorn'
|
||||||
|
import { plugin, MiaoScriptConsole } from '@ccms/api'
|
||||||
|
import { inject, injectable } from "@ccms/container";
|
||||||
|
|
||||||
|
let CommandSender = Java.type("net.md_5.bungee.api.CommandSender")
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class BungeeConsole extends MiaoScriptConsole {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any
|
||||||
|
private proxyServer: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||||
|
|
||||||
|
sender(sender, ...args) {
|
||||||
|
if (!(sender instanceof CommandSender)) {
|
||||||
|
this.error('第一个参数未实现 net.md_5.bungee.api.CommandSender 无法发送消息!')
|
||||||
|
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): void {
|
||||||
|
this.sender(this.proxyServer.getConsole(), args.join(' '));
|
||||||
|
}
|
||||||
|
}
|
||||||
117
packages/bungee/src/event.ts
Normal file
117
packages/bungee/src/event.ts
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
import { event } from '@ccms/api'
|
||||||
|
import { provideSingleton, postConstruct } from '@ccms/container'
|
||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
|
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||||
|
const Event = Java.type("net.md_5.bungee.api.plugin.Event");
|
||||||
|
const Modifier = Java.type("java.lang.reflect.Modifier");
|
||||||
|
const ProxyClass = Java.type(base.getProxyClass().name);
|
||||||
|
const ProxyMethod = reflect.on(base.getProxyClass()).method("method");
|
||||||
|
const HashMap = Java.type('java.util.HashMap');
|
||||||
|
const ReflectMethodArray = Java.type('java.lang.reflect.Method[]');
|
||||||
|
|
||||||
|
const Byte = Java.type('java.lang.Byte');
|
||||||
|
const EventPriority = [];
|
||||||
|
EventPriority[event.EventPriority.LOWEST] = Byte.valueOf(-64);
|
||||||
|
EventPriority[event.EventPriority.LOW] = -Byte.valueOf(32);
|
||||||
|
EventPriority[event.EventPriority.NORMAL] = Byte.valueOf(0);
|
||||||
|
EventPriority[event.EventPriority.HIGH] = Byte.valueOf(32);
|
||||||
|
EventPriority[event.EventPriority.HIGHEST] = Byte.valueOf(64);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bungee Event Impl
|
||||||
|
*/
|
||||||
|
@provideSingleton(event.Event)
|
||||||
|
export class BungeeEvent extends event.Event {
|
||||||
|
private pluginManager = Bungee.getPluginManager()
|
||||||
|
|
||||||
|
// EventBus
|
||||||
|
private eventBus: any;
|
||||||
|
// private final Lock lock = new ReentrantLock();
|
||||||
|
private lock: any;
|
||||||
|
// private final Map<Class<?>, Map<Byte, Map<Object, Method[]>>> byListenerAndPriority = new HashMap<>();
|
||||||
|
private byListenerAndPriority: any;
|
||||||
|
// bakeHandlers(Class<?> eventClass)
|
||||||
|
private bakeHandlers: any;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super('net/md_5/bungee/api/event');
|
||||||
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
init() {
|
||||||
|
this.eventBus = reflect.on(this.pluginManager).get('eventBus').get();
|
||||||
|
this.lock = reflect.on(this.eventBus).get('lock').get()
|
||||||
|
this.byListenerAndPriority = reflect.on(this.eventBus).get('byListenerAndPriority').get();
|
||||||
|
this.bakeHandlers = reflect.accessible(reflect.on(this.eventBus).method("bakeHandlers"));
|
||||||
|
}
|
||||||
|
|
||||||
|
isValidEvent(clazz: any): boolean {
|
||||||
|
//继承于 net.md_5.bungee.api.plugin.Event
|
||||||
|
return Event.class.isAssignableFrom(clazz) &&
|
||||||
|
// 访问符为Public
|
||||||
|
Modifier.isPublic(clazz.getModifiers()) &&
|
||||||
|
// 不是抽象类
|
||||||
|
!Modifier.isAbstract(clazz.getModifiers());
|
||||||
|
}
|
||||||
|
|
||||||
|
register(eventCls: any, exec: Function, priority: event.EventPriority = event.EventPriority.NORMAL, ignoreCancel: boolean = true) {
|
||||||
|
this.lock.lock()
|
||||||
|
try {
|
||||||
|
// private final Map<类, Map<优先级, Map<监听器, 方法[]>>> byListenerAndPriority = new HashMap<>();
|
||||||
|
// this.byListenerAndPriority.put(eventCls)
|
||||||
|
// Map<优先级, Map<监听器, 方法[]>>
|
||||||
|
let prioritiesMap = this.byListenerAndPriority.get(eventCls);
|
||||||
|
if (prioritiesMap == null) {
|
||||||
|
prioritiesMap = new HashMap();
|
||||||
|
this.byListenerAndPriority.put(eventCls, prioritiesMap);
|
||||||
|
}
|
||||||
|
// Map<监听器, 方法[]>
|
||||||
|
let currentPriorityMap = prioritiesMap.get(EventPriority[priority]);
|
||||||
|
if (currentPriorityMap == null) {
|
||||||
|
currentPriorityMap = new HashMap();
|
||||||
|
prioritiesMap.put(EventPriority[priority], currentPriorityMap);
|
||||||
|
}
|
||||||
|
let listener = new ProxyClass(ScriptEngineContextHolder.getEngine(), "exec(args)", { exec, priority: EventPriority[priority] })
|
||||||
|
// 方法[]
|
||||||
|
let methods = new ReflectMethodArray(1);
|
||||||
|
methods[0] = ProxyMethod;
|
||||||
|
currentPriorityMap.put(listener, methods);
|
||||||
|
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||||
|
return listener;
|
||||||
|
} catch (ex) {
|
||||||
|
console.ex(ex)
|
||||||
|
} finally {
|
||||||
|
this.lock.unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unregister(eventCls: any, listener: any): void {
|
||||||
|
this.lock.lock()
|
||||||
|
try {
|
||||||
|
// private final Map<类, Map<优先级, Map<监听器, 方法[]>>> byListenerAndPriority = new HashMap<>();
|
||||||
|
// Map<优先级, Map<监听器, 方法[]>>
|
||||||
|
let prioritiesMap = this.byListenerAndPriority.get(eventCls);
|
||||||
|
if (prioritiesMap != null) {
|
||||||
|
let bindings = reflect.on(listener).get("bindings").get();
|
||||||
|
let priority = bindings["priority"];
|
||||||
|
// Map<监听器, 方法[]>
|
||||||
|
let currentPriorityMap = prioritiesMap.get(priority);
|
||||||
|
if (currentPriorityMap != null) {
|
||||||
|
currentPriorityMap.remove(listener);
|
||||||
|
if (currentPriorityMap.isEmpty()) {
|
||||||
|
prioritiesMap.remove(priority);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (prioritiesMap.isEmpty()) {
|
||||||
|
this.byListenerAndPriority.remove(eventCls);
|
||||||
|
}
|
||||||
|
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||||
|
}
|
||||||
|
} catch (ex) {
|
||||||
|
console.ex(ex)
|
||||||
|
} finally {
|
||||||
|
this.lock.unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
15
packages/bungee/src/index.ts
Normal file
15
packages/bungee/src/index.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
/// <reference types="@javatypes/bungee-api" />
|
||||||
|
|
||||||
|
import { server } from '@ccms/api'
|
||||||
|
import { Container } from '@ccms/container'
|
||||||
|
|
||||||
|
import { BungeeConsole } from './console';
|
||||||
|
import './event';
|
||||||
|
import './server';
|
||||||
|
import './command';
|
||||||
|
import './channel';
|
||||||
|
import './task';
|
||||||
|
|
||||||
|
export default function BungeeImpl(container: Container) {
|
||||||
|
container.bind(server.Console).toConstantValue(BungeeConsole);
|
||||||
|
}
|
||||||
82
packages/bungee/src/server.ts
Normal file
82
packages/bungee/src/server.ts
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import { server, task } from '@ccms/api'
|
||||||
|
import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
||||||
|
|
||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
|
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||||
|
|
||||||
|
@provideSingleton(server.Server)
|
||||||
|
export class BungeeServer implements server.Server {
|
||||||
|
private pluginsFolder: string
|
||||||
|
private pipeline: any
|
||||||
|
private rootLogger: any
|
||||||
|
|
||||||
|
@inject(task.TaskManager)
|
||||||
|
private task: task.TaskManager
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath()
|
||||||
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
initialize() {
|
||||||
|
let count = 0
|
||||||
|
let wait = this.task.create(() => {
|
||||||
|
try {
|
||||||
|
// @ts-ignore
|
||||||
|
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
||||||
|
wait.cancel()
|
||||||
|
} catch (ex) {
|
||||||
|
count++
|
||||||
|
if (count > 50) {
|
||||||
|
console.error('Reflect BungeeCord netty channel pipeline error time > 50times. Err: ' + ex)
|
||||||
|
wait.cancel()
|
||||||
|
} else {
|
||||||
|
console.warn('Wait BungeeCord start ready to get netty channel pipeline. Err: ' + ex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}).later(10).timer(20).submit()
|
||||||
|
try {
|
||||||
|
this.rootLogger = Bungee.getLogger()
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Can't found rootLogger!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getPlayer(name: string) {
|
||||||
|
return Bungee.getPlayer(name)
|
||||||
|
}
|
||||||
|
getVersion(): string {
|
||||||
|
return Bungee.getVersion()
|
||||||
|
}
|
||||||
|
getOnlinePlayers() {
|
||||||
|
return Bungee.getPlayers()
|
||||||
|
}
|
||||||
|
getConsoleSender() {
|
||||||
|
return Bungee.getConsole()
|
||||||
|
}
|
||||||
|
getService(service: string) {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
dispatchCommand(sender: string | any, command: string): boolean {
|
||||||
|
if (typeof sender === 'string') {
|
||||||
|
sender = this.getPlayer(sender)
|
||||||
|
}
|
||||||
|
return Bungee.getPluginManager().dispatchCommand(sender, command)
|
||||||
|
}
|
||||||
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
|
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
|
||||||
|
}
|
||||||
|
getPluginsFolder(): string {
|
||||||
|
return this.pluginsFolder
|
||||||
|
}
|
||||||
|
getNativePluginManager() {
|
||||||
|
return Bungee.getPluginManager() as any
|
||||||
|
}
|
||||||
|
getNettyPipeline() {
|
||||||
|
return this.pipeline
|
||||||
|
}
|
||||||
|
getRootLogger() {
|
||||||
|
return this.rootLogger
|
||||||
|
}
|
||||||
|
}
|
||||||
35
packages/bungee/src/task.ts
Normal file
35
packages/bungee/src/task.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { task, plugin } from '@ccms/api'
|
||||||
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
|
var Runnable = Java.type('java.lang.Runnable')
|
||||||
|
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||||
|
|
||||||
|
@provideSingleton(task.TaskManager)
|
||||||
|
export class BungeeTaskManager extends task.TaskManager {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any
|
||||||
|
|
||||||
|
create0(func: Function): task.Task {
|
||||||
|
return new BungeeTask(this.pluginInstance, func)
|
||||||
|
}
|
||||||
|
callSyncMethod(func: Function): any {
|
||||||
|
return func()
|
||||||
|
}
|
||||||
|
disable0() {
|
||||||
|
this.pluginInstance.getProxy().getScheduler().cancel(this.pluginInstance)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BungeeTask extends task.Task {
|
||||||
|
submit0(...args: any[]): task.Cancelable {
|
||||||
|
let run = new Runnable({ run: () => this.run(...args) })
|
||||||
|
if (this.isAsync) {
|
||||||
|
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||||
|
}
|
||||||
|
if (this.interval) {
|
||||||
|
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
||||||
|
} else {
|
||||||
|
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
8
packages/bungee/tsconfig.json
Normal file
8
packages/bungee/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": "src",
|
||||||
|
"outDir": "dist",
|
||||||
|
"allowJs": true
|
||||||
|
}
|
||||||
|
}
|
||||||
1
packages/client/.npmignore
Symbolic link
1
packages/client/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../../.npmignore
|
||||||
31
packages/client/package.json
Normal file
31
packages/client/package.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"private": true,
|
||||||
|
"name": "@ccms/client",
|
||||||
|
"version": "0.9.4",
|
||||||
|
"description": "MiaoScript client 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": {
|
||||||
|
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
|
||||||
|
"clean": "rimraf dist",
|
||||||
|
"watch": "tsc --watch",
|
||||||
|
"build": "yarn clean && tsc",
|
||||||
|
"start": "node dist/index.js",
|
||||||
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"minecraft-protocol": "^1.16.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^4.0.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
101
packages/client/src/color.ts
Normal file
101
packages/client/src/color.ts
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
class MessagePart {
|
||||||
|
text: string
|
||||||
|
color: string
|
||||||
|
clickEvent: MessagePartEvent
|
||||||
|
hoverEvent: MessagePartEvent
|
||||||
|
translate: string
|
||||||
|
with: MessagePart[]
|
||||||
|
extra: MessagePart[]
|
||||||
|
}
|
||||||
|
|
||||||
|
class MessagePartEvent {
|
||||||
|
action: string
|
||||||
|
value: string
|
||||||
|
}
|
||||||
|
|
||||||
|
var colorMap = []
|
||||||
|
colorMap['0'] = '38;5;0'
|
||||||
|
colorMap['1'] = '38;5;4'
|
||||||
|
colorMap['2'] = '38;5;2'
|
||||||
|
colorMap['3'] = '38;5;6'
|
||||||
|
colorMap['4'] = '38;5;1'
|
||||||
|
colorMap['5'] = '38;5;5'
|
||||||
|
colorMap['6'] = '38;5;3'
|
||||||
|
colorMap['7'] = '38;5;7'
|
||||||
|
colorMap['8'] = '38;5;8'
|
||||||
|
colorMap['9'] = '38;5;12'
|
||||||
|
colorMap['a'] = '38;5;10'
|
||||||
|
colorMap['b'] = '38;5;14'
|
||||||
|
colorMap['c'] = '38;5;9'
|
||||||
|
colorMap['d'] = '38;5;13'
|
||||||
|
colorMap['e'] = '38;5;11'
|
||||||
|
colorMap['f'] = '38;5;15'
|
||||||
|
colorMap['r'] = '0'
|
||||||
|
colorMap['l'] = '1'
|
||||||
|
colorMap['n'] = '4'
|
||||||
|
var regexMap = []
|
||||||
|
for (const c in colorMap) {
|
||||||
|
regexMap[colorMap[c]] = new RegExp(`§${c}`, "g")
|
||||||
|
}
|
||||||
|
function mcColor2ANSI(str) {
|
||||||
|
for (const regex in regexMap) {
|
||||||
|
str = str.replace(regexMap[regex], `\u001b[${regex}m`)
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
let jsonColorMap = {
|
||||||
|
"black": '0',
|
||||||
|
"dark_blue": '1',
|
||||||
|
"dark_green": '2',
|
||||||
|
"dark_aqua": '3',
|
||||||
|
"dark_red": '4',
|
||||||
|
"dark_purple": '5',
|
||||||
|
"gold": '6',
|
||||||
|
"gray": '7',
|
||||||
|
"dark_gray": '8',
|
||||||
|
"blue": '9',
|
||||||
|
"green": 'a',
|
||||||
|
"aqua": 'b',
|
||||||
|
"red": 'c',
|
||||||
|
"light_purple": 'd',
|
||||||
|
"yellow": 'e',
|
||||||
|
"white": 'f',
|
||||||
|
"obfuscated": 'k',
|
||||||
|
"bold": 'l',
|
||||||
|
"strikethrough": 'm',
|
||||||
|
"underline": 'n',
|
||||||
|
"italic": 'o',
|
||||||
|
"reset": 'r',
|
||||||
|
};
|
||||||
|
|
||||||
|
function json2text(json: MessagePart): string {
|
||||||
|
let temp = "";
|
||||||
|
if (json.color) {
|
||||||
|
temp += `§${jsonColorMap[json.color]}`
|
||||||
|
}
|
||||||
|
temp += json.text || json.translate || ''
|
||||||
|
if (json.extra) {
|
||||||
|
json.extra.forEach((ext) => {
|
||||||
|
temp += json2text(ext)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return temp += '§r'
|
||||||
|
}
|
||||||
|
|
||||||
|
function $(input: any) {
|
||||||
|
if (typeof input === "string") {
|
||||||
|
input = JSON.parse(input)
|
||||||
|
}
|
||||||
|
input = json2text(input) + '§r'
|
||||||
|
if (input.startsWith('§卐')) {
|
||||||
|
input = input.substring(2)
|
||||||
|
}
|
||||||
|
return mcColor2ANSI(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
json2text,
|
||||||
|
mcColor2ANSI,
|
||||||
|
$
|
||||||
|
}
|
||||||
33
packages/client/src/event.ts
Normal file
33
packages/client/src/event.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { $ } from './color'
|
||||||
|
|
||||||
|
export function attachEvents(client) {
|
||||||
|
client.on('chat', (packet) => {
|
||||||
|
// Listen for chat messages and echo them back.
|
||||||
|
var jsonMsg = JSON.parse(packet.message)
|
||||||
|
console.log($(jsonMsg))
|
||||||
|
})
|
||||||
|
client.on('state', (newState, oldState) => {
|
||||||
|
console.log('Client Change State', oldState, 'to', newState)
|
||||||
|
let targetServer = process.argv[6]
|
||||||
|
if (newState == "play" && targetServer) {
|
||||||
|
setTimeout(() => {
|
||||||
|
client.write('chat', {
|
||||||
|
message: '/server ' + targetServer
|
||||||
|
})
|
||||||
|
}, 3000)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
client.on('update_health', (packet) => {
|
||||||
|
if (packet.health <= 0) {
|
||||||
|
console.log("Player Dead Auto Respawn...")
|
||||||
|
client.write('client_command', { payload: 0 })
|
||||||
|
} else if (packet.health > 0) {
|
||||||
|
}
|
||||||
|
})
|
||||||
|
client.on('kick_disconnect', (packet) => {
|
||||||
|
console.log($(packet.reason))
|
||||||
|
})
|
||||||
|
client.on('disconnect', (packet) => {
|
||||||
|
console.log($(packet.reason))
|
||||||
|
})
|
||||||
|
}
|
||||||
14
packages/client/src/forge.ts
Normal file
14
packages/client/src/forge.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
export function attachForge(client) {
|
||||||
|
client.on('custom_payload', function(packet) {
|
||||||
|
if (packet.channel === 'FML|HS') {
|
||||||
|
client.write('custom_payload', {
|
||||||
|
channel: 'FML|HS',
|
||||||
|
data: Buffer.of(0x01, 0x02)
|
||||||
|
});
|
||||||
|
client.write('custom_payload', {
|
||||||
|
channel: 'FML|HS',
|
||||||
|
data: Buffer.of(0x02, 0x00)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
99
packages/client/src/index.ts
Normal file
99
packages/client/src/index.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
import { createInterface } from 'readline'
|
||||||
|
import { createClient } from 'minecraft-protocol'
|
||||||
|
|
||||||
|
import { attachForge } from './forge'
|
||||||
|
import { attachEvents } from './event'
|
||||||
|
|
||||||
|
let username = process.argv[2] || 'Mr_jtb'
|
||||||
|
let password = process.argv[3] || ''
|
||||||
|
let version = process.argv[4] || '1.12.2'
|
||||||
|
let readAddress = process.argv[5] || '192.168.2.5:25577'
|
||||||
|
let realAddress = readAddress.split(":")
|
||||||
|
let address = realAddress[0]
|
||||||
|
let port = parseInt(realAddress[1] || "25565")
|
||||||
|
let client = commandLineCreateClient()
|
||||||
|
|
||||||
|
function commandLineCreateClient() {
|
||||||
|
return createConnection(address, port, username, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
function createConnection(host: string, port: number, username: string, password: string) {
|
||||||
|
let client = createClient({
|
||||||
|
version,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
clientToken: 'd02c7f39-2376-45da-a5a5-50e24fa8b185',
|
||||||
|
//@ts-ignore
|
||||||
|
authServer: 'https://mcsso.yumc.pw/api/yggdrasil/authserver',
|
||||||
|
sessionServer: 'https://mcsso.yumc.pw/api/yggdrasil/sessionserver'
|
||||||
|
})
|
||||||
|
|
||||||
|
attachCommon(client)
|
||||||
|
attachForge(client)
|
||||||
|
attachEvents(client)
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
function attachCommon(client) {
|
||||||
|
client.on('error', (error) => {
|
||||||
|
console.log("Client Error", error)
|
||||||
|
})
|
||||||
|
client.on('end', (resone) => {
|
||||||
|
console.log("Client End Resone:", resone)
|
||||||
|
if (`${resone}` != "SocketClosed") {
|
||||||
|
setTimeout(() => {
|
||||||
|
client = commandLineCreateClient()
|
||||||
|
}, 500)
|
||||||
|
} else {
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const rl = createInterface({
|
||||||
|
input: process.stdin,
|
||||||
|
output: process.stdout,
|
||||||
|
completer: (line, func) => {
|
||||||
|
let args = line.split(' ')
|
||||||
|
let comp = args[args.length - 1]
|
||||||
|
client.once('tab_complete', (msg) => {
|
||||||
|
let mcts = msg.matches.filter(s => s)
|
||||||
|
func(null, [mcts, comp])
|
||||||
|
})
|
||||||
|
client.write('tab_complete', {
|
||||||
|
text: line
|
||||||
|
})
|
||||||
|
},
|
||||||
|
terminal: true,
|
||||||
|
prompt: ''
|
||||||
|
})
|
||||||
|
|
||||||
|
rl.on('line', function (line) {
|
||||||
|
switch (line) {
|
||||||
|
case "":
|
||||||
|
break
|
||||||
|
case "eval":
|
||||||
|
break
|
||||||
|
case "write":
|
||||||
|
break
|
||||||
|
case "/respawn":
|
||||||
|
client.write('client_command', { payload: 0 })
|
||||||
|
break
|
||||||
|
case "//reco":
|
||||||
|
client.end("")
|
||||||
|
client = commandLineCreateClient()
|
||||||
|
break
|
||||||
|
case "//quit":
|
||||||
|
console.info('Disconnected')
|
||||||
|
client.end("")
|
||||||
|
break
|
||||||
|
case "//end":
|
||||||
|
console.info('Forcibly ended client')
|
||||||
|
process.exit(0)
|
||||||
|
default:
|
||||||
|
client.write('chat', { message: line })
|
||||||
|
}
|
||||||
|
rl.prompt()
|
||||||
|
})
|
||||||
7
packages/client/tsconfig.json
Normal file
7
packages/client/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": "src",
|
||||||
|
"outDir": "dist"
|
||||||
|
}
|
||||||
|
}
|
||||||
4
packages/common/.gitignore
vendored
4
packages/common/.gitignore
vendored
@@ -1,4 +0,0 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
|
||||||
/package-lock.json
|
|
||||||
/yarn.lock
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
src
|
|
||||||
test
|
|
||||||
typings
|
|
||||||
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
|
|
||||||
type_definitions
|
|
||||||
1
packages/common/.npmignore
Symbolic link
1
packages/common/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../../.npmignore
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/common",
|
"name": "@ccms/common",
|
||||||
"version": "0.0.0",
|
"version": "0.9.4",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,21 +12,18 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"publishConfig": {
|
|
||||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
|
||||||
},
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@ccms/nashorn": "^0.9.4",
|
||||||
|
"@javatypes/jdk": "^0.0.2",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^4.0.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||||
"@ms/nashorn": "^0.0.0"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import '@ms/nashorn'
|
import '@ccms/nashorn'
|
||||||
|
|
||||||
/*global Java, base, module, exports, require, __FILE__*/
|
/*global Java, base, module, exports, require, __FILE__*/
|
||||||
const Path = Java.type("java.nio.file.Path");
|
const Path = Java.type("java.nio.file.Path");
|
||||||
@@ -12,8 +12,8 @@ const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
|||||||
/**
|
/**
|
||||||
* 用文件分割符合并路径
|
* 用文件分割符合并路径
|
||||||
*/
|
*/
|
||||||
export function concat() {
|
export function concat(...args: string[]) {
|
||||||
return Array.prototype.join.call(arguments, separatorChar);
|
return args.join(separatorChar);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,12 +23,10 @@ export function concat() {
|
|||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
export function file(...opts: any[]): any {
|
export function file(...opts: any[]): any {
|
||||||
if (!arguments[0]) {
|
if (!opts[0]) { throw new Error("文件名称不得为 undefined 或者 null !") }
|
||||||
console.warn("文件名称不得为 undefined 或者 null !");
|
switch (opts.length) {
|
||||||
}
|
|
||||||
switch (arguments.length) {
|
|
||||||
case 1:
|
case 1:
|
||||||
var f = arguments[0];
|
var f = opts[0];
|
||||||
if (f instanceof File) {
|
if (f instanceof File) {
|
||||||
return f;
|
return f;
|
||||||
}
|
}
|
||||||
@@ -40,7 +38,7 @@ export function file(...opts: any[]): any {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
return new File(file(arguments[0]), arguments[1]);
|
return new File(file(opts[0]), opts[1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +46,7 @@ export function file(...opts: any[]): any {
|
|||||||
* 创建目录
|
* 创建目录
|
||||||
* @param path
|
* @param path
|
||||||
*/
|
*/
|
||||||
export function mkdirs(path) {
|
export function mkdirs(path: any) {
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
file(path).parentFile.mkdirs();
|
file(path).parentFile.mkdirs();
|
||||||
}
|
}
|
||||||
@@ -57,7 +55,7 @@ export function mkdirs(path) {
|
|||||||
* 创建文件
|
* 创建文件
|
||||||
* @param file
|
* @param file
|
||||||
*/
|
*/
|
||||||
export function create(path) {
|
export function create(path: any) {
|
||||||
var f = file(path);
|
var f = file(path);
|
||||||
if (!f.exists()) {
|
if (!f.exists()) {
|
||||||
mkdirs(f);
|
mkdirs(f);
|
||||||
@@ -70,7 +68,7 @@ export function create(path) {
|
|||||||
* @param file
|
* @param file
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
export function path(f) {
|
export function path(f: any) {
|
||||||
return file(f).canonicalPath;
|
return file(f).canonicalPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +78,7 @@ export function path(f) {
|
|||||||
* @param target 目标文件
|
* @param target 目标文件
|
||||||
* @param override 是否覆盖
|
* @param override 是否覆盖
|
||||||
*/
|
*/
|
||||||
export function copy(inputStream, target, override) {
|
export function copy(inputStream: any, target: any, override: any) {
|
||||||
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
|
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,7 +141,7 @@ export function del(file) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (file.isDirectory()) {
|
if (file.isDirectory()) {
|
||||||
Files.list(file.toPath()).collect(Collector.toList()).forEach(function(f) {
|
Files.list(file.toPath()).collect(Collector.toList()).forEach(function (f) {
|
||||||
del(f);
|
del(f);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,155 +1,69 @@
|
|||||||
'use strict';
|
import * as querystring from 'querystring'
|
||||||
/**
|
|
||||||
* HTTP 网络类
|
|
||||||
* Created by 蒋天蓓 on 2017/2/9 0009.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/*global Java, base, module, exports, require, __FILE__*/
|
const URL = Java.type('java.net.URL')
|
||||||
|
const Paths = Java.type('java.nio.file.Paths')
|
||||||
|
const Files = Java.type('java.nio.file.Files')
|
||||||
|
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption')
|
||||||
|
|
||||||
var URL = Java.type("java.net.URL");
|
export type Method =
|
||||||
var UUID = Java.type("java.util.UUID");
|
| 'get' | 'GET'
|
||||||
var System = Java.type("java.lang.System");
|
| 'delete' | 'DELETE'
|
||||||
var Files = Java.type("java.nio.file.Files");
|
| 'head' | 'HEAD'
|
||||||
var Paths = Java.type("java.nio.file.Paths");
|
| 'options' | 'OPTIONS'
|
||||||
var JavaString = Java.type("java.lang.String");
|
| 'post' | 'POST'
|
||||||
var SecureRandom = Java.type("java.security.SecureRandom");
|
| 'put' | 'PUT'
|
||||||
|
| 'patch' | 'PATCH'
|
||||||
|
|
||||||
var SSLContext = Java.type("javax.net.ssl.SSLContext");
|
interface RequestConfig {
|
||||||
var HttpsURLConnection = Java.type("javax.net.ssl.HttpsURLConnection");
|
url?: string
|
||||||
|
method?: Method
|
||||||
|
headers?: { [key: string]: string }
|
||||||
|
params?: { [key: string]: string }
|
||||||
|
data?: any
|
||||||
|
}
|
||||||
|
|
||||||
var HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier");
|
function request(config: RequestConfig) {
|
||||||
var X509TrustManager = Java.type("javax.net.ssl.X509TrustManager");
|
// @ts-ignore
|
||||||
|
let xhr = new XMLHttpRequest()
|
||||||
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
|
xhr.open(config.method, config.url, false)
|
||||||
var TrustAnyHostnameVerifier = new HostnameVerifier({
|
for (const header in config.headers) {
|
||||||
verify: function(hostname, session) {
|
xhr.setRequestHeader(header, config.headers[header])
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
});
|
let body = config.data
|
||||||
|
if (body && typeof body !== "string") {
|
||||||
var SSLSocketFactory = function initSSLSocketFactory() {
|
switch (config.headers['Content-Type']) {
|
||||||
var sslContext = SSLContext.getInstance("TLS");
|
case "application/json":
|
||||||
// noinspection JSUnusedGlobalSymbols
|
body = JSON.stringify(body)
|
||||||
sslContext.init(null, [new X509TrustManager({
|
break
|
||||||
getAcceptedIssuers: function() {
|
case "application/x-www-form-urlencoded":
|
||||||
return null;
|
body = querystring.encode(body)
|
||||||
},
|
break
|
||||||
checkClientTrusted: function(chain, authType) {
|
|
||||||
},
|
|
||||||
checkServerTrusted: function(chain, authType) {
|
|
||||||
}
|
|
||||||
})], new SecureRandom());
|
|
||||||
return sslContext.getSocketFactory();
|
|
||||||
}();
|
|
||||||
|
|
||||||
var config = {
|
|
||||||
Charset: 'UTF-8',
|
|
||||||
ConnectTimeout: 10000,
|
|
||||||
ReadTimeout: 10000,
|
|
||||||
Debug: false
|
|
||||||
};
|
|
||||||
|
|
||||||
function open(url, method, header) {
|
|
||||||
// conn.setRequestProperty
|
|
||||||
var conn = new URL(url).openConnection();
|
|
||||||
if (conn instanceof HttpsURLConnection) {
|
|
||||||
conn.setHostnameVerifier(TrustAnyHostnameVerifier);
|
|
||||||
conn.setSSLSocketFactory(SSLSocketFactory);
|
|
||||||
}
|
|
||||||
conn.setRequestMethod(method);
|
|
||||||
conn.setDoOutput(true);
|
|
||||||
conn.setDoInput(true);
|
|
||||||
conn.setConnectTimeout(config.ConnectTimeout);
|
|
||||||
conn.setReadTimeout(config.ReadTimeout);
|
|
||||||
if (header) {
|
|
||||||
for (var key in header) {
|
|
||||||
// noinspection JSUnfilteredForInLoop
|
|
||||||
conn.setRequestProperty(key, header[key]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return conn;
|
xhr.send(body)
|
||||||
}
|
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
|
||||||
|
xhr.responseType = "json"
|
||||||
function buildUrl(url, params) {
|
|
||||||
if (params && Object.keys(params).length > 0) {
|
|
||||||
var queryStart = url.indexOf('?');
|
|
||||||
if (queryStart === -1) {
|
|
||||||
url += '?';
|
|
||||||
}
|
|
||||||
return url += object2URLSearchParams(params);
|
|
||||||
}
|
}
|
||||||
return url;
|
return xhr.get()
|
||||||
}
|
}
|
||||||
|
|
||||||
function request(config) {
|
function download(url: string, target: string) {
|
||||||
var conn = open(buildUrl(config.url, config.query), config.method, config.header);
|
console.debug(`Start Download file ${target} from ${url}....`)
|
||||||
try {
|
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING)
|
||||||
conn.connect();
|
console.debug(`File ${target} Download Complate...`)
|
||||||
var data = config.data;
|
}
|
||||||
if (data) {
|
|
||||||
var out = conn.getOutputStream();
|
function _proxy(method: Method) {
|
||||||
if (typeof data === "object") {
|
return function (url: string, data?: any, config: RequestConfig = {}) {
|
||||||
var type = config.header['Content-Type'];
|
if (!config.headers) { config.headers = {} }
|
||||||
switch (type) {
|
config.headers['Content-Type'] = config.headers['Content-Type'] ?? 'application/json'
|
||||||
case "application/x-www-form-urlencoded":
|
return request({ url, method, data, ...config })
|
||||||
data = object2URLSearchParams(data);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
data = JSON.stringify(data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out.write(new JavaString(data).getBytes(config.Charset));
|
|
||||||
out.flush();
|
|
||||||
out.close();
|
|
||||||
}
|
|
||||||
return response(conn);
|
|
||||||
} finally {
|
|
||||||
conn.disconnect();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function response(conn) {
|
export default {
|
||||||
var temp = Paths.get(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
|
get: _proxy('GET'),
|
||||||
Files.copy(conn.getInputStream(), temp);
|
post: _proxy('POST'),
|
||||||
var result = new JavaString(Files.readAllBytes(temp), config.Charset);
|
request,
|
||||||
var tempFile = temp.toFile();
|
download
|
||||||
tempFile.delete() || tempFile.deleteOnExit();
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function object2URLSearchParams(params) {
|
|
||||||
var temp: string[] = [];
|
|
||||||
for (var key in params) {
|
|
||||||
temp.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
|
||||||
}
|
|
||||||
return temp.join('&')
|
|
||||||
}
|
|
||||||
|
|
||||||
var http = {
|
|
||||||
config: config,
|
|
||||||
request: request
|
|
||||||
};
|
|
||||||
|
|
||||||
['GET', 'DELETE', 'HEAD', 'OPTIONS'].forEach(function(method) {
|
|
||||||
http[method.toLowerCase()] = function __likeGet__(url, data, config = {}) {
|
|
||||||
return this.request({
|
|
||||||
...config,
|
|
||||||
url: url,
|
|
||||||
method: method,
|
|
||||||
query: data
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
['POST', 'PUT', 'PATCH'].forEach(function(method) {
|
|
||||||
http[method.toLowerCase()] = function __likePost__(url, data, config) {
|
|
||||||
return this.request({
|
|
||||||
...config,
|
|
||||||
url: url,
|
|
||||||
method: method,
|
|
||||||
data: data
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export = http;
|
|
||||||
|
|||||||
1243
packages/common/src/qrcode.ts
Normal file
1243
packages/common/src/qrcode.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,186 +1,202 @@
|
|||||||
import '@ms/core'
|
/// <reference types="@javatypes/jdk" />
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 反射工具类
|
* 反射工具类
|
||||||
* Created by 蒋天蓓 on 2017/2/9 0009.
|
* Created by MiaoWoo on 2017/2/9 0009.
|
||||||
*/
|
*/
|
||||||
var JavaClass = Java.type('java.lang.Class');
|
const JavaClass = Java.type('java.lang.Class')
|
||||||
var JavaObject = Java.type('java.lang.Object')
|
const JavaObject = Java.type('java.lang.Object')
|
||||||
var NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
|
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
|
||||||
var methodCache = [];
|
const methodCache = []
|
||||||
|
|
||||||
class Reflect {
|
class Reflect {
|
||||||
private obj: any;
|
private obj: java.lang.Object
|
||||||
private class: any
|
private class: java.lang.Class<any>
|
||||||
|
|
||||||
constructor(obj: any) {
|
constructor(obj: any) {
|
||||||
|
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
|
||||||
if (obj instanceof JavaClass) {
|
if (obj instanceof JavaClass) {
|
||||||
this.obj = null;
|
this.obj = null
|
||||||
this.class = obj;
|
this.class = obj
|
||||||
} else {
|
} else {
|
||||||
this.obj = obj;
|
this.obj = obj
|
||||||
this.class = obj.class;
|
if (obj !== null && obj !== undefined && obj.class) {
|
||||||
|
this.class = obj.class
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
method(...args: any[]) {
|
method(name: string, ...args: java.lang.Class<any>[]) {
|
||||||
return declaredMethod(this.class, args[0], types(args.slice(1)));
|
return declaredMethod(this.class, name, ...args)
|
||||||
}
|
}
|
||||||
|
|
||||||
methods() {
|
methods() {
|
||||||
return Java.from(declaredMethods(this.class));
|
return Java.from(declaredMethods(this.class))
|
||||||
}
|
}
|
||||||
|
|
||||||
field(name) {
|
field(name: string | java.lang.String): Reflect {
|
||||||
try {
|
try {
|
||||||
// Try getting a public field
|
// Try getting a public field
|
||||||
var field = this.class.field(name);
|
let field = this.class.getField(name)
|
||||||
return on(field.get(this.obj));
|
return on(field.get(this.obj))
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
// Try again, getting a non-public field
|
// 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) {
|
|
||||||
return Java.from(declared ? this.class.declaredFields : this.class.fields);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
values(declared) {
|
fields(declared = false): java.lang.reflect.Field[] {
|
||||||
var cache = {};
|
return Java.from(declared ? this.class.getDeclaredFields() : this.class.getFields())
|
||||||
var feds = declared ? this.class.declaredFields : this.class.fields;
|
|
||||||
Java.from(feds).forEach(function(fed) {
|
|
||||||
cache[fed.name] = this.field(fed.name).get();
|
|
||||||
}.bind(this))
|
|
||||||
return cache;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
call(...args) {
|
values(declared = false) {
|
||||||
var params = args.slice(1);
|
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.field(field.getName()).get() }, {}) as any
|
||||||
var method = declaredMethod(this.class, args[0], types(params));
|
}
|
||||||
return on(method.invoke(this.get(), params));
|
|
||||||
};
|
|
||||||
|
|
||||||
get(...args) {
|
call(...args: any[]): Reflect {
|
||||||
return args.length === 1 ? this.field(args[0]) : this.obj;
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
// noinspection JSUnusedGlobalSymbols
|
get(): any
|
||||||
set(name, value) {
|
get(index: number, declared?: boolean): Reflect
|
||||||
accessible(declaredField(this.class, name)).set(this.obj, value);
|
get(prop: string): Reflect
|
||||||
return this;
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
create(...args) {
|
set(name: any, value: any): Reflect {
|
||||||
return on(declaredConstructor(this.class, args).newInstance(args));
|
accessible(declaredField(this.class, name)).set(this.obj, value)
|
||||||
};
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
create(...args): Reflect {
|
||||||
|
return on(declaredConstructor(this.class, args).newInstance(args))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get an array of types for an array of objects
|
* Get an array of types for an array of objects
|
||||||
*/
|
*/
|
||||||
function types(values, def?) {
|
function types(values: any[], def?: any) {
|
||||||
if (values === null) {
|
if (values === null) {
|
||||||
return [];
|
return []
|
||||||
}
|
}
|
||||||
var result = [];
|
let result: java.lang.Class<any>[] = []
|
||||||
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class));
|
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class))
|
||||||
return result;
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
function accessible(accessible) {
|
function accessible<T extends java.lang.reflect.AccessibleObject>(accessible: T): T {
|
||||||
if (accessible === null) {
|
if (!accessible?.isAccessible()) {
|
||||||
return null;
|
accessible.setAccessible(true)
|
||||||
}
|
}
|
||||||
if (!accessible.isAccessible()) {
|
return accessible
|
||||||
accessible.setAccessible(true);
|
|
||||||
}
|
|
||||||
return accessible;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredConstructor(clazz, param) {
|
function declaredConstructor(clazz, param) {
|
||||||
var constructor;
|
let constructor
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param));
|
constructor = clazz.getDeclaredConstructor(types(param))
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param, true));
|
constructor = clazz.getDeclaredConstructor(types(param, true))
|
||||||
} catch (ex) {
|
} 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) {
|
||||||
var field = null;
|
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
|
||||||
|
let target = clazz
|
||||||
|
let field = null
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
while (clazz !== JavaObject.class) {
|
while (target !== JavaObject.class) {
|
||||||
try {
|
try {
|
||||||
field = clazz.getDeclaredField(name);
|
field = target.getDeclaredField(name)
|
||||||
if (field !== null) {
|
if (field !== null) { break }
|
||||||
break;
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
clazz = clazz.getSuperclass();
|
if (target === undefined) { break }
|
||||||
|
target = target.getSuperclass()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (field === null) {
|
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) {
|
function declaredMethod(clazz: java.lang.Class<any>, name: string, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
||||||
var key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
|
let key = clazz.getName() + '.' + name + ':' + (clazzs || []).join(':')
|
||||||
if (!methodCache[key]) {
|
if (!methodCache[key]) {
|
||||||
try {
|
try {
|
||||||
methodCache[key] = clazz.getMethod(name, clazzs);
|
// @ts-ignore
|
||||||
|
methodCache[key] = clazz.getMethod(name, clazzs)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
|
try {
|
||||||
|
methodCache[key] = clazz.getDeclaredMethod(name, clazzs as any)
|
||||||
|
} catch (ex) {
|
||||||
|
for (const m of Java.from(declaredMethods(clazz))) {
|
||||||
|
if (m.getName() == name) {
|
||||||
|
methodCache[key] = m
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return methodCache[key];
|
return methodCache[key]
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethods(clazz) {
|
function declaredMethods(clazz: java.lang.Class<any>) {
|
||||||
return clazz.declaredMethods;
|
return clazz.getDeclaredMethods()
|
||||||
}
|
}
|
||||||
|
|
||||||
var classMethodsCache = [];
|
let classMethodsCache: any[] = []
|
||||||
|
|
||||||
function mapToObject(javaObj) {
|
function mapToObject(javaObj) {
|
||||||
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||||
var target = {};
|
let target = {}
|
||||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
|
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t))
|
||||||
return target;
|
return target
|
||||||
}
|
}
|
||||||
|
|
||||||
function getJavaObjectMethods(javaObj) {
|
function getJavaObjectMethods(javaObj) {
|
||||||
var className = javaObj.class.name;
|
let className = javaObj.class.name
|
||||||
if (!classMethodsCache[className]) {
|
if (!classMethodsCache[className]) {
|
||||||
var names = [];
|
let names: any[] = []
|
||||||
var methods = javaObj.class.methods;
|
let methods = javaObj.class.methods
|
||||||
for (var i in 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) {
|
function mapMethod(target, source, name) {
|
||||||
target[name] = function __SimpleDynamicMethod__(...args) {
|
target[name] = function __SimpleDynamicMethod__(...args) {
|
||||||
if (args.length > 0) {
|
if (args.length > 0) {
|
||||||
return source[name](args);
|
return source[name](args)
|
||||||
} else {
|
} else {
|
||||||
return source[name]();
|
return source[name]()
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function on(obj) {
|
function on(obj) {
|
||||||
if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
||||||
return new Reflect(obj);
|
return new Reflect(obj)
|
||||||
}
|
}
|
||||||
|
|
||||||
export = {
|
export = {
|
||||||
@@ -188,4 +204,4 @@ export = {
|
|||||||
accessible,
|
accessible,
|
||||||
declaredMethods,
|
declaredMethods,
|
||||||
mapToObject
|
mapToObject
|
||||||
};
|
}
|
||||||
|
|||||||
109
packages/common/src/tellraw.ts
Normal file
109
packages/common/src/tellraw.ts
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
class ChatMessagePart {
|
||||||
|
private internal: any = {}
|
||||||
|
|
||||||
|
get text() {
|
||||||
|
return this.internal.text
|
||||||
|
}
|
||||||
|
set text(text: string) {
|
||||||
|
this.internal.text = text
|
||||||
|
}
|
||||||
|
|
||||||
|
click(action: string, value: string) {
|
||||||
|
this.internal.clickEvent = { action, value }
|
||||||
|
}
|
||||||
|
|
||||||
|
hover(action: string, value: string) {
|
||||||
|
this.internal.hoverEvent = { action, value }
|
||||||
|
}
|
||||||
|
|
||||||
|
convert() {
|
||||||
|
return this.internal;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Tellraw {
|
||||||
|
static duplicateChar = '§卐'
|
||||||
|
static create() {
|
||||||
|
return new Tellraw().then(Tellraw.duplicateChar);
|
||||||
|
}
|
||||||
|
|
||||||
|
private cache: string = '';
|
||||||
|
private parts = [new ChatMessagePart()];
|
||||||
|
|
||||||
|
then(part: ChatMessagePart | string) {
|
||||||
|
if (typeof part === "string") {
|
||||||
|
var newPart = new ChatMessagePart();
|
||||||
|
newPart.text = part
|
||||||
|
this.then(newPart);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
var last = this.latest();
|
||||||
|
if (!last.text) {
|
||||||
|
last.text = part.text;
|
||||||
|
} else {
|
||||||
|
this.parts.push(part);
|
||||||
|
}
|
||||||
|
this.cache = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
text(text: string) {
|
||||||
|
this.latest().text = text;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
tip(text: string) {
|
||||||
|
this.latest().hover("show_text", text);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
item(text: string) {
|
||||||
|
this.latest().hover("show_item", text);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
command(command: string) {
|
||||||
|
this.latest().click("run_command", command);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
suggest(url: string) {
|
||||||
|
this.latest().click("suggest_command", url);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
file(path: string) {
|
||||||
|
this.latest().click("open_file", path);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
link(url: string) {
|
||||||
|
this.latest().click("open_url", url);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
latest() {
|
||||||
|
return this.parts[this.parts.length - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
json() {
|
||||||
|
if (!this.cache) {
|
||||||
|
var temp = [];
|
||||||
|
this.parts.forEach(t => {
|
||||||
|
temp.push(t.convert());
|
||||||
|
});
|
||||||
|
this.cache = JSON.stringify(temp);
|
||||||
|
console.trace(this.cache);
|
||||||
|
}
|
||||||
|
return this.cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
string() {
|
||||||
|
var temp = '';
|
||||||
|
this.parts.forEach(t => {
|
||||||
|
temp += t.text
|
||||||
|
});
|
||||||
|
return temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Tellraw
|
||||||
@@ -1,25 +1,30 @@
|
|||||||
function Template(tpl: string) {
|
class Template {
|
||||||
var match: RegExpExecArray;
|
private renderFunc: Function;
|
||||||
var code = ['var r=[];'];
|
|
||||||
var re = /\{\{\s*([a-zA-Z\.\_0-9()]+)\s*\}\}/m;
|
constructor(tpl: string) {
|
||||||
function addLine(text: string) {
|
var match: RegExpExecArray;
|
||||||
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
|
var code = ['var r=[];'];
|
||||||
};
|
var re = /\{\{\s*([a-zA-Z\.\_0-9()]+)\s*\}\}/m;
|
||||||
while (match = re.exec(tpl)) {
|
|
||||||
if (match.index > 0) {
|
while (match = re.exec(tpl)) {
|
||||||
addLine(tpl.slice(0, match.index));
|
if (match.index > 0) {
|
||||||
|
this.addLine(code, tpl.slice(0, match.index));
|
||||||
|
}
|
||||||
|
code.push('r.push(this.' + match[1] + ');');
|
||||||
|
tpl = tpl.substring(match.index + match[0].length);
|
||||||
}
|
}
|
||||||
code.push('r.push(this.' + match[1] + ');');
|
this.addLine(code, tpl);
|
||||||
tpl = tpl.substring(match.index + match[0].length);
|
code.push('return r.join(\'\');');
|
||||||
|
// 创建函数:
|
||||||
|
this.renderFunc = new Function(code.join('\n'));
|
||||||
|
}
|
||||||
|
addLine(code: string[], text: string) {
|
||||||
|
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
|
||||||
}
|
}
|
||||||
addLine(tpl);
|
|
||||||
code.push('return r.join(\'\');');
|
|
||||||
// 创建函数:
|
|
||||||
var fn = new Function(code.join('\n'));
|
|
||||||
// 用render()调用函数并绑定this参数:
|
// 用render()调用函数并绑定this参数:
|
||||||
this.render = function(model) {
|
render(model: object) {
|
||||||
return fn.apply(model);
|
return this.renderFunc.apply(model);
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export = {
|
export = {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import '@ms/nashorn'
|
import '@ccms/nashorn'
|
||||||
|
|
||||||
let Files = Java.type("java.nio.file.Files");
|
let Files = Java.type("java.nio.file.Files");
|
||||||
let Paths = Java.type("java.nio.file.Paths");
|
let Paths = Java.type("java.nio.file.Paths");
|
||||||
|
|||||||
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()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
"extends": "../../tsconfig.json",
|
"extends": "../../tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": "src",
|
"baseUrl": "src",
|
||||||
"outDir": "dist",
|
"outDir": "dist"
|
||||||
"declaration": true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
1
packages/compile/.npmignore
Symbolic link
1
packages/compile/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../../.npmignore
|
||||||
26
packages/compile/package.json
Normal file
26
packages/compile/package.json
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"name": "@ccms/compile",
|
||||||
|
"version": "0.9.4",
|
||||||
|
"description": "MiaoScript compile 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": {
|
||||||
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^4.0.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
5
packages/compile/src/index.ts
Normal file
5
packages/compile/src/index.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import * as ts from 'typescript'
|
||||||
|
|
||||||
|
let scan = ts.createScanner(ts.ScriptTarget.ES5, true, ts.LanguageVariant.Standard)
|
||||||
|
scan.setText('let a = 1')
|
||||||
|
scan.tryScan(() => { })
|
||||||
7
packages/compile/tsconfig.json
Normal file
7
packages/compile/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": "src",
|
||||||
|
"outDir": "dist"
|
||||||
|
}
|
||||||
|
}
|
||||||
4
packages/container/.gitignore
vendored
4
packages/container/.gitignore
vendored
@@ -1,4 +0,0 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
|
||||||
/package-lock.json
|
|
||||||
/yarn.lock
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
src
|
|
||||||
test
|
|
||||||
typings
|
|
||||||
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
|
|
||||||
type_definitions
|
|
||||||
1
packages/container/.npmignore
Symbolic link
1
packages/container/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../../.npmignore
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/container",
|
"name": "@ccms/container",
|
||||||
"version": "0.0.0",
|
"version": "0.9.4",
|
||||||
"description": "MiaoScript container package",
|
"description": "MiaoScript container package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,21 +12,20 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"publishConfig": {
|
|
||||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
|
||||||
},
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@ccms/nashorn": "^0.9.4",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.0",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.6.2"
|
"typescript": "^4.0.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"inversify": "^5.0.1",
|
||||||
"inversify-binding-decorators": "^4.0.0"
|
"inversify-binding-decorators": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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 CONTAINER = Symbol.for("@ms/ioc:Container");
|
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
|
||||||
const INJECTION = Symbol.for("INJECTION");
|
const INJECTION = Symbol.for("INJECTION")
|
||||||
|
|
||||||
function _proxyGetter(
|
function _proxyGetter(
|
||||||
proto: any,
|
proto: any,
|
||||||
@@ -11,19 +11,19 @@ function _proxyGetter(
|
|||||||
resolve: () => any,
|
resolve: () => any,
|
||||||
doCache: boolean
|
doCache: boolean
|
||||||
) {
|
) {
|
||||||
function getter() {
|
function getter(this: object) {
|
||||||
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
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)) {
|
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
||||||
return Reflect.getMetadata(INJECTION, this, key);
|
return Reflect.getMetadata(INJECTION, this, key)
|
||||||
} else {
|
} else {
|
||||||
return resolve();
|
return resolve()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setter(newVal: any) {
|
function setter(this: object, newVal: any) {
|
||||||
Reflect.defineMetadata(INJECTION, newVal, this, key);
|
Reflect.defineMetadata(INJECTION, newVal, this, key)
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.defineProperty(proto, key, {
|
Object.defineProperty(proto, key, {
|
||||||
@@ -31,63 +31,63 @@ function _proxyGetter(
|
|||||||
enumerable: true,
|
enumerable: true,
|
||||||
get: getter,
|
get: getter,
|
||||||
set: setter
|
set: setter
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function initContainer(container: Container) {
|
function initContainer(container: Container) {
|
||||||
Reflect.defineMetadata(CONTAINER, container, Reflect);
|
Reflect.defineMetadata(ContainerInstance, container, Reflect)
|
||||||
_container = container;
|
return _container = container
|
||||||
}
|
}
|
||||||
|
|
||||||
function getContainer(): Container {
|
function getContainer(): Container {
|
||||||
return _container || Reflect.getMetadata(CONTAINER, Reflect)
|
return _container || initContainer(new Container())
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectDecorator(doCache: boolean) {
|
function makePropertyInjectDecorator(doCache: boolean) {
|
||||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||||
return function(proto: any, key: string): void {
|
return function (proto: any, key: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().get(serviceIdentifier);
|
return getContainer().get(serviceIdentifier)
|
||||||
};
|
}
|
||||||
_proxyGetter(proto, key, resolve, doCache);
|
_proxyGetter(proto, key, resolve, doCache)
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectNamedDecorator(doCache: boolean) {
|
function makePropertyInjectNamedDecorator(doCache: boolean) {
|
||||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
||||||
return function(proto: any, key: string): void {
|
return function (proto: any, key: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().getNamed(serviceIdentifier, named);
|
return getContainer().getNamed(serviceIdentifier, named)
|
||||||
};
|
}
|
||||||
_proxyGetter(proto, key, resolve, doCache);
|
_proxyGetter(proto, key, resolve, doCache)
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectTaggedDecorator(doCache: boolean) {
|
function makePropertyInjectTaggedDecorator(doCache: boolean) {
|
||||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
||||||
return function(proto: any, propertyName: string): void {
|
return function (proto: any, propertyName: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().getTagged(serviceIdentifier, key, value);
|
return getContainer().getTagged(serviceIdentifier, key, value)
|
||||||
};
|
}
|
||||||
_proxyGetter(proto, propertyName, resolve, doCache);
|
_proxyGetter(proto, propertyName, resolve, doCache)
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyMultiInjectDecorator(doCache: boolean) {
|
function makePropertyMultiInjectDecorator(doCache: boolean) {
|
||||||
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||||
return function(proto: any, key: string): void {
|
return function (proto: any, key: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().getAll(serviceIdentifier);
|
return getContainer().getAll(serviceIdentifier)
|
||||||
};
|
}
|
||||||
_proxyGetter(proto, key, resolve, doCache);
|
_proxyGetter(proto, key, resolve, doCache)
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let doCache = true;
|
let doCache = true
|
||||||
|
|
||||||
let lazyInject = makePropertyInjectDecorator(doCache)
|
let lazyInject = makePropertyInjectDecorator(doCache)
|
||||||
let lazyInjectNamed = makePropertyInjectNamedDecorator(doCache)
|
let lazyInjectNamed = makePropertyInjectNamedDecorator(doCache)
|
||||||
@@ -97,8 +97,9 @@ let lazyMultiInject = makePropertyMultiInjectDecorator(doCache)
|
|||||||
export {
|
export {
|
||||||
initContainer,
|
initContainer,
|
||||||
getContainer,
|
getContainer,
|
||||||
|
ContainerInstance,
|
||||||
lazyInject,
|
lazyInject,
|
||||||
lazyInjectNamed,
|
lazyInjectNamed,
|
||||||
lazyInjectTagged,
|
lazyInjectTagged,
|
||||||
lazyMultiInject
|
lazyMultiInject
|
||||||
};
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user