Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e28d881976 | |||
| 1bdb324fc4 | |||
| 5c90ac3b1f | |||
| 653d7268cf | |||
| efa5e6d110 | |||
| ceb354f11e | |||
| d97af356fd | |||
| 6fd7174ca5 | |||
| 784ea2d65a | |||
| 3ccc9b3d06 | |||
| beef57d85d | |||
| 166b17b527 | |||
| d6ca19a56f | |||
| c61f87a449 | |||
| ede3f83dd5 | |||
| 69ef3b3979 | |||
|
|
0a8574621d | ||
| 5426ec1eed | |||
| 831f6d0916 | |||
| 1a5175f466 | |||
|
|
2ad290bd48 | ||
| 611d4e5425 | |||
| 894d5d43e6 | |||
| cd57944cb8 | |||
| 75b34bfc48 | |||
| 47478e13aa | |||
|
|
17af1fd49b | ||
| b5423cd26c | |||
| aca864500f | |||
| f86e1a8c94 | |||
| a76f9e8b50 |
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"useWorkspaces": true,
|
"useWorkspaces": true,
|
||||||
"npmClient": "yarn",
|
"npmClient": "yarn",
|
||||||
"packages": [
|
"packages": [
|
||||||
|
|||||||
@@ -20,6 +20,6 @@
|
|||||||
"packages/*"
|
"packages/*"
|
||||||
],
|
],
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"lerna": "^3.22.1"
|
"lerna": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/amqp",
|
"name": "@ccms/amqp",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript amqp package",
|
"description": "MiaoScript amqp package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,17 +19,17 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/common": "^0.10.0",
|
"@ccms/common": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0"
|
"@ccms/container": "^0.14.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.10.0",
|
"@ccms/nashorn": "^0.14.0",
|
||||||
"@javatypes/amqp-client": "^0.0.3",
|
"@javatypes/amqp-client": "^0.0.3",
|
||||||
"@javatypes/spring-amqp": "^0.0.3",
|
"@javatypes/spring-amqp": "^0.0.3",
|
||||||
"@javatypes/spring-rabbit": "^0.0.3",
|
"@javatypes/spring-rabbit": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/api",
|
"name": "@ccms/api",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,16 +19,16 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/common": "^0.10.0",
|
"@ccms/common": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0",
|
"@ccms/container": "^0.14.0",
|
||||||
"@ccms/ployfill": "^0.10.0",
|
"@ccms/polyfill": "^0.14.1",
|
||||||
"base64-js": "^1.3.1",
|
"base64-js": "^1.5.1",
|
||||||
"source-map-builder": "^0.0.7"
|
"source-map-builder": "^0.0.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/base64-js": "^1.3.0",
|
"@types/base64-js": "^1.3.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ enum LogLevel {
|
|||||||
|
|
||||||
export class MiaoScriptConsole implements Console {
|
export class MiaoScriptConsole implements Console {
|
||||||
Console: NodeJS.ConsoleConstructor
|
Console: NodeJS.ConsoleConstructor
|
||||||
|
memory: any
|
||||||
|
|
||||||
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||||
private static sourceFileMaps: { [key: string]: string } = {}
|
private static sourceFileMaps: { [key: string]: string } = {}
|
||||||
@@ -27,7 +28,8 @@ export class MiaoScriptConsole implements Console {
|
|||||||
private _level: LogLevel = LogLevel.INFO
|
private _level: LogLevel = LogLevel.INFO
|
||||||
|
|
||||||
protected logger: any
|
protected logger: any
|
||||||
protected prefix: string = '§6[§bMiaoScript§6]§r '
|
|
||||||
|
public prefix: string = '§6[§bMiaoScript§6]§r '
|
||||||
|
|
||||||
constructor(name?: string) {
|
constructor(name?: string) {
|
||||||
this.name = name
|
this.name = name
|
||||||
@@ -47,10 +49,10 @@ export class MiaoScriptConsole implements Console {
|
|||||||
set name(name: string) {
|
set name(name: string) {
|
||||||
if (name) {
|
if (name) {
|
||||||
this._name = `[${name}] `
|
this._name = `[${name}] `
|
||||||
// noinspection JSUnusedGlobalSymbols
|
|
||||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log(...args: any[]): void {
|
log(...args: any[]): void {
|
||||||
this.logger.info(this.name + args.join(' '))
|
this.logger.info(this.name + args.join(' '))
|
||||||
}
|
}
|
||||||
@@ -90,7 +92,7 @@ export class MiaoScriptConsole implements Console {
|
|||||||
ex(ex: Error) {
|
ex(ex: Error) {
|
||||||
this.stack(ex).forEach(line => this.console(line))
|
this.stack(ex).forEach(line => this.console(line))
|
||||||
}
|
}
|
||||||
readSourceMap(fileName: string, lineNumber: number) {
|
readSourceMap(fileName: string, lineNumber: any) {
|
||||||
try {
|
try {
|
||||||
if (fileName.endsWith('js')) {
|
if (fileName.endsWith('js')) {
|
||||||
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
||||||
@@ -133,6 +135,7 @@ export class MiaoScriptConsole implements Console {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
stack(ex: Error, color: boolean = true): string[] {
|
stack(ex: Error, color: boolean = true): string[] {
|
||||||
|
if (!ex) return []
|
||||||
let stack = ex.getStackTrace()
|
let stack = ex.getStackTrace()
|
||||||
let cache = [(color ? '§c' : '') + ex]
|
let cache = [(color ? '§c' : '') + ex]
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
@@ -152,17 +155,20 @@ export class MiaoScriptConsole implements Console {
|
|||||||
} else {
|
} else {
|
||||||
let className = trace.className
|
let className = trace.className
|
||||||
var fileName = trace.fileName as string
|
var fileName = trace.fileName as string
|
||||||
|
var lineNumber = trace.lineNumber
|
||||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
||||||
className = className.substr(className.lastIndexOf('$') + 1)
|
className = className.substr(className.lastIndexOf('$') + 1)
|
||||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
var { fileName, lineNumber } = this.readSourceMap(fileName, lineNumber)
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||||
} else {
|
} else {
|
||||||
|
if (!global.debug) {
|
||||||
for (let prefix in ignoreLogPrefix) {
|
for (let prefix in ignoreLogPrefix) {
|
||||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if (color) {
|
if (color) {
|
||||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||||
} else {
|
} else {
|
||||||
@@ -190,6 +196,9 @@ export class MiaoScriptConsole implements Console {
|
|||||||
dirxml(...data: any[]): void {
|
dirxml(...data: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
|
exception(message?: string, ...optionalParams: any[]): void {
|
||||||
|
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.")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,4 +12,5 @@ export * from './console'
|
|||||||
export * from './channel'
|
export * from './channel'
|
||||||
export * from './command'
|
export * from './command'
|
||||||
export * from './database'
|
export * from './database'
|
||||||
|
export * from './particle'
|
||||||
export * from './constants'
|
export * from './constants'
|
||||||
|
|||||||
494
packages/api/src/particle.ts
Normal file
494
packages/api/src/particle.ts
Normal file
@@ -0,0 +1,494 @@
|
|||||||
|
import { Autowired, injectable } from '@ccms/container'
|
||||||
|
|
||||||
|
import { task, plugin } from './index'
|
||||||
|
|
||||||
|
const UUID = Java.type('java.util.UUID')
|
||||||
|
const Math = Java.type('java.lang.Math')
|
||||||
|
|
||||||
|
export namespace particle {
|
||||||
|
/**
|
||||||
|
* 表示一个特效对象
|
||||||
|
*
|
||||||
|
* @author Zoyn
|
||||||
|
*/
|
||||||
|
export abstract class Particle {
|
||||||
|
private spawner: ParticleSpawner
|
||||||
|
private readonly uuid: string
|
||||||
|
|
||||||
|
private particle: any /* Particle */
|
||||||
|
private count: number = 1;
|
||||||
|
private offsetX: number = 0;
|
||||||
|
private offsetY: number = 0;
|
||||||
|
private offsetZ: number = 0;
|
||||||
|
private extra: number = 0;
|
||||||
|
private data: Object = null;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.uuid = UUID.randomUUID().toString()
|
||||||
|
}
|
||||||
|
abstract show(location: any)
|
||||||
|
|
||||||
|
getUUID() {
|
||||||
|
return this.uuid
|
||||||
|
}
|
||||||
|
|
||||||
|
getSpawner() {
|
||||||
|
return this.spawner
|
||||||
|
}
|
||||||
|
|
||||||
|
setSpawner(spawner: ParticleSpawner) {
|
||||||
|
this.spawner = spawner
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getParticle() {
|
||||||
|
return this.particle
|
||||||
|
}
|
||||||
|
|
||||||
|
setParticle(particle: any, data: any = null) {
|
||||||
|
this.particle = particle
|
||||||
|
this.data = data
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getCount() {
|
||||||
|
return this.count
|
||||||
|
}
|
||||||
|
|
||||||
|
setCount(count: number) {
|
||||||
|
this.count = count
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getOffsetX() {
|
||||||
|
return this.offsetX
|
||||||
|
}
|
||||||
|
|
||||||
|
setOffsetX(offsetX: number) {
|
||||||
|
this.offsetX = offsetX
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getOffsetY() {
|
||||||
|
return this.offsetY
|
||||||
|
}
|
||||||
|
|
||||||
|
setOffsetY(offsetY: number) {
|
||||||
|
this.offsetY = offsetY
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getOffsetZ() {
|
||||||
|
return this.offsetZ
|
||||||
|
}
|
||||||
|
|
||||||
|
setOffsetZ(offsetZ: number) {
|
||||||
|
this.offsetZ = offsetZ
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getExtra() {
|
||||||
|
return this.extra
|
||||||
|
}
|
||||||
|
|
||||||
|
setExtra(extra: number) {
|
||||||
|
this.extra = extra
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getData() {
|
||||||
|
return this.data
|
||||||
|
}
|
||||||
|
|
||||||
|
setData(data) {
|
||||||
|
this.data = data
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过给定一个坐标就可以使用已经指定的参数来播放粒子
|
||||||
|
*
|
||||||
|
* @param location 坐标
|
||||||
|
*/
|
||||||
|
spawn(location: any) {
|
||||||
|
if (!this.spawner) throw new Error(`particle ${this.uuid} not set spawner can't spawn!`)
|
||||||
|
this.spawner.spawn(location, this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 表示一条线
|
||||||
|
*
|
||||||
|
* @author Zoyn
|
||||||
|
*/
|
||||||
|
export class Line extends Particle {
|
||||||
|
private vector: any
|
||||||
|
private start: any
|
||||||
|
private end: any
|
||||||
|
/**
|
||||||
|
* 步长
|
||||||
|
*/
|
||||||
|
private step: number
|
||||||
|
/**
|
||||||
|
* 向量长度
|
||||||
|
*/
|
||||||
|
private length: number
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造一条线
|
||||||
|
*
|
||||||
|
* @param start 线的起点
|
||||||
|
* @param end 线的终点
|
||||||
|
*/
|
||||||
|
constructor(start: any, end: any)
|
||||||
|
/**
|
||||||
|
* 构造一条线
|
||||||
|
*
|
||||||
|
* @param start 线的起点
|
||||||
|
* @param end 线的终点
|
||||||
|
* @param step 每个粒子之间的间隔 (也即步长)
|
||||||
|
*/
|
||||||
|
constructor(start: any, end: any, step: number = 0.1) {
|
||||||
|
super()
|
||||||
|
this.start = start
|
||||||
|
this.end = end
|
||||||
|
this.step = step
|
||||||
|
// 对向量进行重置
|
||||||
|
this.resetVector()
|
||||||
|
}
|
||||||
|
|
||||||
|
show() {
|
||||||
|
for (let i = 0; i < this.length; i += this.step) {
|
||||||
|
let vectorTemp = this.vector.clone().multiply(i)
|
||||||
|
this.spawn(this.start.clone().add(vectorTemp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取线的起始坐标
|
||||||
|
*
|
||||||
|
* @return {@link Location}
|
||||||
|
*/
|
||||||
|
getStart() {
|
||||||
|
return this.start
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 利用给定的坐标设置线的起始坐标
|
||||||
|
*
|
||||||
|
* @param start 起始坐标
|
||||||
|
* @return {@link Line}
|
||||||
|
*/
|
||||||
|
setStart(start) {
|
||||||
|
this.start = start
|
||||||
|
this.resetVector()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取线的终点坐标
|
||||||
|
*
|
||||||
|
* @return {@link Location}
|
||||||
|
*/
|
||||||
|
getEnd() {
|
||||||
|
return this.end
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 利用给定的坐标设置线的终点坐标
|
||||||
|
*
|
||||||
|
* @param end 终点
|
||||||
|
* @return {@link Line}
|
||||||
|
*/
|
||||||
|
setEnd(end) {
|
||||||
|
this.end = end
|
||||||
|
this.resetVector()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取每个粒子之间的间隔
|
||||||
|
*
|
||||||
|
* @return 也就是循环的步长
|
||||||
|
*/
|
||||||
|
getStep() {
|
||||||
|
return this.step
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置每个粒子之间的间隔
|
||||||
|
*
|
||||||
|
* @param step 间隔
|
||||||
|
* @return {@link Line}
|
||||||
|
*/
|
||||||
|
setStep(step) {
|
||||||
|
this.step = step
|
||||||
|
this.resetVector()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动重设线的向量
|
||||||
|
*/
|
||||||
|
resetVector() {
|
||||||
|
this.vector = this.end.clone().subtract(this.start).toVector()
|
||||||
|
this.length = this.vector.length()
|
||||||
|
this.vector.normalize()
|
||||||
|
}
|
||||||
|
|
||||||
|
public static buildLine(locA: any, locB: any, step: number, particle: any) {
|
||||||
|
let vectorAB = locB.clone().subtract(locA).toVector()
|
||||||
|
let vectorLength = vectorAB.length()
|
||||||
|
vectorAB.normalize()
|
||||||
|
for (let i = 0; i < vectorLength; i += step) {
|
||||||
|
ParticleManager.globalSpawner.spawn(locA.clone().add(vectorAB.clone().multiply(i)), particle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 表示一个弧
|
||||||
|
*
|
||||||
|
* @author Zoyn
|
||||||
|
*/
|
||||||
|
export class Arc extends Particle {
|
||||||
|
private angle: number
|
||||||
|
private radius: number
|
||||||
|
private step: number
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造一个弧
|
||||||
|
*
|
||||||
|
* @param origin 弧所在的圆的圆点
|
||||||
|
* @param angle 弧所占的角度
|
||||||
|
* @param radius 弧所在的圆的半径
|
||||||
|
* @param step 每个粒子的间隔(也即步长)
|
||||||
|
*/
|
||||||
|
constructor(angle: number = 30, radius: number = 1, step: number = 1) {
|
||||||
|
super()
|
||||||
|
this.angle = angle
|
||||||
|
this.radius = radius
|
||||||
|
this.step = step
|
||||||
|
}
|
||||||
|
|
||||||
|
show(location: any) {
|
||||||
|
for (let i = 0; i < this.angle; i += this.step) {
|
||||||
|
let radians: number = Math.toRadians(i)
|
||||||
|
let x: number = this.radius * Math.cos(radians)
|
||||||
|
let z: number = this.radius * Math.sin(radians)
|
||||||
|
|
||||||
|
super.spawn(location.clone().add(x, 0, z))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getAngle(): number {
|
||||||
|
return this.angle
|
||||||
|
}
|
||||||
|
|
||||||
|
setAngle(angle: number): Arc {
|
||||||
|
this.angle = angle
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getRadius(): number {
|
||||||
|
return this.radius
|
||||||
|
}
|
||||||
|
|
||||||
|
setRadius(radius: number): Arc {
|
||||||
|
this.radius = radius
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getStep(): number {
|
||||||
|
return this.step
|
||||||
|
}
|
||||||
|
|
||||||
|
setStep(step: number): Arc {
|
||||||
|
this.step = step
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 表示一个圆
|
||||||
|
*
|
||||||
|
* @author Zoyn
|
||||||
|
*/
|
||||||
|
export class Circle extends Arc {
|
||||||
|
constructor(radius: number)
|
||||||
|
constructor(radius: number, step: number)
|
||||||
|
/**
|
||||||
|
* 构造一个圆
|
||||||
|
*
|
||||||
|
* @param origin 圆的圆点
|
||||||
|
* @param radius 圆的半径
|
||||||
|
* @param step 每个粒子的间隔(也即步长)
|
||||||
|
* @param period 特效周期(如果需要可以使用)
|
||||||
|
*/
|
||||||
|
constructor(radius: number = 1, step: number = 1) {
|
||||||
|
// Circle只需要控制这个fullArc就可以满足所有的要求
|
||||||
|
super(360, radius, step)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export abstract class ParticleManager {
|
||||||
|
public static globalSpawner: ParticleSpawner = undefined
|
||||||
|
@Autowired()
|
||||||
|
private taskManager: task.TaskManager
|
||||||
|
|
||||||
|
protected taskId: java.util.concurrent.atomic.AtomicInteger
|
||||||
|
protected cacheTasks = new Map<string, ParticleTask>()
|
||||||
|
protected pluginCacheTasks = new Map<string, Map<number, ParticleTask>>()
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.taskId = new AtomicInteger(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获得自增的任务ID
|
||||||
|
*/
|
||||||
|
public nextId() {
|
||||||
|
return this.taskId.incrementAndGet()
|
||||||
|
}
|
||||||
|
|
||||||
|
public getTaskManager() {
|
||||||
|
return this.taskManager
|
||||||
|
}
|
||||||
|
|
||||||
|
public create(particle: Particle, plugin?: plugin.Plugin) {
|
||||||
|
let uuid = particle.getUUID()
|
||||||
|
if (this.cacheTasks.has(uuid)) {
|
||||||
|
return this.cacheTasks.get(uuid)
|
||||||
|
}
|
||||||
|
let task = this.create0(plugin, particle)
|
||||||
|
this.cacheTasks.set(uuid, task)
|
||||||
|
if (plugin) {
|
||||||
|
if (!this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
|
this.pluginCacheTasks.set(plugin.description.name, new Map())
|
||||||
|
}
|
||||||
|
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
|
||||||
|
}
|
||||||
|
return task
|
||||||
|
}
|
||||||
|
|
||||||
|
public cancel(particle: Particle) {
|
||||||
|
let uuid = particle.getUUID()
|
||||||
|
if (this.cacheTasks.has(uuid)) {
|
||||||
|
this.cacheTasks.get(uuid).cancel()
|
||||||
|
this.cacheTasks.delete(uuid)
|
||||||
|
} else {
|
||||||
|
throw new Error(`particle ${uuid} not found!`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
disable(plugin: plugin.Plugin) {
|
||||||
|
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
|
this.pluginCacheTasks
|
||||||
|
.get(plugin.description.name)
|
||||||
|
.forEach((task) => task.cancel())
|
||||||
|
this.pluginCacheTasks.delete(plugin.description.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
protected create0(owner: plugin.Plugin, particle: Particle): ParticleTask {
|
||||||
|
particle.setSpawner(this.getGlobalSpawner())
|
||||||
|
return new ParticleTask(owner, particle, this)
|
||||||
|
}
|
||||||
|
protected abstract getGlobalSpawner(): ParticleSpawner
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ParticleTask {
|
||||||
|
|
||||||
|
private particle: Particle
|
||||||
|
private isAsync: boolean = false
|
||||||
|
private interval: number = 0
|
||||||
|
private _location: any
|
||||||
|
private _follow: any
|
||||||
|
|
||||||
|
private owner: plugin.Plugin
|
||||||
|
private taskId: number
|
||||||
|
private task: task.Task
|
||||||
|
private taskManager: task.TaskManager
|
||||||
|
protected particleManager: ParticleManager
|
||||||
|
|
||||||
|
constructor(owner: plugin.Plugin, particle: Particle, particleManager: ParticleManager) {
|
||||||
|
this.owner = owner
|
||||||
|
this.taskId = particleManager.nextId()
|
||||||
|
this.particle = particle
|
||||||
|
this.taskManager = particleManager.getTaskManager()
|
||||||
|
this.particleManager = particleManager
|
||||||
|
}
|
||||||
|
|
||||||
|
getOwner() {
|
||||||
|
return this.task.getOwner()
|
||||||
|
}
|
||||||
|
|
||||||
|
getTaskId() {
|
||||||
|
return this.taskId
|
||||||
|
}
|
||||||
|
|
||||||
|
getParticle() {
|
||||||
|
return this.particle
|
||||||
|
}
|
||||||
|
|
||||||
|
async(isAsync: boolean = true) {
|
||||||
|
this.isAsync = isAsync
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
timer(tick: number) {
|
||||||
|
this.interval = tick
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
follow(entity: { getLocation: () => any }) {
|
||||||
|
this._follow = entity
|
||||||
|
this._location = undefined
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
location(location: any) {
|
||||||
|
this._location = location
|
||||||
|
this._follow = undefined
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
submit() {
|
||||||
|
this.cancel()
|
||||||
|
if (this._follow && !this.interval) throw new Error(`enable follow entity but interval is ${this.interval}!`)
|
||||||
|
this.taskManager.create(() => {
|
||||||
|
this.task = this.taskManager
|
||||||
|
.create(() => {
|
||||||
|
try {
|
||||||
|
if (this._follow) {
|
||||||
|
if (!this._follow.isOnline()) return this.cancel()
|
||||||
|
this.particle.show(this._follow.getLocation().clone().add(0, 1, 0))
|
||||||
|
} else if (this._location) {
|
||||||
|
this.particle.show(this._location)
|
||||||
|
} else {
|
||||||
|
console.warn(`ParticleTask ${this.taskId} particle ${this.particle.getUUID()} cancel because entity and location both undefined!`)
|
||||||
|
this.task.cancel()
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`§6插件 §a${this.owner.description.name} §c播放粒子发送异常 §4粒子播放任务已终止!`)
|
||||||
|
console.ex(error)
|
||||||
|
this.cancel()
|
||||||
|
}
|
||||||
|
}, this.owner)
|
||||||
|
.async(this.isAsync)
|
||||||
|
.timer(this.interval)
|
||||||
|
.submit()
|
||||||
|
}, this.owner).later(2).submit()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel() {
|
||||||
|
if (this.task != null) {
|
||||||
|
this.task.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export abstract class ParticleSpawner {
|
||||||
|
abstract spawnParticle(location: any, particle: any, count: number)
|
||||||
|
abstract spawn(location: any, particle: Particle)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,9 +18,15 @@ export namespace server {
|
|||||||
export const ServerInstance = Symbol("ServerInstance")
|
export const ServerInstance = Symbol("ServerInstance")
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class NativePluginManager {
|
export abstract class NativePluginManager {
|
||||||
|
list(): any[] {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
has(name: string): boolean {
|
has(name: string): boolean {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
get(name: string): any {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
load(name: string): boolean {
|
load(name: string): boolean {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,34 +1,66 @@
|
|||||||
import { plugin } from './index'
|
import { plugin } from './index'
|
||||||
import { injectable } from '@ccms/container'
|
import { injectable } from '@ccms/container'
|
||||||
|
|
||||||
|
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||||
|
|
||||||
export namespace task {
|
export namespace task {
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class TaskManager {
|
export abstract class TaskManager {
|
||||||
protected cacheTasks = new Map<string, task.Task[]>()
|
protected taskId: java.util.concurrent.atomic.AtomicInteger
|
||||||
|
protected cacheTasks = new Map<number, task.Task>()
|
||||||
|
protected pluginCacheTasks = new Map<string, Map<number, task.Task>>()
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.taskId = new AtomicInteger(0)
|
||||||
|
process.on('task.finish', (task: task.Task) => {
|
||||||
|
let taskId = task.getTaskId()
|
||||||
|
this.cacheTasks.delete(taskId)
|
||||||
|
let ownerName = task.getOwner()?.description.name
|
||||||
|
if (ownerName && this.pluginCacheTasks.has(ownerName)) {
|
||||||
|
this.pluginCacheTasks.get(ownerName).delete(taskId)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
||||||
if (!this.cacheTasks.has(plugin.description.name)) {
|
if (!this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
this.cacheTasks.set(plugin.description.name, [])
|
this.pluginCacheTasks.set(plugin.description.name, new Map())
|
||||||
}
|
}
|
||||||
this.cacheTasks.get(plugin.description.name).push(task)
|
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
|
||||||
return task
|
return task
|
||||||
}
|
}
|
||||||
|
|
||||||
protected pluginDisable(plugin: plugin.Plugin) {
|
protected pluginDisable(plugin: plugin.Plugin) {
|
||||||
if (this.cacheTasks.has(plugin.description.name)) {
|
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
this.cacheTasks.get(plugin.description.name).forEach(task => task.cancel())
|
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => {
|
||||||
this.cacheTasks.delete(plugin.description.name)
|
task.cancel()
|
||||||
|
})
|
||||||
|
this.pluginCacheTasks.delete(plugin.description.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获得自增的任务ID
|
||||||
|
*/
|
||||||
|
protected nextId() {
|
||||||
|
return this.taskId.incrementAndGet()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建任务
|
* 创建任务
|
||||||
* @param func 任务内容
|
* @param func 任务内容
|
||||||
*/
|
*/
|
||||||
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
||||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
||||||
let task = this.create0(func)
|
let task = this.create0(plugin, func, this.nextId())
|
||||||
|
this.cacheTasks.set(task.getTaskId(), task)
|
||||||
if (plugin) { return this.pluginCreate(plugin, task) }
|
if (plugin) { return this.pluginCreate(plugin, task) }
|
||||||
return task
|
return task
|
||||||
}
|
}
|
||||||
|
cancel(taskId: number) {
|
||||||
|
if (!this.cacheTasks.has(taskId)) { throw new Error(`Task ${taskId} not found!`) }
|
||||||
|
this.cacheTasks.get(taskId).cancel()
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 在主线程执行代码
|
* 在主线程执行代码
|
||||||
* @param func 执行内容
|
* @param func 执行内容
|
||||||
@@ -41,22 +73,33 @@ export namespace task {
|
|||||||
if (plugin) { return this.pluginDisable(plugin) }
|
if (plugin) { return this.pluginDisable(plugin) }
|
||||||
this.disable0()
|
this.disable0()
|
||||||
}
|
}
|
||||||
protected abstract create0(func: Function): task.Task
|
protected abstract create0(owner: plugin.Plugin, func: Function, id: number): task.Task
|
||||||
protected abstract disable0()
|
protected abstract disable0()
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 任务抽象
|
* 任务抽象
|
||||||
*/
|
*/
|
||||||
export abstract class Task {
|
export abstract class Task implements Cancelable {
|
||||||
protected plugin: any
|
|
||||||
protected func: Function
|
protected func: Function
|
||||||
protected isAsync: boolean = false;
|
protected isAsync: boolean = false;
|
||||||
protected laterTime: number = 0;
|
protected laterTime: number = 0;
|
||||||
protected interval: number = 0;
|
protected interval: number = 0;
|
||||||
|
protected owner: plugin.Plugin
|
||||||
|
protected taskId: number
|
||||||
|
protected innerTask: any
|
||||||
|
|
||||||
constructor(plugin: any, func: Function) {
|
constructor(owner: plugin.Plugin, func: Function, id: number) {
|
||||||
this.plugin = plugin
|
this.owner = owner
|
||||||
this.func = func
|
this.func = func
|
||||||
|
this.taskId = id
|
||||||
|
}
|
||||||
|
|
||||||
|
getOwner() {
|
||||||
|
return this.owner
|
||||||
|
}
|
||||||
|
|
||||||
|
getTaskId() {
|
||||||
|
return this.taskId
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -90,12 +133,15 @@ export namespace task {
|
|||||||
* 取消任务
|
* 取消任务
|
||||||
*/
|
*/
|
||||||
cancel(): boolean {
|
cancel(): boolean {
|
||||||
throw new Error("Method not implemented.")
|
let result = this.cancel0()
|
||||||
|
process.emit('task.finish', this)
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
protected run(...args: any[]): void {
|
protected run(...args: any[]): void {
|
||||||
try {
|
try {
|
||||||
this.func(...args)
|
this.func(...args)
|
||||||
|
!this.interval && process.emit('task.finish', this)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console('§4插件执行任务时发生错误', ex)
|
console.console('§4插件执行任务时发生错误', ex)
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
@@ -106,17 +152,22 @@ export namespace task {
|
|||||||
* 提交任务
|
* 提交任务
|
||||||
* @param args 任务参数
|
* @param args 任务参数
|
||||||
*/
|
*/
|
||||||
submit(...args: any[]): Cancelable {
|
submit(...args: any[]): task.Task {
|
||||||
let cancelable = this.submit0(...args)
|
this.innerTask = this.submit0(...args)
|
||||||
this.cancel = cancelable.cancel
|
return this
|
||||||
return cancelable
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 提交任务
|
* 提交任务
|
||||||
* @param args 任务参数
|
* @param args 任务参数
|
||||||
*/
|
*/
|
||||||
protected abstract submit0(...args: any[]): Cancelable
|
protected abstract submit0(...args: any[]): any
|
||||||
|
/**
|
||||||
|
* 取消任务
|
||||||
|
*/
|
||||||
|
protected cancel0(): boolean {
|
||||||
|
return this.innerTask?.cancel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 返可取消的对象
|
* 返可取消的对象
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bukkit",
|
"name": "@ccms/bukkit",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript bukkit package",
|
"description": "MiaoScript bukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/spigot-api": "^0.0.3",
|
"@javatypes/spigot-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/common": "^0.10.0",
|
"@ccms/common": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0"
|
"@ccms/container": "^0.14.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,12 @@ import './chat'
|
|||||||
import './task'
|
import './task'
|
||||||
import './event'
|
import './event'
|
||||||
import './server'
|
import './server'
|
||||||
|
import { BukkitNativePluginManager } from './plugin'
|
||||||
import './command'
|
import './command'
|
||||||
import './channel'
|
import './channel'
|
||||||
|
import './particle'
|
||||||
|
|
||||||
export default function BukkitImpl(container: Container) {
|
export default function BukkitImpl(container: Container) {
|
||||||
container.bind(server.Console).toConstantValue(BukkitConsole)
|
container.bind(server.Console).toConstantValue(BukkitConsole)
|
||||||
|
container.rebind(server.NativePluginManager).toConstantValue(new BukkitNativePluginManager())
|
||||||
}
|
}
|
||||||
|
|||||||
31
packages/bukkit/src/particle.ts
Normal file
31
packages/bukkit/src/particle.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { provideSingleton } from '@ccms/container'
|
||||||
|
import { particle, plugin } from '@ccms/api'
|
||||||
|
|
||||||
|
@provideSingleton(particle.ParticleManager)
|
||||||
|
export class BukkitParticleManager extends particle.ParticleManager {
|
||||||
|
private globalSpawner = new BukkitParticleSpawner()
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
particle.ParticleManager.globalSpawner = this.globalSpawner
|
||||||
|
}
|
||||||
|
protected getGlobalSpawner() {
|
||||||
|
return this.globalSpawner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export class BukkitParticleSpawner extends particle.ParticleSpawner {
|
||||||
|
spawnParticle(location: any, particle: any, count: number = 1) {
|
||||||
|
location.getWorld().spawnParticle(particle, location, count)
|
||||||
|
}
|
||||||
|
spawn(location: any, particle: particle.Particle) {
|
||||||
|
location.getWorld().spawnParticle(
|
||||||
|
particle.getParticle(),
|
||||||
|
location,
|
||||||
|
particle.getCount(),
|
||||||
|
particle.getOffsetX(),
|
||||||
|
particle.getOffsetY(),
|
||||||
|
particle.getOffsetZ(),
|
||||||
|
particle.getExtra(),
|
||||||
|
particle.getData()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
12
packages/bukkit/src/plugin.ts
Normal file
12
packages/bukkit/src/plugin.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { server } from '@ccms/api'
|
||||||
|
|
||||||
|
const Bukkit = org.bukkit.Bukkit
|
||||||
|
|
||||||
|
export class BukkitNativePluginManager extends server.NativePluginManager {
|
||||||
|
has(name: string) {
|
||||||
|
return !!this.get(name)
|
||||||
|
}
|
||||||
|
get(name: string) {
|
||||||
|
return Bukkit.getPluginManager().getPlugin(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,17 +7,14 @@ const Callable = Java.type('java.util.concurrent.Callable')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class BukkitTaskManager extends task.TaskManager {
|
export class BukkitTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
private pluginInstance: any
|
return new BukkitTask(owner, func, id)
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
|
||||||
return new BukkitTask(this.pluginInstance, func)
|
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
return Bukkit.getScheduler().callSyncMethod(base.getInstance(), new Callable({ call: () => func() })).get()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
Bukkit.getScheduler().cancelTasks(this.pluginInstance)
|
Bukkit.getScheduler().cancelTasks(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,9 +23,9 @@ export class BukkitTask extends task.Task {
|
|||||||
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
||||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
return run[funcName](base.getInstance(), this.laterTime, this.interval)
|
||||||
} else {
|
} else {
|
||||||
return run[funcName](this.plugin, this.laterTime)
|
return run[funcName](base.getInstance(), this.laterTime)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bungee",
|
"name": "@ccms/bungee",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript bungee package",
|
"description": "MiaoScript bungee package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/bungee-api": "^0.0.3",
|
"@javatypes/bungee-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/common": "^0.10.0",
|
"@ccms/common": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0"
|
"@ccms/container": "^0.14.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,13 +3,15 @@
|
|||||||
import { server } from '@ccms/api'
|
import { server } from '@ccms/api'
|
||||||
import { Container } from '@ccms/container'
|
import { Container } from '@ccms/container'
|
||||||
|
|
||||||
import { BungeeConsole } from './console';
|
import { BungeeConsole } from './console'
|
||||||
import './event';
|
import './task'
|
||||||
import './server';
|
import './event'
|
||||||
import './command';
|
import './server'
|
||||||
import './channel';
|
import { BungeeNativePluginManager } from './plugin'
|
||||||
import './task';
|
import './command'
|
||||||
|
import './channel'
|
||||||
|
|
||||||
export default function BungeeImpl(container: Container) {
|
export default function BungeeImpl(container: Container) {
|
||||||
container.bind(server.Console).toConstantValue(BungeeConsole);
|
container.bind(server.Console).toConstantValue(BungeeConsole)
|
||||||
|
container.rebind(server.NativePluginManager).toConstantValue(new BungeeNativePluginManager())
|
||||||
}
|
}
|
||||||
|
|||||||
12
packages/bungee/src/plugin.ts
Normal file
12
packages/bungee/src/plugin.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { server } from '@ccms/api'
|
||||||
|
|
||||||
|
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||||
|
|
||||||
|
export class BungeeNativePluginManager extends server.NativePluginManager {
|
||||||
|
has(name: string) {
|
||||||
|
return !!this.get(name)
|
||||||
|
}
|
||||||
|
get(name: string) {
|
||||||
|
return Bungee.getPluginManager().getPlugin(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,17 +6,14 @@ let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class BungeeTaskManager extends task.TaskManager {
|
export class BungeeTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
private pluginInstance: any
|
return new BungeeTask(owner, func, id)
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
|
||||||
return new BungeeTask(this.pluginInstance, func)
|
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func()
|
return func()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
this.pluginInstance.getProxy().getScheduler().cancel(this.pluginInstance)
|
base.getInstance().getProxy().getScheduler().cancel(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,12 +21,12 @@ export class BungeeTask extends task.Task {
|
|||||||
submit0(...args: any[]): task.Cancelable {
|
submit0(...args: any[]): task.Cancelable {
|
||||||
let run = new Runnable({ run: () => this.run(...args) })
|
let run = new Runnable({ run: () => this.run(...args) })
|
||||||
if (this.isAsync) {
|
if (this.isAsync) {
|
||||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
return base.getInstance().getProxy().getScheduler().runAsync(base.getInstance(), run)
|
||||||
}
|
}
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
||||||
} else {
|
} else {
|
||||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "@ccms/client",
|
"name": "@ccms/client",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript client package",
|
"description": "MiaoScript client package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,10 +22,11 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"minecraft-protocol": "^1.16.0"
|
"minecraft-protocol": "^1.24.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/node": "^14.14.37",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,10 +4,12 @@ import { createClient } from 'minecraft-protocol'
|
|||||||
import { attachForge } from './forge'
|
import { attachForge } from './forge'
|
||||||
import { attachEvents } from './event'
|
import { attachEvents } from './event'
|
||||||
|
|
||||||
let username = process.argv[2] || 'Mr_jtb'
|
let readUserInfo = process.argv[2] || 'Mr_jtb'
|
||||||
let password = process.argv[3] || ''
|
let realUserInfo = readUserInfo.split(":")
|
||||||
let version = process.argv[4] || '1.12.2'
|
let username = realUserInfo[0]
|
||||||
let readAddress = process.argv[5] || '192.168.2.5:25577'
|
let password = realUserInfo[1] || ''
|
||||||
|
let version = process.argv[3] || '1.12.2'
|
||||||
|
let readAddress = process.argv[4] || '192.168.2.25:25565'
|
||||||
let realAddress = readAddress.split(":")
|
let realAddress = readAddress.split(":")
|
||||||
let address = realAddress[0]
|
let address = realAddress[0]
|
||||||
let port = parseInt(realAddress[1] || "25565")
|
let port = parseInt(realAddress[1] || "25565")
|
||||||
@@ -18,17 +20,23 @@ function commandLineCreateClient() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createConnection(host: string, port: number, username: string, password: string) {
|
function createConnection(host: string, port: number, username: string, password: string) {
|
||||||
let client = createClient({
|
let clientOptions: any = {
|
||||||
version,
|
version,
|
||||||
host,
|
host,
|
||||||
port,
|
port,
|
||||||
username,
|
username,
|
||||||
password,
|
password,
|
||||||
clientToken: 'd02c7f39-2376-45da-a5a5-50e24fa8b185',
|
// clientToken: 'd02c7f39-2376-45da-a5a5-50e24fa8b185',
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
authServer: 'https://mcsso.yumc.pw/api/yggdrasil/authserver',
|
// authServer: 'https://skin.yumc.pw/api/yggdrasil/authserver',
|
||||||
sessionServer: 'https://mcsso.yumc.pw/api/yggdrasil/sessionserver'
|
// sessionServer: 'https://skin.yumc.pw/api/yggdrasil/sessionserver'
|
||||||
})
|
}
|
||||||
|
if (clientOptions.password) {
|
||||||
|
clientOptions.clientToken = 'd02c7f39-2376-45da-a5a5-50e24fa8b185'
|
||||||
|
clientOptions.authServer = 'https://skin.yumc.pw/api/yggdrasil/authserver'
|
||||||
|
clientOptions.sessionServer = 'https://skin.yumc.pw/api/yggdrasil/sessionserver'
|
||||||
|
}
|
||||||
|
let client = createClient(clientOptions)
|
||||||
|
|
||||||
attachCommon(client)
|
attachCommon(client)
|
||||||
attachForge(client)
|
attachForge(client)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/common",
|
"name": "@ccms/common",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,11 +19,11 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.10.0",
|
"@ccms/nashorn": "^0.14.0",
|
||||||
"@javatypes/jdk": "^0.0.3",
|
"@javatypes/jdk": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ interface RequestConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function request(config: RequestConfig) {
|
function request(config: RequestConfig) {
|
||||||
// @ts-ignore
|
// @ts-ignore XMLHttpRequest class only exist nashorn polyfill
|
||||||
let xhr = new XMLHttpRequest()
|
let xhr = new XMLHttpRequest()
|
||||||
xhr.open(config.method, config.url, false)
|
xhr.open(config.method, config.url, false)
|
||||||
for (const header in config.headers) {
|
for (const header in config.headers) {
|
||||||
@@ -44,6 +44,7 @@ function request(config: RequestConfig) {
|
|||||||
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
|
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
|
||||||
xhr.responseType = "json"
|
xhr.responseType = "json"
|
||||||
}
|
}
|
||||||
|
// @ts-ignore get only exist nashorn polyfill
|
||||||
return xhr.get()
|
return xhr.get()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/compile",
|
"name": "@ccms/compile",
|
||||||
"version": "0.10.0",
|
"version": "0.14.0",
|
||||||
"description": "MiaoScript compile package",
|
"description": "MiaoScript compile package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,6 +21,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/container",
|
"name": "@ccms/container",
|
||||||
"version": "0.10.0",
|
"version": "0.14.0",
|
||||||
"description": "MiaoScript container package",
|
"description": "MiaoScript container package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,13 +19,13 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.10.0",
|
"@ccms/nashorn": "^0.14.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"inversify": "^5.0.1",
|
"inversify": "^5.0.5",
|
||||||
"inversify-binding-decorators": "^4.0.0"
|
"inversify-binding-decorators": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/core",
|
"name": "@ccms/core",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,11 +21,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0"
|
"@ccms/container": "^0.14.0"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,23 @@
|
|||||||
let containerStartTime = Date.now()
|
let containerStartTime = Date.now()
|
||||||
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
||||||
import { plugin, server, task, constants } from '@ccms/api'
|
import { plugin, server, task, constants } from '@ccms/api'
|
||||||
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ccms/container'
|
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule, Autowired } from '@ccms/container'
|
||||||
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
||||||
import http from '@ccms/common/dist/http'
|
import http from '@ccms/common/dist/http'
|
||||||
|
|
||||||
@provideSingleton(MiaoScriptCore)
|
@provideSingleton(MiaoScriptCore)
|
||||||
class MiaoScriptCore {
|
class MiaoScriptCore {
|
||||||
@inject(server.Console)
|
@Autowired(server.Console)
|
||||||
private Console: Console
|
private Console: Console
|
||||||
@inject(task.TaskManager)
|
@Autowired(plugin.PluginFolder)
|
||||||
private taskManager: task.TaskManager
|
|
||||||
@inject(plugin.PluginFolder)
|
|
||||||
private pluginFolder: string
|
private pluginFolder: string
|
||||||
@inject(plugin.PluginManager)
|
@Autowired()
|
||||||
|
private taskManager: task.TaskManager
|
||||||
|
@Autowired()
|
||||||
private pluginManager: plugin.PluginManager
|
private pluginManager: plugin.PluginManager
|
||||||
|
|
||||||
enable() {
|
enable() {
|
||||||
this.loadServerConsole()
|
this.loadServerConsole()
|
||||||
this.loadTaskFunction()
|
|
||||||
global.level = "TRACE"
|
|
||||||
this.loadPlugins()
|
this.loadPlugins()
|
||||||
return () => this.disable()
|
return () => this.disable()
|
||||||
}
|
}
|
||||||
@@ -29,15 +27,6 @@ class MiaoScriptCore {
|
|||||||
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
||||||
}
|
}
|
||||||
|
|
||||||
loadTaskFunction() {
|
|
||||||
global.setGlobal('setTimeout', (func: Function, tick: number, ...args: any[]) => {
|
|
||||||
return this.taskManager.create(func).later(tick).submit(...args)
|
|
||||||
}, { writable: false, configurable: false })
|
|
||||||
global.setGlobal('setInterval', (func: Function, tick: number, ...args: any[]) => {
|
|
||||||
return this.taskManager.create(func).timer(tick).submit(...args)
|
|
||||||
}, { writable: false, configurable: false })
|
|
||||||
}
|
|
||||||
|
|
||||||
loadPlugins() {
|
loadPlugins() {
|
||||||
let loadPluginStartTime = new Date().getTime()
|
let loadPluginStartTime = new Date().getTime()
|
||||||
console.i18n("ms.core.plugin.initialize")
|
console.i18n("ms.core.plugin.initialize")
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/database",
|
"name": "@ccms/database",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript database package",
|
"description": "MiaoScript database package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,10 +22,10 @@
|
|||||||
"@javatypes/spring-jdbc": "^0.0.3",
|
"@javatypes/spring-jdbc": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0"
|
"@ccms/container": "^0.14.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
ms.i18n.completed: "Internationalization component initialization completed. Current Language: English"
|
ms.i18n.completed: "Internationalization component initialization completed. Current Language: English"
|
||||||
ms.ployfill.initialize: "Initialization Java Nashorn ployfill. Please wait..."
|
ms.polyfill.initialize: "Initialization Java Nashorn polyfill. Please wait..."
|
||||||
ms.ployfill.completed: "Java Nashorn ployfill loading completed... Cost ({time}s)!"
|
ms.polyfill.completed: "Java Nashorn polyfill loading completed... Cost ({time}s)!"
|
||||||
|
|
||||||
ms.core.ioc.initialize: "Initialization MiaoScript IOC Container {scope}/container. Please wait..."
|
ms.core.ioc.initialize: "Initialization MiaoScript IOC Container {scope}/container. Please wait..."
|
||||||
ms.core.ioc.completed: "MiaoScript IOC Container {scope}/container loading completed({time}s)!"
|
ms.core.ioc.completed: "MiaoScript IOC Container {scope}/container loading completed({time}s)!"
|
||||||
@@ -31,7 +31,8 @@ ms.api.command.tab.completer.error: "§6Player {player} §6exec §b{plugin} §6P
|
|||||||
|
|
||||||
ms.plugin.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
ms.plugin.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
||||||
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
||||||
ms.plugin.manager.scan: "Scanning Plugins in {folder} ..."
|
ms.plugin.manager.scan: "Scanner {scanner} Scanning Plugins in {folder} ..."
|
||||||
|
ms.plugin.manager.scan.finish: "Scanner {scanner} Found {size} Plugins in {folder} Start Build..."
|
||||||
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
||||||
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
|
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
|
||||||
ms.plugin.manager.stage.exec: "[{plugin}] Exec {name} Stage {stage} When servers is {servers}..."
|
ms.plugin.manager.stage.exec: "[{plugin}] Exec {name} Stage {stage} When servers is {servers}..."
|
||||||
@@ -39,6 +40,7 @@ ms.plugin.manager.stage.exec.error: "§6Plugin §b{plugin} §6exec §d{executor}
|
|||||||
ms.plugin.manager.stage.load: "Loading"
|
ms.plugin.manager.stage.load: "Loading"
|
||||||
ms.plugin.manager.stage.enable: "Enabling"
|
ms.plugin.manager.stage.enable: "Enabling"
|
||||||
ms.plugin.manager.stage.disable: "Disabling"
|
ms.plugin.manager.stage.disable: "Disabling"
|
||||||
|
ms.plugin.manager.build: "Plugin {name}({version}) Build Finish source: {file}({scanner}) loader: {loader} Cost: {cost}s."
|
||||||
ms.plugin.manager.build.error: "§6Load Plugin From §b{file} §6failed. §4Error: §c{error}"
|
ms.plugin.manager.build.error: "§6Load Plugin From §b{file} §6failed. §4Error: §c{error}"
|
||||||
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
||||||
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
ms.i18n.completed: "国际化组件 初始化完成 当前语言: 简体中文"
|
ms.i18n.completed: "国际化组件 初始化完成 当前语言: 简体中文"
|
||||||
ms.ployfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
ms.polyfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
||||||
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
ms.polyfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
||||||
|
|
||||||
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 {scope}/container. 请稍候..."
|
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 {scope}/container. 请稍候..."
|
||||||
ms.core.ioc.completed: "MiaoScript IOC 容器 {scope}/container 加载完成 耗时({time}s)"
|
ms.core.ioc.completed: "MiaoScript IOC 容器 {scope}/container 加载完成 耗时({time}s)"
|
||||||
@@ -32,7 +32,8 @@ ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin}
|
|||||||
|
|
||||||
ms.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
ms.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
||||||
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
||||||
ms.plugin.manager.scan: "扫描 {folder} 文件夹中插件..."
|
ms.plugin.manager.scan: "扫描器 {scanner} 扫描 {folder} 中的插件..."
|
||||||
|
ms.plugin.manager.scan.finish: "扫描器 {scanner} 在 {folder} 中 发现 {size} 个插件 开始构建..."
|
||||||
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
||||||
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
||||||
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
||||||
@@ -40,6 +41,7 @@ ms.plugin.manager.stage.exec.error: "§6插件 §b{plugin} §6执行 §d{executo
|
|||||||
ms.plugin.manager.stage.load: "加载"
|
ms.plugin.manager.stage.load: "加载"
|
||||||
ms.plugin.manager.stage.enable: "启用"
|
ms.plugin.manager.stage.enable: "启用"
|
||||||
ms.plugin.manager.stage.disable: "关闭"
|
ms.plugin.manager.stage.disable: "关闭"
|
||||||
|
ms.plugin.manager.build: "插件 {name}({version}) 构建完成 来源: {file}({scanner}) 引导: {loader} 构建耗时: {cost}s."
|
||||||
ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4错误: §c{error}"
|
ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4错误: §c{error}"
|
||||||
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
||||||
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/i18n",
|
"name": "@ccms/i18n",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript i18n package",
|
"description": "MiaoScript i18n package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,14 +19,14 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.10.0",
|
"@ccms/nashorn": "^0.14.0",
|
||||||
"@types/js-yaml": "^3.12.5",
|
"@types/js-yaml": "^4.0.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"js-yaml": "^3.14.0"
|
"js-yaml": "^4.0.0"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
/// <reference types="@ccms/nashorn" />
|
||||||
import * as yaml from 'js-yaml'
|
import * as yaml from 'js-yaml'
|
||||||
|
|
||||||
const File = Java.type("java.io.File");
|
const File = Java.type("java.io.File")
|
||||||
const separatorChar = File.separatorChar;
|
const separatorChar = File.separatorChar
|
||||||
type TranslateParam = { [key: string]: any }
|
type TranslateParam = { [key: string]: any }
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
interface Console {
|
interface Console {
|
||||||
i18n(name: string, param?: TranslateParam);
|
i18n(name: string, param?: TranslateParam)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,20 +23,20 @@ export class Translate {
|
|||||||
|
|
||||||
constructor(root: string | TranslateContent) {
|
constructor(root: string | TranslateContent) {
|
||||||
if (typeof root == 'string') {
|
if (typeof root == 'string') {
|
||||||
this.root = root;
|
this.root = root
|
||||||
} else {
|
} else {
|
||||||
this.langMap = root.langMap;
|
this.langMap = root.langMap
|
||||||
this.fallbackMap = root.fallbackMap || {};
|
this.fallbackMap = root.fallbackMap || {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
translate(name: string, param?: TranslateParam) {
|
translate(name: string, param?: TranslateParam) {
|
||||||
let langText: string = this.langMap[name] || this.fallbackMap[name];
|
let langText: string = this.langMap[name] || this.fallbackMap[name]
|
||||||
if (!langText) { return '[WARN] @ccms/i18n miss lang translate: ' + name }
|
if (!langText) { return '[WARN] @ccms/i18n miss lang translate: ' + name }
|
||||||
for (const key in param) {
|
for (const key in param) {
|
||||||
langText = langText.replace(new RegExp("{" + key + "}", 'gm'), param[key])
|
langText = langText.replace(new RegExp("{" + key + "}", 'gm'), param[key])
|
||||||
}
|
}
|
||||||
return langText;
|
return langText
|
||||||
}
|
}
|
||||||
|
|
||||||
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
||||||
@@ -49,8 +49,8 @@ export class Translate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
readYamlFile(dir: string, name: string) {
|
readYamlFile(dir: string, name: string) {
|
||||||
let langFile = this.concat(dir, 'languages', name + '.yml');
|
let langFile = this.concat(dir, 'languages', name + '.yml')
|
||||||
return this.exists(langFile) && yaml.safeLoad(base.read(langFile))
|
return this.exists(langFile) && yaml.load(base.read(langFile))
|
||||||
}
|
}
|
||||||
|
|
||||||
concat(...args: string[]) {
|
concat(...args: string[]) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/keyvalue",
|
"name": "@ccms/keyvalue",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript keyvalue package",
|
"description": "MiaoScript keyvalue package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,18 +19,18 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/common": "^0.10.0",
|
"@ccms/common": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0"
|
"@ccms/container": "^0.14.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.10.0",
|
"@ccms/nashorn": "^0.14.0",
|
||||||
"@javatypes/amqp-client": "^0.0.3",
|
"@javatypes/amqp-client": "^0.0.3",
|
||||||
"@javatypes/spring-amqp": "^0.0.3",
|
"@javatypes/spring-amqp": "^0.0.3",
|
||||||
"@javatypes/spring-rabbit": "^0.0.3",
|
"@javatypes/spring-rabbit": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/nashorn",
|
"name": "@ccms/nashorn",
|
||||||
"version": "0.10.0",
|
"version": "0.14.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,6 +22,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,12 +67,14 @@ declare global {
|
|||||||
interface Core {
|
interface Core {
|
||||||
getClass(name: String): any
|
getClass(name: String): any
|
||||||
getProxyClass(): any
|
getProxyClass(): any
|
||||||
|
getJavaScriptTaskClass(): any
|
||||||
getInstance(): any
|
getInstance(): any
|
||||||
read(path: string): string
|
read(path: string): string
|
||||||
save(path: string, content: string): void
|
save(path: string, content: string): void
|
||||||
delete(path: string): void
|
delete(path: string): void
|
||||||
}
|
}
|
||||||
interface Console {
|
interface Console {
|
||||||
|
prefix: string
|
||||||
ex(err: Error): void
|
ex(err: Error): void
|
||||||
stack(err: Error, color?: boolean): string[]
|
stack(err: Error, color?: boolean): string[]
|
||||||
sender(sender: any, ...args: any): void
|
sender(sender: any, ...args: any): void
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/nodejs",
|
"name": "@ccms/nodejs",
|
||||||
"version": "0.10.0",
|
"version": "0.14.0",
|
||||||
"description": "MiaoScript nodejs package",
|
"description": "MiaoScript nodejs package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,10 +19,10 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.10.0",
|
"@ccms/nashorn": "^0.14.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/nukkit",
|
"name": "@ccms/nukkit",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript nukkit package",
|
"description": "MiaoScript nukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/nukkit-api": "^0.0.3",
|
"@javatypes/nukkit-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/common": "^0.10.0",
|
"@ccms/common": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0"
|
"@ccms/container": "^0.14.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,25 @@
|
|||||||
import { MiaoScriptConsole } from '@ccms/api'
|
import { MiaoScriptConsole } from '@ccms/api'
|
||||||
|
|
||||||
let Nukkit = base.getInstance().getServer();
|
let Nukkit = base.getInstance().getServer()
|
||||||
|
let LogLevel = Java.type('cn.nukkit.utils.LogLevel')
|
||||||
let CommandSender = Java.type('cn.nukkit.command.CommandSender')
|
let CommandSender = Java.type('cn.nukkit.command.CommandSender')
|
||||||
|
|
||||||
export class NukkitConsole extends MiaoScriptConsole {
|
export class NukkitConsole extends MiaoScriptConsole {
|
||||||
sender(sender, ...args) {
|
sender(sender, ...args) {
|
||||||
if (!(sender instanceof CommandSender)) {
|
if (!(sender instanceof CommandSender)) {
|
||||||
this.error(`First parameter ${sender} not instanceof cn.nukkit.command.CommandSender can't send message!`)
|
this.error(`First parameter ${sender} not instanceof cn.nukkit.command.CommandSender can't send message!`)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (Object.prototype.toString.call(args[0]) === "[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: string[]): void {
|
console(...args: string[]): void {
|
||||||
this.sender(Nukkit.getConsoleSender(), args.join(' '));
|
this.sender(Nukkit.getConsoleSender(), args.join(' '))
|
||||||
|
}
|
||||||
|
error(...args: any[]) {
|
||||||
|
this.logger.log(LogLevel.ERROR, this.name + args.join(' '))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,14 @@
|
|||||||
import { server } from '@ccms/api'
|
import { server } from '@ccms/api'
|
||||||
import { Container } from '@ccms/container'
|
import { Container } from '@ccms/container'
|
||||||
|
|
||||||
import { NukkitConsole } from './console';
|
import { NukkitConsole } from './console'
|
||||||
import './event';
|
import './task'
|
||||||
import './server';
|
import './event'
|
||||||
import './command';
|
import './server'
|
||||||
import './task';
|
import { NukkitNativePluginManager } from './plugin'
|
||||||
|
import './command'
|
||||||
|
|
||||||
export default function NukkitImpl(container: Container) {
|
export default function NukkitImpl(container: Container) {
|
||||||
container.bind(server.Console).toConstantValue(NukkitConsole);
|
container.bind(server.Console).toConstantValue(NukkitConsole)
|
||||||
|
container.bind(server.NativePluginManager).toConstantValue(new NukkitNativePluginManager())
|
||||||
}
|
}
|
||||||
|
|||||||
12
packages/nukkit/src/plugin.ts
Normal file
12
packages/nukkit/src/plugin.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { server } from '@ccms/api'
|
||||||
|
|
||||||
|
let Nukkit: cn.nukkit.Server = base.getInstance().getServer()
|
||||||
|
|
||||||
|
export class NukkitNativePluginManager extends server.NativePluginManager {
|
||||||
|
has(name: string) {
|
||||||
|
return !!this.get(name)
|
||||||
|
}
|
||||||
|
get(name: string) {
|
||||||
|
return Nukkit.getPluginManager().getPlugin(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,17 +5,14 @@ const NukkitRunnable = Java.type('cn.nukkit.scheduler.NukkitRunnable')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class NukkitTaskManager extends task.TaskManager {
|
export class NukkitTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
private pluginInstance: any
|
return new NukkitTask(owner, func, id)
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
|
||||||
return new NukkitTask(this.pluginInstance, func)
|
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func()
|
return func()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
base.getInstance().getServer().getScheduler().cancelTask(this.pluginInstance)
|
base.getInstance().getServer().getScheduler().cancelTask(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,9 +21,9 @@ export class NukkitTask extends task.Task {
|
|||||||
let run = new NukkitRunnable({ run: () => this.run(...args) })
|
let run = new NukkitRunnable({ run: () => this.run(...args) })
|
||||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
return run[funcName](base.getInstance(), this.laterTime, this.interval)
|
||||||
} else {
|
} else {
|
||||||
return run[funcName](this.plugin, this.laterTime)
|
return run[funcName](base.getInstance(), this.laterTime)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
import { EventEmitter } from 'events'
|
|
||||||
|
|
||||||
const Thread = Java.type('java.lang.Thread')
|
|
||||||
const ThreadGroup = Java.type("java.lang.ThreadGroup")
|
|
||||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
|
||||||
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
|
|
||||||
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
|
|
||||||
|
|
||||||
const threadCount = new AtomicInteger(0)
|
|
||||||
const threadGroup = new ThreadGroup("@ccms/ployfill-micro-task")
|
|
||||||
const microTaskPool = new ThreadPoolExecutor(
|
|
||||||
10, 100, 60, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
|
||||||
new LinkedBlockingQueue(500),
|
|
||||||
(run: any) => new Thread(threadGroup, run, "@ccms/micro-task-" + threadCount.incrementAndGet()),
|
|
||||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
|
||||||
)
|
|
||||||
|
|
||||||
class Process extends EventEmitter {
|
|
||||||
env = {
|
|
||||||
__noSuchProperty__: (prop) => {
|
|
||||||
return Packages.java.lang.System.getenv(prop)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
platform = Packages.java.lang.System.getProperty("os.name")
|
|
||||||
nextTick(func: Function) {
|
|
||||||
microTaskPool.execute(func)
|
|
||||||
}
|
|
||||||
queueMicrotask(func: Function) {
|
|
||||||
microTaskPool.execute(func)
|
|
||||||
}
|
|
||||||
exit(code: number) {
|
|
||||||
process.emit('exit', code)
|
|
||||||
microTaskPool.shutdown()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
global.setGlobal('process', new Process(), {})
|
|
||||||
global.setGlobal('queueMicrotask', (func: any) => microTaskPool.execute(func), {})
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
(function nashornEventLoopMain(context) {
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
var Thread = Java.type('java.lang.Thread');
|
|
||||||
var Phaser = Java.type('java.util.concurrent.Phaser');
|
|
||||||
var ArrayDeque = Java.type('java.util.ArrayDeque');
|
|
||||||
var HashMap = Java.type('java.util.HashMap');
|
|
||||||
var TimeUnit = Java.type("java.util.concurrent.TimeUnit");
|
|
||||||
var Runnable = Java.type('java.lang.Runnable');
|
|
||||||
|
|
||||||
var globalTimerId;
|
|
||||||
var timerMap;
|
|
||||||
var eventLoop;
|
|
||||||
var phaser = new Phaser();
|
|
||||||
|
|
||||||
// __NASHORN_POLYFILL_TIMER__ type is ScheduledExecutorService
|
|
||||||
var scheduler = context.__NASHORN_POLYFILL_TIMER__;
|
|
||||||
|
|
||||||
resetEventLoop();
|
|
||||||
|
|
||||||
// console.log('main javasript thread ' + Thread.currentThread().getName());
|
|
||||||
|
|
||||||
function resetEventLoop() {
|
|
||||||
globalTimerId = 1;
|
|
||||||
if (timerMap) {
|
|
||||||
timerMap.forEach(function(key, value) {
|
|
||||||
value.cancel(true);
|
|
||||||
})
|
|
||||||
}
|
|
||||||
timerMap = new HashMap();
|
|
||||||
eventLoop = new ArrayDeque();
|
|
||||||
}
|
|
||||||
|
|
||||||
function waitForMessages() {
|
|
||||||
phaser.register();
|
|
||||||
var wait = !(eventLoop.size() === 0);
|
|
||||||
phaser.arriveAndDeregister();
|
|
||||||
return wait;
|
|
||||||
}
|
|
||||||
|
|
||||||
function processNextMessages() {
|
|
||||||
var remaining = 1;
|
|
||||||
while (remaining) {
|
|
||||||
phaser.register();
|
|
||||||
var message = eventLoop.removeFirst();
|
|
||||||
remaining = eventLoop.size();
|
|
||||||
phaser.arriveAndDeregister();
|
|
||||||
|
|
||||||
var fn = message.fn;
|
|
||||||
var args = message.args;
|
|
||||||
|
|
||||||
try {
|
|
||||||
fn.apply(context, args);
|
|
||||||
} catch (e) {
|
|
||||||
console.trace(e);
|
|
||||||
console.trace(fn);
|
|
||||||
console.trace(args);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
context.nashornEventLoop = {
|
|
||||||
process: function() {
|
|
||||||
while (waitForMessages()) {
|
|
||||||
processNextMessages()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
reset: resetEventLoop
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
function createRunnable(fn, timerId, args, repeated) {
|
|
||||||
return new Runnable({
|
|
||||||
run: function() {
|
|
||||||
try {
|
|
||||||
var phase = phaser.register();
|
|
||||||
eventLoop.addLast({
|
|
||||||
fn: fn,
|
|
||||||
args: args
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
console.trace(e);
|
|
||||||
} finally {
|
|
||||||
if (!repeated) timerMap.remove(timerId);
|
|
||||||
phaser.arriveAndDeregister();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
var setTimeout = function(fn, millis /* [, args...] */) {
|
|
||||||
var args = [].slice.call(arguments, 2, arguments.length);
|
|
||||||
|
|
||||||
var timerId = globalTimerId++;
|
|
||||||
var runnable = createRunnable(fn, timerId, args, false);
|
|
||||||
|
|
||||||
var task = scheduler.schedule(runnable, millis, TimeUnit.MILLISECONDS);
|
|
||||||
timerMap.put(timerId, task);
|
|
||||||
|
|
||||||
return timerId;
|
|
||||||
};
|
|
||||||
|
|
||||||
var setImmediate = function(fn /* [, args...] */) {
|
|
||||||
var args = [].slice.call(arguments, 1, arguments.length);
|
|
||||||
// @ts-ignore
|
|
||||||
return setTimeout(fn, 0, args);
|
|
||||||
}
|
|
||||||
|
|
||||||
var clearImmediate = function(timerId) {
|
|
||||||
clearTimeout(timerId);
|
|
||||||
}
|
|
||||||
|
|
||||||
var clearTimeout = function(timerId) {
|
|
||||||
var task = timerMap.get(timerId);
|
|
||||||
if (task) {
|
|
||||||
task.cancel(true);
|
|
||||||
timerMap.remove(timerId);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
var setInterval = function(fn, delay /* [, args...] */) {
|
|
||||||
var args = [].slice.call(arguments, 2, arguments.length);
|
|
||||||
var timerId = globalTimerId++;
|
|
||||||
var runnable = createRunnable(fn, timerId, args, true);
|
|
||||||
var task = scheduler.scheduleWithFixedDelay(runnable, delay, delay, TimeUnit.MILLISECONDS);
|
|
||||||
timerMap.put(timerId, task);
|
|
||||||
return timerId;
|
|
||||||
};
|
|
||||||
|
|
||||||
var clearInterval = function(timerId) {
|
|
||||||
clearTimeout(timerId);
|
|
||||||
};
|
|
||||||
|
|
||||||
context.setTimeout = setTimeout;
|
|
||||||
context.clearTimeout = clearTimeout;
|
|
||||||
context.setImmediate = setImmediate;
|
|
||||||
context.clearImmediate = clearImmediate;
|
|
||||||
context.setInterval = setInterval;
|
|
||||||
context.clearInterval = clearInterval;
|
|
||||||
// @ts-ignore
|
|
||||||
})(typeof global !== "undefined" && global || typeof self !== "undefined" && self || this);
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/plugin",
|
"name": "@ccms/plugin",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,16 +19,16 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/js-yaml": "^3.12.5",
|
"@types/js-yaml": "^4.0.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/common": "^0.10.0",
|
"@ccms/common": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0",
|
"@ccms/container": "^0.14.0",
|
||||||
"@ccms/i18n": "^0.10.0",
|
"@ccms/i18n": "^0.14.1",
|
||||||
"js-yaml": "^3.14.0"
|
"js-yaml": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { command, plugin, server } from '@ccms/api'
|
import { command, plugin, server } from '@ccms/api'
|
||||||
import { provideSingleton, inject, Autowired } from '@ccms/container'
|
import { provideSingleton, Autowired } from '@ccms/container'
|
||||||
|
import { interfaces } from './interfaces'
|
||||||
import { getPluginCommandMetadata, getPluginTabCompleterMetadata } from './utils'
|
import { getPluginCommandMetadata, getPluginTabCompleterMetadata } from './utils'
|
||||||
|
|
||||||
@provideSingleton(PluginCommandManager)
|
@provideSingleton(PluginCommandManager)
|
||||||
@@ -23,11 +24,10 @@ export class PluginCommandManager {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for (let command of [cmd.name, ...cmd.alias]) {
|
for (let command of [cmd.name, ...cmd.alias]) {
|
||||||
|
let [cmdExecutor, cmdCompleter] = this.generateAutoMainCommand(pluginInstance, cmd, tabs.get(command))
|
||||||
this.CommandManager.on(pluginInstance, command, {
|
this.CommandManager.on(pluginInstance, command, {
|
||||||
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
cmd: cmdExecutor.bind(pluginInstance),
|
||||||
tab: tabs.has(command) ?
|
tab: cmdCompleter?.bind(pluginInstance)
|
||||||
pluginInstance[tabs.get(command).executor].bind(pluginInstance) :
|
|
||||||
console.debug(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -37,4 +37,29 @@ export class PluginCommandManager {
|
|||||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||||
cmds.forEach(cmd => this.CommandManager.off(pluginInstance, cmd.name))
|
cmds.forEach(cmd => this.CommandManager.off(pluginInstance, cmd.name))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private generateAutoMainCommand(pluginInstance: plugin.Plugin, cmd: interfaces.CommandMetadata, tab: interfaces.CommandMetadata) {
|
||||||
|
let cmdExecutor = pluginInstance[cmd.executor]
|
||||||
|
let cmdCompleter = tab ? pluginInstance[tab.executor] : undefined
|
||||||
|
let cmdSubCache = Object.keys(pluginInstance.constructor.prototype).filter(s => s.startsWith('cmd')).map(s => s.substring(3))
|
||||||
|
if (cmd.autoMain) {
|
||||||
|
cmdExecutor = (sender: any, command: string, args: string[]) => {
|
||||||
|
let subcommand = args[0] || 'help'
|
||||||
|
let cmdKey = 'cmd' + subcommand
|
||||||
|
if (!pluginInstance[cmdKey]) {
|
||||||
|
console.sender(sender, '§4未知的子命令: §c' + subcommand)
|
||||||
|
pluginInstance['cmdhelp'] && console.sender(sender, `§6请执行 §b/${command} §ahelp §6查看帮助!`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
args.shift()
|
||||||
|
return pluginInstance[cmdKey].apply(pluginInstance, [sender, ...args])
|
||||||
|
}
|
||||||
|
let originCompleter = cmdCompleter
|
||||||
|
cmdCompleter = (sender: any, command: string, args: string[]) => {
|
||||||
|
return (args.length == 1 ? cmdSubCache : []).concat(originCompleter?.apply(pluginInstance, [sender, command, args]) || [])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!cmdCompleter) { console.warn(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`) }
|
||||||
|
return [cmdExecutor, cmdCompleter]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,10 +13,10 @@ export interface PluginConfigLoader {
|
|||||||
|
|
||||||
export class YamlPluginConfig implements PluginConfigLoader {
|
export class YamlPluginConfig implements PluginConfigLoader {
|
||||||
load(content: string) {
|
load(content: string) {
|
||||||
return yaml.safeLoad(content)
|
return yaml.load(content)
|
||||||
}
|
}
|
||||||
dump(variable: any): string {
|
dump(variable: any): string {
|
||||||
return yaml.safeDump(variable, { skipInvalid: true, lineWidth: 120 })
|
return yaml.dump(variable, { skipInvalid: true, lineWidth: 120 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,6 +92,16 @@ export class PluginConfigManager {
|
|||||||
} else {
|
} else {
|
||||||
value = configLoader.load(base.read(metadata.file))
|
value = configLoader.load(base.read(metadata.file))
|
||||||
console.debug(`[${plugin.description.name}] Load Config ${metadata.variable} from file ${metadata.file} =>\n${JSON.stringify(value, undefined, 4)}`)
|
console.debug(`[${plugin.description.name}] Load Config ${metadata.variable} from file ${metadata.file} =>\n${JSON.stringify(value, undefined, 4)}`)
|
||||||
|
if (metadata.default) {
|
||||||
|
let needSave = false
|
||||||
|
for (const key of Object.keys(metadata.default)) {
|
||||||
|
if (value[key] == undefined) {
|
||||||
|
value[key] = metadata.default[key]
|
||||||
|
needSave = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
needSave && base.save(metadata.file, configLoader.dump(value))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
this.defienConfigProp(plugin, metadata, value)
|
this.defienConfigProp(plugin, metadata, value)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -47,6 +47,10 @@ export namespace interfaces {
|
|||||||
* 参数列表
|
* 参数列表
|
||||||
*/
|
*/
|
||||||
paramtypes?: string[]
|
paramtypes?: string[]
|
||||||
|
/**
|
||||||
|
* 自动化主命令
|
||||||
|
*/
|
||||||
|
autoMain?: boolean
|
||||||
}
|
}
|
||||||
export interface ListenerMetadata extends ExecMetadata {
|
export interface ListenerMetadata extends ExecMetadata {
|
||||||
/**
|
/**
|
||||||
@@ -63,6 +67,10 @@ export namespace interfaces {
|
|||||||
* 配置文件版本号
|
* 配置文件版本号
|
||||||
*/
|
*/
|
||||||
version?: number
|
version?: number
|
||||||
|
/**
|
||||||
|
* 默认配置
|
||||||
|
*/
|
||||||
|
default?: any
|
||||||
/**
|
/**
|
||||||
* 实体变量名称
|
* 实体变量名称
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -81,9 +81,12 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
this.initialize()
|
this.initialize()
|
||||||
for (const [, scanner] of this.sacnnerMap) {
|
for (const [, scanner] of this.sacnnerMap) {
|
||||||
try {
|
try {
|
||||||
scanner.scan(folder).forEach(loadMetadata => {
|
console.i18n('ms.plugin.manager.scan', { scanner: scanner.type, folder })
|
||||||
|
let plugins = scanner.scan(folder)
|
||||||
|
console.i18n('ms.plugin.manager.scan.finish', { scanner: scanner.type, folder, size: plugins.length })
|
||||||
|
plugins.forEach(loadMetadata => {
|
||||||
try {
|
try {
|
||||||
this.loadPlugin(scanner.load(loadMetadata))
|
this.loadAndRequirePlugin(loadMetadata)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`plugin scanner ${scanner.type} load ${loadMetadata.file} occurred error ${error}`)
|
console.error(`plugin scanner ${scanner.type} load ${loadMetadata.file} occurred error ${error}`)
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
@@ -158,6 +161,20 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private loadAndRequirePlugin(loadMetadata: plugin.PluginLoadMetadata) {
|
||||||
|
let startTime = Date.now()
|
||||||
|
let metadata = this.loadPlugin(loadMetadata.scanner.load(loadMetadata))
|
||||||
|
console.i18n('ms.plugin.manager.build', {
|
||||||
|
name: loadMetadata.metadata.name,
|
||||||
|
version: loadMetadata.metadata.version,
|
||||||
|
file: loadMetadata.file.toString().replace(root, ''),
|
||||||
|
scanner: loadMetadata.scanner.type,
|
||||||
|
loader: loadMetadata.loader.type,
|
||||||
|
cost: (Date.now() - startTime) / 1000
|
||||||
|
})
|
||||||
|
return metadata
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从文件加载插件
|
* 从文件加载插件
|
||||||
* @param file java.io.File
|
* @param file java.io.File
|
||||||
@@ -165,7 +182,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
loadFromFile(file: string, scanner = this.sacnnerMap.get('file')): plugin.Plugin {
|
loadFromFile(file: string, scanner = this.sacnnerMap.get('file')): plugin.Plugin {
|
||||||
if (!file) { throw new Error('plugin file can\'t be undefiend!') }
|
if (!file) { throw new Error('plugin file can\'t be undefiend!') }
|
||||||
if (!scanner) { throw new Error('plugin scanner can\'t be undefiend!') }
|
if (!scanner) { throw new Error('plugin scanner can\'t be undefiend!') }
|
||||||
let metadata = this.loadPlugin(scanner.load(scanner.read(file)))
|
let metadata = this.loadAndRequirePlugin(scanner.read(file))
|
||||||
let plugin = this.buildPlugin(metadata)
|
let plugin = this.buildPlugin(metadata)
|
||||||
this.load(plugin)
|
this.load(plugin)
|
||||||
this.enable(plugin)
|
this.enable(plugin)
|
||||||
@@ -233,21 +250,25 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private checkDepends(depends: string | string[]) {
|
private checkDepends(depends: string | string[]) {
|
||||||
if (!depends) return true
|
if (!depends) return []
|
||||||
for (const depend of depends) { if (!this.metadataMap.has(depend)) return false }
|
let loseDepends = []
|
||||||
return true
|
for (const depend of depends) { if (!this.metadataMap.has(depend)) loseDepends.push(depend) }
|
||||||
|
return loseDepends
|
||||||
}
|
}
|
||||||
private checkNativeDepends(depends: string | string[]) {
|
private checkNativeDepends(depends: string | string[]) {
|
||||||
if (!depends) return true
|
if (!depends) return []
|
||||||
for (const depend of depends) { if (!this.nativePluginManager.has(depend)) return false }
|
let loseDepends = []
|
||||||
return true
|
for (const depend of depends) { if (!this.nativePluginManager.has(depend)) loseDepends.push(depend) }
|
||||||
|
return loseDepends
|
||||||
}
|
}
|
||||||
private buildPlugin(metadata: plugin.PluginMetadata) {
|
private buildPlugin(metadata: plugin.PluginMetadata) {
|
||||||
if (this.instanceMap.has(metadata.name)) { throw new Error(`Plugin ${metadata.name} is already load from ${metadata.source}...`) }
|
if (this.instanceMap.has(metadata.name)) { throw new Error(`Plugin ${metadata.name} is already load from ${metadata.source}...`) }
|
||||||
if (!this.loaderMap.has(metadata.type)) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查 §c${metadata.type} §4加载器是否正常启用!`) }
|
if (!this.loaderMap.has(metadata.type)) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查 §c${metadata.type} §4加载器是否正常启用!`) }
|
||||||
if (!this.serverChecker.check(metadata.servers)) { throw new Error(`§6插件 §b${metadata.name} §c服务器类型不兼容(${metadata.servers.join(',')}) §6忽略加载...`) }
|
if (!this.serverChecker.check(metadata.servers)) { throw new Error(`§6插件 §b${metadata.name} §c服务器类型不兼容(${metadata.servers.join(',')}) §6忽略加载...`) }
|
||||||
if (!this.checkDepends(metadata.depends)) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查依赖 §3${metadata.depends.join(',')} §4是否安装完整!`) }
|
let loseDepends = this.checkDepends(metadata.depends) || []
|
||||||
if (!this.checkNativeDepends(metadata.nativeDepends)) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查插件依赖 §3${metadata.nativeDepends.join(',')} §4是否安装完整!`) }
|
if (loseDepends.length) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查依赖 §3[${loseDepends.join(',')}] §4是否安装完整!`) }
|
||||||
|
let loseNativeDepends = this.checkNativeDepends(metadata.nativeDepends) || []
|
||||||
|
if (loseNativeDepends.length) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查插件依赖 §3[${loseNativeDepends.join(',')}] §4是否安装完整!`) }
|
||||||
let pluginInstance = this.loaderMap.get(metadata.type).build(metadata)
|
let pluginInstance = this.loaderMap.get(metadata.type).build(metadata)
|
||||||
if (!pluginInstance) { throw new Error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`) }
|
if (!pluginInstance) { throw new Error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`) }
|
||||||
this.instanceMap.set(metadata.name, pluginInstance)
|
this.instanceMap.set(metadata.name, pluginInstance)
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ export class JSFileScanner implements plugin.PluginScanner {
|
|||||||
|
|
||||||
private scanFolder(folder: any): string[] {
|
private scanFolder(folder: any): string[] {
|
||||||
var files = []
|
var files = []
|
||||||
console.i18n('ms.plugin.manager.scan', { folder })
|
|
||||||
this.checkUpdateFolder(folder)
|
this.checkUpdateFolder(folder)
|
||||||
// must check file is exist maybe is a illegal symbolic link file
|
// must check file is exist maybe is a illegal symbolic link file
|
||||||
fs.list(folder).forEach((path: any) => {
|
fs.list(folder).forEach((path: any) => {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export class PluginTaskManager {
|
|||||||
private taskManager: task.TaskManager
|
private taskManager: task.TaskManager
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.cancelTask(plugin))
|
process.on('plugin.after.disable', this.cancelTask.bind(this))
|
||||||
}
|
}
|
||||||
|
|
||||||
private cancelTask(pluginInstance: plugin.Plugin) {
|
private cancelTask(pluginInstance: plugin.Plugin) {
|
||||||
|
|||||||
33
packages/plugins/docs/MiaoMail.md
Normal file
33
packages/plugins/docs/MiaoMail.md
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
private static void injectInventoryAddItemMethod() {
|
||||||
|
System.out.println("Injectoring Mail...");
|
||||||
|
try {
|
||||||
|
ClassPool pool = ClassPool.getDefault();
|
||||||
|
String inventoryClassName = Bukkit.getServer().getClass().getPackage().getName() + ".inventory.CraftInventory";
|
||||||
|
File classFile = new File(URLDecoder.decode(InventoryDragEvent.class.getProtectionDomain().getCodeSource().getLocation().getPath().split("!")[0], "UTF-8"));
|
||||||
|
pool.appendClassPath(classFile.getPath());
|
||||||
|
classFile = new File(URLDecoder.decode(MailPlugin.class.getProtectionDomain().getCodeSource().getLocation().getPath().split("!")[0], "UTF-8"));
|
||||||
|
pool.appendClassPath(classFile.getPath());
|
||||||
|
CtClass inventoryClass = pool.get(inventoryClassName);
|
||||||
|
CtMethod addItemMethod = inventoryClass.getDeclaredMethod("addItem");
|
||||||
|
|
||||||
|
addItemMethod.insertAfter(
|
||||||
|
"if(this instanceof org.bukkit.inventory.PlayerInventory){"
|
||||||
|
+ " final org.bukkit.inventory.PlayerInventory playerInventory = (org.bukkit.inventory.PlayerInventory)this;"
|
||||||
|
+ " final org.bukkit.entity.Player player = (org.bukkit.entity.Player)playerInventory.getHolder();"
|
||||||
|
+ " if(!$_.values().isEmpty()){"
|
||||||
|
+ " org.bukkit.event.inventory.InventoryDragEvent event = new org.bukkit.event.inventory.InventoryDragEvent(player.getOpenInventory(), new org.bukkit.inventory.ItemStack(org.bukkit.Material.AIR), new org.bukkit.inventory.ItemStack(org.bukkit.Material.AIR), true, $_);"
|
||||||
|
+ " event.setCancelled(true);"
|
||||||
|
+ " event.setResult(org.bukkit.event.Event.Result.DENY);"
|
||||||
|
+ " org.bukkit.Bukkit.getPluginManager().callEvent(event);"
|
||||||
|
+ " }"
|
||||||
|
+ "}");
|
||||||
|
try {
|
||||||
|
inventoryClass.toClass();
|
||||||
|
System.out.println("Injected");
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("Inject fail, Please restart server");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
14
packages/plugins/docs/MiaoPay.md
Normal file
14
packages/plugins/docs/MiaoPay.md
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
# MiaoPay
|
||||||
|
|
||||||
|
## 安装方式
|
||||||
|
先按照帖子
|
||||||
|
|
||||||
|
### 网关
|
||||||
|
- https://pay.yumc.pw/api
|
||||||
|
|
||||||
|
### 相关接口
|
||||||
|
|
||||||
|
#### 创建订单
|
||||||
|
- METHOD: /create
|
||||||
|
- PARAM:
|
||||||
|
-
|
||||||
112
packages/plugins/docs/MiaoReport.md
Normal file
112
packages/plugins/docs/MiaoReport.md
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
# MiaoReport(喵式报告)
|
||||||
|
|
||||||
|
## 插件简介
|
||||||
|
|
||||||
|
- 本插件只有一个功能 就是上报当前服务器信息和运行日志到 Ubuntu Paste
|
||||||
|
- 适用于哪些 有问题 但是不知道怎么提供报错的用户
|
||||||
|
|
||||||
|
## 插件命令
|
||||||
|
|
||||||
|
- 只有一个 `/mbrp`
|
||||||
|
- 并且只有 OP 权限用户才可以执行
|
||||||
|
|
||||||
|
## 功能预览
|
||||||
|
|
||||||
|
- 报告地址 https://paste.ubuntu.com/p/mVjJtb6Xcg/
|
||||||
|
- 报告详情(已删除无用信息 并不是完整报告)
|
||||||
|
|
||||||
|
```
|
||||||
|
当前报告由 MiaoBugReport(0.0.1) 生成 作者 MiaoWoo 官网 https://w.yumc.pw
|
||||||
|
生成时间: 2021-02-13 21:52:54
|
||||||
|
============================== 以下为本次报告内容 ==============================
|
||||||
|
服务器版本: git-Spigot-dcd1643-e60fc34 (MC: 1.12.2)
|
||||||
|
Bukkit版本: 1.12.2-R0.1-SNAPSHOT
|
||||||
|
============================== 运行数据 ==============================
|
||||||
|
运行时间: 1 小时 25 分 48 秒
|
||||||
|
CPU 核心: 16
|
||||||
|
最大内存: 7282 MB
|
||||||
|
分配内存: 626 MB
|
||||||
|
空闲内存: 307 MB
|
||||||
|
============================== 数据统计 ==============================
|
||||||
|
世界列表:
|
||||||
|
- world(NORMAL)
|
||||||
|
- 已加载区块: 272
|
||||||
|
- 实体数量: 146
|
||||||
|
- Tile数量: 10
|
||||||
|
- 玩家数量: 0
|
||||||
|
- world_nether(NETHER)
|
||||||
|
- 已加载区块: 0
|
||||||
|
- 实体数量: 0
|
||||||
|
- Tile数量: 0
|
||||||
|
- 玩家数量: 0
|
||||||
|
- world_the_end(THE_END)
|
||||||
|
- 已加载区块: 0
|
||||||
|
- 实体数量: 0
|
||||||
|
- Tile数量: 0
|
||||||
|
- 玩家数量: 0
|
||||||
|
在线玩家: Mr_jtb
|
||||||
|
插件列表: MiaoBugReport(0.0.1)
|
||||||
|
============================== 服务器线程堆栈 ==============================
|
||||||
|
"Spigot Metrics Thread" daemon prio=5 id=32
|
||||||
|
java.lang.Thread.State: TIMED_WAITING
|
||||||
|
at java.lang.Object.wait(Native Method)
|
||||||
|
at java.util.TimerThread.mainLoop(Unknown Source)
|
||||||
|
at java.util.TimerThread.run(Unknown Source)
|
||||||
|
|
||||||
|
"Spigot Watchdog Thread" prio=5 id=31
|
||||||
|
java.lang.Thread.State: TIMED_WAITING
|
||||||
|
at java.lang.Thread.sleep(Native Method)
|
||||||
|
at org.spigotmc.WatchdogThread.run(WatchdogThread.java:92)
|
||||||
|
|
||||||
|
"Server thread" prio=5 id=26
|
||||||
|
java.lang.Thread.State: TIMED_WAITING
|
||||||
|
at java.lang.Thread.sleep(Native Method)
|
||||||
|
at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:560)
|
||||||
|
at java.lang.Thread.run(Unknown Source)
|
||||||
|
|
||||||
|
"Server console handler" daemon prio=5 id=29
|
||||||
|
java.lang.Thread.State: RUNNABLE
|
||||||
|
at org.fusesource.jansi.internal.Kernel32.ReadConsoleInputW(Native Method)
|
||||||
|
at org.fusesource.jansi.internal.Kernel32.readConsoleInputHelper(Kernel32.java:761)
|
||||||
|
at org.fusesource.jansi.internal.Kernel32.readConsoleKeyInput(Kernel32.java:794)
|
||||||
|
at org.fusesource.jansi.internal.WindowsSupport.readConsoleInput(WindowsSupport.java:97)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.WindowsTerminal.readConsoleInput(WindowsTerminal.java:215)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.WindowsTerminal.access$000(WindowsTerminal.java:55)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.WindowsTerminal$1.read(WindowsTerminal.java:157)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.internal.NonBlockingInputStream.read(NonBlockingInputStream.java:169)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.internal.NonBlockingInputStream.read(NonBlockingInputStream.java:137)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.internal.NonBlockingInputStream.read(NonBlockingInputStream.java:246)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.internal.InputStreamReader.read(InputStreamReader.java:261)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.internal.InputStreamReader.read(InputStreamReader.java:198)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.console.ConsoleReader.readCharacter(ConsoleReader.java:2145)
|
||||||
|
at org.bukkit.craftbukkit.libs.jline.console.ConsoleReader.readLine(ConsoleReader.java:2349)
|
||||||
|
at net.minecraft.server.v1_12_R1.DedicatedServer$2.run(DedicatedServer.java:85)
|
||||||
|
|
||||||
|
"Netty Server IO #0" daemon prio=5 id=34
|
||||||
|
java.lang.Thread.State: RUNNABLE
|
||||||
|
at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(Native Method)
|
||||||
|
at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll(Unknown Source)
|
||||||
|
at sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(Unknown Source)
|
||||||
|
at sun.nio.ch.WindowsSelectorImpl.doSelect(Unknown Source)
|
||||||
|
at sun.nio.ch.SelectorImpl.lockAndDoSelect(Unknown Source)
|
||||||
|
at sun.nio.ch.SelectorImpl.select(Unknown Source)
|
||||||
|
at io.netty.channel.nio.SelectedSelectionKeySetSelector.select(SelectedSelectionKeySetSelector.java:62)
|
||||||
|
at io.netty.channel.nio.NioEventLoop.select(NioEventLoop.java:753)
|
||||||
|
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:409)
|
||||||
|
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884)
|
||||||
|
at java.lang.Thread.run(Unknown Source)
|
||||||
|
...忽略其他线程信息
|
||||||
|
============================== 本次运行日志 ==============================
|
||||||
|
[20:27:18] [Server thread/INFO]: Starting minecraft server version 1.12.2
|
||||||
|
...忽略启动日志
|
||||||
|
[20:27:27] [Server thread/INFO]: [MiaoBugReport] Enabling MiaoBugReport v0.0.1
|
||||||
|
[20:27:28] [Server thread/INFO]: Server permissions file permissions.yml is empty, ignoring it
|
||||||
|
[20:27:28] [Server thread/INFO]: Done (8.205s)! For help, type "help" or "?"
|
||||||
|
[20:27:53] [Craft Scheduler Thread - 0/INFO]: [0;33;22m[[0;36;1mMiaoBugReport[0;33;22m][m [0;32;1m正在生成日志数据...[m
|
||||||
|
[20:27:55] [Craft Scheduler Thread - 0/INFO]: [0;33;22m[[0;36;1mMiaoBugReport[0;33;22m][m [0;32;1m正在上报数据至UbuntuPaste...[m
|
||||||
|
[20:27:55] [Craft Scheduler Thread - 0/INFO]: [0;33;22m[[0;36;1mMiaoBugReport[0;33;22m][m [0;32;1m数据上报完成 您可以分享地址给他人[m
|
||||||
|
============================== 报告结束 ==============================
|
||||||
|
```
|
||||||
|
|
||||||
|
## 下载地址
|
||||||
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "@ccms/plugins",
|
"name": "@ccms/plugins",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript plugins package",
|
"description": "MiaoScript plugins package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -20,16 +20,22 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@javatypes/bukkit-api": "^0.0.3",
|
||||||
|
"@javatypes/bungee-api": "^0.0.3",
|
||||||
|
"@javatypes/sponge-api": "^0.0.3",
|
||||||
"@javatypes/spring-data-redis": "^0.0.3",
|
"@javatypes/spring-data-redis": "^0.0.3",
|
||||||
"@javatypes/spring-web": "^0.0.3",
|
"@javatypes/spring-web": "^0.0.3",
|
||||||
"@javatypes/tomcat": "^0.0.3",
|
"@javatypes/tomcat": "^0.0.3",
|
||||||
|
"@types/crypto-js": "^4.0.1",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@babel/standalone": "^7.13.12",
|
||||||
"@ccms/container": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/plugin": "^0.10.0"
|
"@ccms/container": "^0.14.0",
|
||||||
|
"@ccms/plugin": "^0.14.1",
|
||||||
|
"crypto-js": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,24 @@
|
|||||||
/// <reference types="@javatypes/bungee-api" />
|
/// <reference types="@javatypes/bungee-api" />
|
||||||
/// <reference types="@javatypes/spigot-api" />
|
/// <reference types="@javatypes/bukkit-api" />
|
||||||
/// <reference types="@javatypes/sponge-api" />
|
/// <reference types="@javatypes/sponge-api" />
|
||||||
|
|
||||||
import { server } from '@ccms/api';
|
import { server } from '@ccms/api'
|
||||||
import { inject } from '@ccms/container';
|
import { Autowired } from '@ccms/container'
|
||||||
import { plugin, interfaces, cmd, listener, tab } from '@ccms/plugin'
|
import { Cmd, JSPlugin, Listener, Tab, interfaces } from '@ccms/plugin'
|
||||||
|
|
||||||
@plugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
@JSPlugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
export class HelloWorld extends interfaces.Plugin {
|
export class HelloWorld extends interfaces.Plugin {
|
||||||
@inject(server.Server)
|
@Autowired(server.Server)
|
||||||
private Server: server.Server
|
private Server: server.Server
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
this.logger.log('Plugin load from MiaoScript Plugin System...');
|
this.logger.log('Plugin load from MiaoScript Plugin System...')
|
||||||
}
|
}
|
||||||
enable() {
|
enable() {
|
||||||
this.logger.log('Plugin enable from MiaoScript Plugin System...');
|
this.logger.log('Plugin enable from MiaoScript Plugin System...')
|
||||||
}
|
}
|
||||||
disable() {
|
disable() {
|
||||||
this.logger.log('Plugin disable from MiaoScript Plugin System...');
|
this.logger.log('Plugin disable from MiaoScript Plugin System...')
|
||||||
}
|
}
|
||||||
|
|
||||||
bukkitload() {
|
bukkitload() {
|
||||||
@@ -61,28 +61,29 @@ export class HelloWorld extends interfaces.Plugin {
|
|||||||
this.logger.log('Plugin Disable When ServerType is Nukkit!')
|
this.logger.log('Plugin Disable When ServerType is Nukkit!')
|
||||||
}
|
}
|
||||||
|
|
||||||
@cmd()
|
@Cmd()
|
||||||
hello(sender: any, command: string, args: string[]) {
|
hello(sender: any, command: string, args: string[]) {
|
||||||
this.logger.log(sender, command, args);
|
this.logger.log(sender, command, args)
|
||||||
sender.sendMessage(JSON.stringify({ command, ...args }))
|
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||||
}
|
}
|
||||||
|
|
||||||
@tab()
|
@Tab()
|
||||||
tabhello(_sender: any, _command: string, _args: string[]) {
|
tabhello(_sender: any, _command: string, _args: string[]) {
|
||||||
return ['world']
|
return ['world']
|
||||||
}
|
}
|
||||||
|
|
||||||
@listener({ servers: ['bukkit', 'nukkit'] })
|
@Listener({ servers: ['bukkit', 'nukkit'] })
|
||||||
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||||
let plyaer = event.getPlayer();
|
let plyaer = event.getPlayer()
|
||||||
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
|
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
|
||||||
setTimeout(() => this.sendWelcome(plyaer), 10);
|
setTimeout(() => this.sendWelcome(plyaer), 500)
|
||||||
}
|
}
|
||||||
|
|
||||||
@listener({ servers: ['sponge'] })
|
@Listener({ servers: ['sponge'] })
|
||||||
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
||||||
|
event.getTargetEntity().getLocation()
|
||||||
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
||||||
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 10);
|
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 500)
|
||||||
}
|
}
|
||||||
|
|
||||||
private sendWelcome(player: any) {
|
private sendWelcome(player: any) {
|
||||||
@@ -90,10 +91,9 @@ export class HelloWorld extends interfaces.Plugin {
|
|||||||
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
|
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
@listener({ servers: ['bungee'] })
|
@Listener({ servers: ['bungee'] })
|
||||||
ServerConnected(e: any) {
|
ServerConnected(event: net.md_5.bungee.api.event.ServerConnectedEvent) {
|
||||||
let event = e as net.md_5.bungee.api.event.ServerConnectedEvent
|
|
||||||
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
|
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
|
||||||
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 10);
|
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 500)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
78
packages/plugins/src/McbbsPlugin.ts
Normal file
78
packages/plugins/src/McbbsPlugin.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
/// <reference types="@javatypes/bungee-api" />
|
||||||
|
/// <reference types="@javatypes/bukkit-api" />
|
||||||
|
/// <reference types="@javatypes/sponge-api" />
|
||||||
|
|
||||||
|
import { plugin, server } from '@ccms/api'
|
||||||
|
import { Autowired } from '@ccms/container'
|
||||||
|
import { Cmd, interfaces, JSPlugin, Tab } from '@ccms/plugin'
|
||||||
|
import { Server as SocketIOServer, Socket as SocketIOSocket, Namespace } from '@ccms/websocket'
|
||||||
|
|
||||||
|
import * as fs from '@ccms/common/dist/fs'
|
||||||
|
|
||||||
|
const FileFilter = Java.type('java.io.FileFilter')
|
||||||
|
const ByteArrayInputStream = java.io.ByteArrayInputStream
|
||||||
|
const ByteArrayOutputStream = java.io.ByteArrayOutputStream
|
||||||
|
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets")
|
||||||
|
const GZIPInputStream = Java.type('java.util.zip.GZIPInputStream')
|
||||||
|
const ByteArray = Java.type("byte[]")
|
||||||
|
|
||||||
|
@JSPlugin({ version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
|
export class McbbsPlugin extends interfaces.Plugin {
|
||||||
|
@Autowired()
|
||||||
|
private Server: server.Server
|
||||||
|
@Autowired()
|
||||||
|
private pluginManager: plugin.PluginManager
|
||||||
|
|
||||||
|
private namespace: any
|
||||||
|
|
||||||
|
load() {
|
||||||
|
}
|
||||||
|
|
||||||
|
enable() {
|
||||||
|
let consolePlugin: any = this.pluginManager.getPlugin('MiaoConsole')
|
||||||
|
if (consolePlugin.socketIOServer) {
|
||||||
|
this.startWebSocketServer(consolePlugin.socketIOServer)
|
||||||
|
} else {
|
||||||
|
process.on('websocket.create', (server: SocketIOServer) => {
|
||||||
|
this.startWebSocketServer(server)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private startWebSocketServer(server: SocketIOServer) {
|
||||||
|
this.namespace = server.of('/McbbsPlugin')
|
||||||
|
this.namespace.on('connect', (client: SocketIOSocket) => {
|
||||||
|
this.initWebSocketClient(client)
|
||||||
|
this.logger.console(`§6客户端 §b${client.id} §a新建连接...`)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
disable() {
|
||||||
|
this.namespace.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
private initWebSocketClient(client: SocketIOSocket) {
|
||||||
|
client.on('ungzip', (content) => {
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
client.on('error', (error) => {
|
||||||
|
this.logger.console(`§6客户端 §b${client.id} §c触发异常: ${error}`)
|
||||||
|
this.logger.error(error)
|
||||||
|
})
|
||||||
|
client.on('disconnect', () => {
|
||||||
|
this.logger.console(`§6客户端 §b${client.id} §c断开连接...`)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
@Cmd()
|
||||||
|
msme(sender: any, command: string, args: string[]) {
|
||||||
|
this.logger.log(sender, command, args)
|
||||||
|
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Tab()
|
||||||
|
tabmsme(_sender: any, _command: string, _args: string[]) {
|
||||||
|
return ['world']
|
||||||
|
}
|
||||||
|
}
|
||||||
48
packages/plugins/src/MiaoAuth.ts
Normal file
48
packages/plugins/src/MiaoAuth.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
/// <reference types="@javatypes/bungee-api" />
|
||||||
|
/// <reference types="@javatypes/bukkit-api" />
|
||||||
|
/// <reference types="@javatypes/sponge-api" />
|
||||||
|
|
||||||
|
import { plugin, server } from '@ccms/api'
|
||||||
|
import { Autowired } from '@ccms/container'
|
||||||
|
import { Cmd, interfaces, JSPlugin, Tab } from '@ccms/plugin'
|
||||||
|
|
||||||
|
import type { MiaoReward } from './MiaoReward'
|
||||||
|
import * as fs from '@ccms/common/dist/fs'
|
||||||
|
|
||||||
|
@JSPlugin({ version: '1.0.0', author: 'MiaoWoo', source: __filename, depends: ['MiaoReward'] })
|
||||||
|
export class MiaoAuth extends interfaces.Plugin {
|
||||||
|
@Autowired()
|
||||||
|
private Server: server.Server
|
||||||
|
@Autowired()
|
||||||
|
private pluginManager: plugin.PluginManager
|
||||||
|
|
||||||
|
private MiaoReward: MiaoReward
|
||||||
|
|
||||||
|
load() {
|
||||||
|
}
|
||||||
|
|
||||||
|
enable() {
|
||||||
|
this.MiaoReward = this.pluginManager.getPlugin('MiaoReward') as MiaoReward
|
||||||
|
if (!this.MiaoReward) { return this.logger.error('当前脚本插件需要 MiaoReward 作为前置插件!') }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
disable() {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Cmd({ autoMain: true })
|
||||||
|
msma() { }
|
||||||
|
|
||||||
|
cmdbind(sender: org.bukkit.entity.Player) {
|
||||||
|
if (!sender.getItemInHand) { return this.logger.sender(sender, '§4控制台无法执行此命令!') }
|
||||||
|
if (!this.MiaoReward.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置 请联系管理员配置MiaoReward!') }
|
||||||
|
this.MiaoReward.scanAuth(sender, 'bind', { title: '账号绑定', content: '是否绑定' }, (token, user) => {
|
||||||
|
|
||||||
|
}, () => {
|
||||||
|
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
@Tab()
|
||||||
|
tabmsma() { }
|
||||||
|
}
|
||||||
@@ -50,7 +50,7 @@ class MiaoMessage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@plugin({ name: 'MiaoChat', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
@plugin({ version: '1.0.1', author: 'MiaoWoo', source: __filename })
|
||||||
export class MiaoChat extends interfaces.Plugin {
|
export class MiaoChat extends interfaces.Plugin {
|
||||||
@Autowired()
|
@Autowired()
|
||||||
private Server: server.Server
|
private Server: server.Server
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
/// <reference types="@ccms/nashorn" />
|
||||||
|
|
||||||
import { plugin as pluginApi, server, task, constants, command } from '@ccms/api'
|
import { plugin as pluginApi, server, task, constants, command } from '@ccms/api'
|
||||||
import { plugin, interfaces, cmd, tab, enable, config, disable } from '@ccms/plugin'
|
import { plugin, interfaces, cmd, tab, enable, config, disable, PluginConfig } from '@ccms/plugin'
|
||||||
import { inject, ContainerInstance, Container } from '@ccms/container'
|
import { ContainerInstance, Container, Autowired } from '@ccms/container'
|
||||||
import io, { Server as SocketIOServer, Socket as SocketIOSocket } from '@ccms/websocket'
|
import io, { Server as SocketIOServer, Socket as SocketIOSocket } from '@ccms/websocket'
|
||||||
import * as fs from '@ccms/common/dist/fs'
|
import * as fs from '@ccms/common/dist/fs'
|
||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
@@ -19,22 +19,22 @@ let help = [
|
|||||||
'§6/mconsole §areload §6- §3重载插件',
|
'§6/mconsole §areload §6- §3重载插件',
|
||||||
]
|
]
|
||||||
|
|
||||||
@plugin({ name: 'MiaoConsole', prefix: 'Console', version: '1.0.0', author: 'MiaoWoo', servers: ['!nukkit'], source: __filename })
|
@plugin({ prefix: 'Console', version: '1.1.1', author: 'MiaoWoo', servers: ['!nukkit'], source: __filename })
|
||||||
export class MiaoConsole extends interfaces.Plugin {
|
export class MiaoConsole extends interfaces.Plugin {
|
||||||
@inject(ContainerInstance)
|
@Autowired(ContainerInstance)
|
||||||
private container: Container
|
private container: Container
|
||||||
@inject(server.ServerType)
|
@Autowired(server.ServerType)
|
||||||
private serverType: string
|
private serverType: string
|
||||||
@inject(server.Server)
|
@Autowired(pluginApi.PluginFolder)
|
||||||
private server: server.Server
|
|
||||||
@inject(command.Command)
|
|
||||||
private command: command.Command
|
|
||||||
@inject(task.TaskManager)
|
|
||||||
private task: task.TaskManager
|
|
||||||
@inject(pluginApi.PluginManager)
|
|
||||||
private pluginManager: pluginApi.PluginManager
|
|
||||||
@inject(pluginApi.PluginFolder)
|
|
||||||
private pluginFolder: string
|
private pluginFolder: string
|
||||||
|
@Autowired()
|
||||||
|
private server: server.Server
|
||||||
|
@Autowired()
|
||||||
|
private command: command.Command
|
||||||
|
@Autowired()
|
||||||
|
private task: task.TaskManager
|
||||||
|
@Autowired()
|
||||||
|
private pluginManager: pluginApi.PluginManager
|
||||||
|
|
||||||
private token: string
|
private token: string
|
||||||
private instance: any
|
private instance: any
|
||||||
@@ -42,11 +42,13 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
private rootLogger: any
|
private rootLogger: any
|
||||||
private appender: any
|
private appender: any
|
||||||
private handler: any
|
private handler: any
|
||||||
|
private babel: any
|
||||||
|
private downgrade = true
|
||||||
|
|
||||||
private logCache: string[] = []
|
private logCache: string[] = []
|
||||||
|
|
||||||
@config()
|
@config()
|
||||||
private secret = { token: undefined }
|
private secret: PluginConfig = { token: undefined }
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
if (this.secret.token) {
|
if (this.secret.token) {
|
||||||
@@ -58,10 +60,25 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
process.on('message', (msg) => {
|
process.on('message', (msg) => {
|
||||||
this.logCache.push(msg)
|
this.logCache.push(msg)
|
||||||
if (this.logCache.length > 30) {
|
if (this.logCache.length > 100) {
|
||||||
this.logCache = this.logCache.slice(this.logCache.length - 30, this.logCache.length)
|
this.logCache = this.logCache.slice(this.logCache.length - 100, this.logCache.length)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
this.task.create(() => {
|
||||||
|
if (!this.babel) {
|
||||||
|
try {
|
||||||
|
this.logger.console('§3脚本 Babel 引擎初始化中 请稍候...')
|
||||||
|
let startTime = Date.now()
|
||||||
|
this.babel = require('@babel/standalone')
|
||||||
|
this.compileCode(`() => console.log("Babel ready!")`)
|
||||||
|
this.logger.console(`§3脚本 Babel 引擎初始化完毕 耗时 §a${Date.now() - startTime}ms...`)
|
||||||
|
this.downgrade = false
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.console(`§c脚本 Babel 引擎初始化失败 将无法使用ES5以上语法!`)
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}).async().submit()
|
||||||
}
|
}
|
||||||
|
|
||||||
@cmd()
|
@cmd()
|
||||||
@@ -81,8 +98,6 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cmdreload(sender: any) {
|
cmdreload(sender: any) {
|
||||||
// @ts-ignore
|
|
||||||
require.clear('websocket')
|
|
||||||
this.pluginManager.reload(this)
|
this.pluginManager.reload(this)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -90,6 +105,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
cmdtoken(sender: any, sub: string, token: string) {
|
cmdtoken(sender: any, sub: string, token: string) {
|
||||||
if (sub == "set") {
|
if (sub == "set") {
|
||||||
this.secret.token = this.token = token
|
this.secret.token = this.token = token
|
||||||
|
this.secret.save()
|
||||||
this.logger.sender(sender, '§a已保存§6服务器登录Token:§3', this.token, '§4请勿分享给其他人 防止服务器被攻击!')
|
this.logger.sender(sender, '§a已保存§6服务器登录Token:§3', this.token, '§4请勿分享给其他人 防止服务器被攻击!')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -216,28 +232,28 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
root: fs.concat(root, 'wwwroot')
|
root: fs.concat(root, 'wwwroot')
|
||||||
})
|
})
|
||||||
this.container.bind(io.Instance).toConstantValue(this.socketIOServer)
|
this.container.bind(io.Instance).toConstantValue(this.socketIOServer)
|
||||||
|
process.emit('websocket.create', this.socketIOServer)
|
||||||
}
|
}
|
||||||
|
|
||||||
startSocketIOServer() {
|
startSocketIOServer() {
|
||||||
let namespace = this.socketIOServer.of('/MiaoConsole')
|
let namespace = this.socketIOServer.of('/MiaoConsole')
|
||||||
process.on('message', (msg) => namespace.emit('log', msg))
|
process.on('message', (msg) => namespace.emit('log', msg))
|
||||||
namespace.on('connect', (client: SocketIOSocket) => {
|
namespace.on('connection', (client: SocketIOSocket) => {
|
||||||
if (!this.token) {
|
if (!this.token) {
|
||||||
this.logger.console(`§6客户端 §b${client.id} §a请求连接 §4服务器尚未设置 Token 无法连接!`)
|
this.logger.console(`§6客户端 §b${client.id} §a请求连接 §4服务器尚未设置 Token 无法连接!`)
|
||||||
client.emit('unauthorized')
|
client.emit('unauthorized', () => client.disconnect(true))
|
||||||
client.disconnect(true)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (this.token != client.handshake.query.token) {
|
if (this.token != client.handshake.query.token) {
|
||||||
this.logger.console(`§6客户端 §b${client.id} §c无效请求 §4请提供正确Token后再次连接!`)
|
this.logger.console(`§6客户端 §b${client.id} §c无效请求 §4请提供正确Token后再次连接!`)
|
||||||
client.emit('unauthorized')
|
client.emit('unauthorized', () => client.disconnect(true))
|
||||||
client.disconnect(true)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
this.initWebSocketClient(client)
|
this.initWebSocketClient(client)
|
||||||
this.logCache.forEach(msg => client.emit('log', msg))
|
this.logCache.forEach(msg => client.emit('log', msg))
|
||||||
this.logger.console(`§6客户端 §b${client.id} §a新建连接 ${this.rootLogger ? '启动日志转发' : '§4转发日志启动失败'}...`)
|
this.logger.console(`§6客户端 §b${client.id} §a新建连接 ${this.rootLogger ? '启动日志转发' : '§4转发日志启动失败'}...`)
|
||||||
})
|
})
|
||||||
|
process.emit('websocket.start', this.socketIOServer)
|
||||||
}
|
}
|
||||||
|
|
||||||
private initWebSocketClient(client: SocketIOSocket) {
|
private initWebSocketClient(client: SocketIOSocket) {
|
||||||
@@ -246,14 +262,23 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
client.emit('log', `Currect Server Version is ${this.server.getVersion()}`)
|
client.emit('log', `Currect Server Version is ${this.server.getVersion()}`)
|
||||||
})
|
})
|
||||||
client.on('command', (cmd) => {
|
client.on('command', (cmd) => {
|
||||||
setTimeout(() => this.server.dispatchConsoleCommand(cmd), 0)
|
this.task.callSyncMethod(() => this.server.dispatchConsoleCommand(cmd))
|
||||||
client.emit('log', `§6命令: §b${cmd} §a执行成功!`)
|
client.emit('log', `§6命令: §b${cmd} §a执行成功!`)
|
||||||
})
|
})
|
||||||
client.on('tabComplate', (input, index, callback) => {
|
client.on('tabComplate', (input, index, callback) => {
|
||||||
|
try {
|
||||||
callback?.(this.command.tabComplete(this.server.getConsoleSender(), input, index) || [])
|
callback?.(this.command.tabComplete(this.server.getConsoleSender(), input, index) || [])
|
||||||
|
} catch (error) {
|
||||||
|
callback?.([])
|
||||||
|
client.emit('log', `§4命令补全发生异常: ${error}!`)
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
client.on('exec', (code) => {
|
client.on('exec', (code) => {
|
||||||
try {
|
try {
|
||||||
|
if (!this.babel) {
|
||||||
|
return client.emit('log', '§cBabel 引擎初始化中 请稍候再试!')
|
||||||
|
}
|
||||||
client.emit('log', this.runCode(code, client.nsp, client))
|
client.emit('log', this.runCode(code, client.nsp, client))
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
client.emit('log', `§4代码执行异常 错误: ${ex}\n${console.stack(ex).join('\n')}`)
|
client.emit('log', `§4代码执行异常 错误: ${ex}\n${console.stack(ex).join('\n')}`)
|
||||||
@@ -280,7 +305,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
if (!dir.isDirectory()) {
|
if (!dir.isDirectory()) {
|
||||||
return fn(undefined, `${file} 不是一个目录!`)
|
return fn(undefined, `${file} 不是一个目录!`)
|
||||||
}
|
}
|
||||||
fn(fs.list(dir))
|
fn(fs.list(dir).map(f => f.name))
|
||||||
})
|
})
|
||||||
client.on('error', (error) => {
|
client.on('error', (error) => {
|
||||||
this.logger.console(`§6客户端 §b${client.id} §c触发异常: ${error}`)
|
this.logger.console(`§6客户端 §b${client.id} §c触发异常: ${error}`)
|
||||||
@@ -306,15 +331,33 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
this.container,
|
this.container,
|
||||||
this.pluginManager
|
this.pluginManager
|
||||||
]
|
]
|
||||||
let tfunc = new Function(
|
client.emit('log', '§3代码编译中 请稍候...')
|
||||||
...paramNames,
|
let startTime = Date.now()
|
||||||
`var api = require('@ccms/api');
|
let tfunc = new Function(...paramNames, this.compileCode(code))
|
||||||
|
client.emit('log', `§3代码编译完成 耗时 §e${Date.now() - startTime}ms §b开始执行 请稍候...`)
|
||||||
|
return tfunc.apply(this, params) + ''
|
||||||
|
}
|
||||||
|
|
||||||
|
private compileCode(code: string) {
|
||||||
|
if (!this.downgrade && this.babel?.transform) {
|
||||||
|
code = this.babel.transform(code, {
|
||||||
|
filename: 'miaoconsole-temp.ts',
|
||||||
|
presets: ['typescript', 'es2015'],
|
||||||
|
plugins: [
|
||||||
|
['proposal-decorators', { legacy: true }],
|
||||||
|
'transform-runtime'
|
||||||
|
],
|
||||||
|
sourceMaps: "inline"
|
||||||
|
}).code
|
||||||
|
}
|
||||||
|
return `var api = require('@ccms/api');
|
||||||
if (this.serverType == "spring") {
|
if (this.serverType == "spring") {
|
||||||
var dbm = container.get(api.database.DataBaseManager)
|
var dbm = container.get(api.database.DataBaseManager)
|
||||||
var db = dbm.getMainDatabase()
|
var db = dbm.getMainDatabase()
|
||||||
var bf = base.getInstance().getAutowireCapableBeanFactory()
|
var bf = base.getInstance().getAutowireCapableBeanFactory()
|
||||||
}
|
}
|
||||||
return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
var startTime = Date.now()
|
||||||
return this.task.callSyncMethod(() => tfunc.apply(this, params)) + ''
|
var result = eval(${JSON.stringify(code)});
|
||||||
|
return '§3代码执行完成 耗时 §e' + (Date.now() - startTime) + 'ms §a返回结果: §r'+ result`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
175
packages/plugins/src/MiaoExplorer.ts
Normal file
175
packages/plugins/src/MiaoExplorer.ts
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
/// <reference types="@javatypes/bungee-api" />
|
||||||
|
/// <reference types="@javatypes/bukkit-api" />
|
||||||
|
/// <reference types="@javatypes/sponge-api" />
|
||||||
|
|
||||||
|
import { plugin, server } from '@ccms/api'
|
||||||
|
import { Autowired } from '@ccms/container'
|
||||||
|
import { Cmd, interfaces, JSPlugin, Tab } from '@ccms/plugin'
|
||||||
|
import { Server as SocketIOServer, Socket as SocketIOSocket, Namespace } from '@ccms/websocket'
|
||||||
|
|
||||||
|
import * as fs from '@ccms/common/dist/fs'
|
||||||
|
|
||||||
|
const FileFilter = Java.type('java.io.FileFilter')
|
||||||
|
const ByteArrayInputStream = java.io.ByteArrayInputStream
|
||||||
|
const ByteArrayOutputStream = java.io.ByteArrayOutputStream
|
||||||
|
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets")
|
||||||
|
const GZIPInputStream = Java.type('java.util.zip.GZIPInputStream')
|
||||||
|
const ByteArray = Java.type("byte[]")
|
||||||
|
|
||||||
|
@JSPlugin({ prefix: 'Explorer', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
|
export class MiaoExplorer extends interfaces.Plugin {
|
||||||
|
@Autowired()
|
||||||
|
private Server: server.Server
|
||||||
|
@Autowired()
|
||||||
|
private pluginManager: plugin.PluginManager
|
||||||
|
|
||||||
|
private token: string
|
||||||
|
private namespace: any
|
||||||
|
private chunkCacheMap: Map<string, Array<string>>
|
||||||
|
|
||||||
|
load() {
|
||||||
|
this.chunkCacheMap = new Map()
|
||||||
|
}
|
||||||
|
|
||||||
|
enable() {
|
||||||
|
let consolePlugin: any = this.pluginManager.getPlugin('MiaoConsole')
|
||||||
|
if (consolePlugin.socketIOServer) {
|
||||||
|
this.startWebSocketServer(consolePlugin.socketIOServer)
|
||||||
|
} else {
|
||||||
|
process.on('websocket.create', (server: SocketIOServer) => {
|
||||||
|
this.startWebSocketServer(server)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private startWebSocketServer(server: SocketIOServer) {
|
||||||
|
let consolePlugin: any = this.pluginManager.getPlugin('MiaoConsole')
|
||||||
|
this.token = consolePlugin.token
|
||||||
|
this.namespace = server.of('/MiaoExplorer')
|
||||||
|
this.namespace.on('connection', (client: SocketIOSocket) => {
|
||||||
|
if (!this.token) {
|
||||||
|
this.logger.console(`§6客户端 §b${client.id} §a请求连接 §4服务器尚未设置 Token 无法连接!`)
|
||||||
|
client.emit('unauthorized', () => client.disconnect(true))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (this.token != client.handshake.query.token) {
|
||||||
|
this.logger.console(`§6客户端 §b${client.id} §c无效请求 §4请提供正确Token后再次连接!`)
|
||||||
|
client.emit('unauthorized', () => client.disconnect(true))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.initWebSocketClient(client)
|
||||||
|
this.logger.console(`§6客户端 §b${client.id} §a新建连接...`)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
disable() {
|
||||||
|
this.namespace.removeAllListeners('connect')
|
||||||
|
this.namespace.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
private readDir(dir) {
|
||||||
|
let children = Java.from(dir.listFiles(new FileFilter({
|
||||||
|
accept: file => file.getName().endsWith('.yml') || file.isDirectory()
|
||||||
|
}))).sort().map(file => {
|
||||||
|
if (file.isDirectory()) {
|
||||||
|
let children = this.readDir(file)
|
||||||
|
if (!children.length) { return null }
|
||||||
|
return {
|
||||||
|
label: file.getName(),
|
||||||
|
value: fs.path(file),
|
||||||
|
children,
|
||||||
|
disabled: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
label: file.getName(),
|
||||||
|
value: fs.path(file),
|
||||||
|
creatable: true,
|
||||||
|
editable: true,
|
||||||
|
removable: true,
|
||||||
|
deleteApi: "delete"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return children.filter(s => s)
|
||||||
|
}
|
||||||
|
|
||||||
|
private initWebSocketClient(client: SocketIOSocket) {
|
||||||
|
client.on('ls', (fn) => {
|
||||||
|
var pluginDirs = Java.from(fs.file('./plugins').listFiles(new FileFilter({
|
||||||
|
accept: dirs => dirs.isDirectory()
|
||||||
|
})))
|
||||||
|
let result = {
|
||||||
|
options: pluginDirs.sort().map(f => {
|
||||||
|
let node: any = {
|
||||||
|
label: f.getName(),
|
||||||
|
value: fs.path(f)
|
||||||
|
}
|
||||||
|
let children = this.readDir(f)
|
||||||
|
if (!children.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
node.children = children
|
||||||
|
node.disabled = true
|
||||||
|
return node
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn && fn(result.options.filter(s => s))
|
||||||
|
})
|
||||||
|
client.on('read', (file, callback) => {
|
||||||
|
callback?.(base.read(file))
|
||||||
|
})
|
||||||
|
client.on('chunk', (file, index, content, callback) => {
|
||||||
|
if (!this.chunkCacheMap.has(file)) {
|
||||||
|
this.chunkCacheMap.set(file, [])
|
||||||
|
}
|
||||||
|
this.chunkCacheMap.get(file)[index] = content
|
||||||
|
callback?.(true)
|
||||||
|
})
|
||||||
|
client.on('ungzip', (content) => {
|
||||||
|
try {
|
||||||
|
console.log(content)
|
||||||
|
let baos = new ByteArrayOutputStream()
|
||||||
|
let byte = java.util.Base64.getDecoder().decode(content)
|
||||||
|
let gzip = new GZIPInputStream(new ByteArrayInputStream(byte))
|
||||||
|
let buffer = new ByteArray(1024)
|
||||||
|
let n: number
|
||||||
|
while ((n = gzip.read(buffer)) != -1) {
|
||||||
|
baos.write(buffer, 0, n)
|
||||||
|
}
|
||||||
|
gzip.close()
|
||||||
|
baos.close()
|
||||||
|
content = baos.toString(StandardCharsets.UTF_8.name())
|
||||||
|
this.logger.log(content)
|
||||||
|
} catch (error) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
client.on('save', (file, callback) => {
|
||||||
|
if (!this.chunkCacheMap.has(file)) {
|
||||||
|
return callback?.(false)
|
||||||
|
}
|
||||||
|
let content = this.chunkCacheMap.get(file).join('')
|
||||||
|
this.chunkCacheMap.delete(file)
|
||||||
|
base.save(file, content)
|
||||||
|
callback?.(true)
|
||||||
|
})
|
||||||
|
client.on('error', (error) => {
|
||||||
|
this.logger.console(`§6客户端 §b${client.id} §c触发异常: ${error}`)
|
||||||
|
this.logger.error(error)
|
||||||
|
})
|
||||||
|
client.on('disconnect', () => {
|
||||||
|
this.logger.console(`§6客户端 §b${client.id} §c断开连接...`)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
@Cmd()
|
||||||
|
msme(sender: any, command: string, args: string[]) {
|
||||||
|
this.logger.log(sender, command, args)
|
||||||
|
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Tab()
|
||||||
|
tabmsme(_sender: any, _command: string, _args: string[]) {
|
||||||
|
return ['world']
|
||||||
|
}
|
||||||
|
}
|
||||||
36
packages/plugins/src/MiaoParticle.ts
Normal file
36
packages/plugins/src/MiaoParticle.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
/// <reference types="@javatypes/bungee-api" />
|
||||||
|
/// <reference types="@javatypes/bukkit-api" />
|
||||||
|
/// <reference types="@javatypes/sponge-api" />
|
||||||
|
|
||||||
|
import { particle } from '@ccms/api'
|
||||||
|
import { Autowired } from '@ccms/container'
|
||||||
|
import { Cmd, JSPlugin, Tab, interfaces } from '@ccms/plugin'
|
||||||
|
|
||||||
|
@JSPlugin({ version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
|
export class MiaoParticle extends interfaces.Plugin {
|
||||||
|
@Autowired()
|
||||||
|
private particleManager: particle.ParticleManager
|
||||||
|
|
||||||
|
private particleTask: particle.ParticleTask
|
||||||
|
|
||||||
|
enable() {
|
||||||
|
// let boot = new Bootstrap()
|
||||||
|
this.particleTask = this.particleManager.create(new particle.Circle(2, 20).setParticle(org.bukkit.Particle.BLOCK_DUST), this)
|
||||||
|
}
|
||||||
|
|
||||||
|
diable() {
|
||||||
|
this.particleTask.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Cmd({ autoMain: true })
|
||||||
|
mpt() { }
|
||||||
|
|
||||||
|
cmdtest(sender: org.bukkit.entity.Player) {
|
||||||
|
this.particleTask.follow(sender).async(true).timer(5).submit()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Tab()
|
||||||
|
tabmpt(_sender: any, _command: string, _args: string[]) {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
406
packages/plugins/src/MiaoPay.ts
Normal file
406
packages/plugins/src/MiaoPay.ts
Normal file
@@ -0,0 +1,406 @@
|
|||||||
|
/// <reference types="@javatypes/bungee-api" />
|
||||||
|
/// <reference types="@javatypes/bukkit-api" />
|
||||||
|
/// <reference types="@javatypes/sponge-api" />
|
||||||
|
|
||||||
|
import { plugin, server, task } from '@ccms/api'
|
||||||
|
import { Autowired, JSClass } from '@ccms/container'
|
||||||
|
import { Cmd, Config, interfaces, JSPlugin, Listener, PluginConfig, Tab } from '@ccms/plugin'
|
||||||
|
|
||||||
|
import type { MiaoReward } from './MiaoReward'
|
||||||
|
import http from '@ccms/common/dist/http'
|
||||||
|
import * as CryptoJS from "crypto-js"
|
||||||
|
|
||||||
|
const Thread = java.lang.Thread
|
||||||
|
|
||||||
|
interface PlayerPointsAPI {
|
||||||
|
look(name: string)
|
||||||
|
give(name: string, amount: number)
|
||||||
|
take(name: string, amount: number)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Order {
|
||||||
|
order_id: string
|
||||||
|
amount: number
|
||||||
|
url?: string
|
||||||
|
}
|
||||||
|
interface Sync {
|
||||||
|
scaned: boolean
|
||||||
|
start?: number
|
||||||
|
left?: number
|
||||||
|
cancelled?: boolean
|
||||||
|
paying?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PlaceholderAPI {
|
||||||
|
registerPlaceholderHook: (key: string, onPlaceholderRequest: (player, s) => string) => void
|
||||||
|
unregisterPlaceholderHook: (key: string) => void
|
||||||
|
setPlaceholders: (player: any, str: string) => string
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultConfig = {
|
||||||
|
prefix: '§6[§b喵式支付§6]',
|
||||||
|
name: '',
|
||||||
|
id: '',
|
||||||
|
secret: '',
|
||||||
|
command: 'points give %player_name% %amount%',
|
||||||
|
check: '%playerpoints_points%',
|
||||||
|
ratio: 100,
|
||||||
|
coinName: '点券',
|
||||||
|
reward: {
|
||||||
|
'*': [
|
||||||
|
'msg %player_name% 充值 %amount% 点券成功...'
|
||||||
|
],
|
||||||
|
10: [
|
||||||
|
"points give %player_name% 1",
|
||||||
|
'msg %player_name% 充值 10 点券 奖励 1 点券...'
|
||||||
|
],
|
||||||
|
300: [
|
||||||
|
"points give %player_name% 15",
|
||||||
|
'msg %player_name% 充值 300 点券 奖励 15 点券...'
|
||||||
|
],
|
||||||
|
500: [
|
||||||
|
"points give %player_name% 25",
|
||||||
|
'msg %player_name% 充值 500 点券 奖励 25 点券...'
|
||||||
|
],
|
||||||
|
680: [
|
||||||
|
"points give %player_name% 35",
|
||||||
|
'msg %player_name% 充值 680 点券 奖励 35 点券...'
|
||||||
|
],
|
||||||
|
1280: [
|
||||||
|
"points give %player_name% 70",
|
||||||
|
'msg %player_name% 充值 1280 点券 奖励 70 点券...'
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JSPlugin({ version: '1.3.5', author: 'MiaoWoo', source: __filename, depends: ['MiaoReward'], nativeDepends: ['PlaceholderAPI'] })
|
||||||
|
export class MiaoPay extends interfaces.Plugin {
|
||||||
|
@Autowired()
|
||||||
|
private server: server.Server
|
||||||
|
@Autowired()
|
||||||
|
private taskManager: task.TaskManager
|
||||||
|
@Autowired()
|
||||||
|
private pluginManager: plugin.PluginManager
|
||||||
|
|
||||||
|
@JSClass('me.clip.placeholderapi.PlaceholderAPI')
|
||||||
|
private PlaceholderAPI: PlaceholderAPI
|
||||||
|
|
||||||
|
private apiGateWay = "https://pay.yumc.pw"
|
||||||
|
private MiaoReward: MiaoReward
|
||||||
|
|
||||||
|
private cacheMap = new Map<string, Order>();
|
||||||
|
private cacheSyncMap = new Map<string, Sync>();
|
||||||
|
|
||||||
|
@Config()
|
||||||
|
private config: PluginConfig & typeof defaultConfig = defaultConfig
|
||||||
|
|
||||||
|
load() {
|
||||||
|
let needSave = false
|
||||||
|
for (const key of Object.keys(defaultConfig)) {
|
||||||
|
if (!this.config[key]) {
|
||||||
|
this.config[key] = defaultConfig[key]
|
||||||
|
needSave = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
needSave && this.config.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
enable() {
|
||||||
|
this.MiaoReward = this.pluginManager.getPlugin('MiaoReward') as MiaoReward
|
||||||
|
if (!this.MiaoReward) { return this.logger.error('当前脚本插件需要 MiaoReward 作为前置脚本插件!') }
|
||||||
|
if (!this.config.id || !this.config.secret) { return this.logger.console('§4尚未配置商户信息 将无法正常收款!') }
|
||||||
|
}
|
||||||
|
|
||||||
|
disable() {
|
||||||
|
this.cacheMap.forEach((v, k) => {
|
||||||
|
this.MiaoReward.cancelTask(this.server.getPlayer(k))
|
||||||
|
})
|
||||||
|
this.cacheMap.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Cmd({ autoMain: true })
|
||||||
|
mpay() { }
|
||||||
|
|
||||||
|
cmdpay(sender: org.bukkit.entity.Player, amount: number = 0) {
|
||||||
|
if (!sender.getItemInHand) { return this.logger.sender(sender, '§4控制台无法执行此命令!') }
|
||||||
|
if (!this.MiaoReward.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置 请联系管理员先配置MiaoReward!') }
|
||||||
|
if (!this.config.id || !this.config.secret) { return this.logger.sender(sender, '§c当前服务器尚未配置 请联系管理员配置支付密钥!') }
|
||||||
|
if (this.cacheMap.has(sender.getName())) {
|
||||||
|
this.logger.sender(sender, '§c您有一笔订单尚未完成 请完成支付或等待订单超时!')
|
||||||
|
let sync = this.cacheSyncMap.get(sender.getName())
|
||||||
|
if (!sync.cancelled) { return }
|
||||||
|
sync.scaned = false
|
||||||
|
sync.left = (sync.paying ? 100 : 55) - (Math.round(Date.now() / 1000) - sync.start)
|
||||||
|
let order = this.cacheMap.get(sender.getName())
|
||||||
|
this.MiaoReward.setItemAndTp(sender, order.url, sync, `充值 ${this.config.ratio * order.amount} ${this.config.coinName}`, `支付宝/微信/QQ 扫码支付`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (amount < 1) { return this.logger.sender(sender, `§c充值异常 §4充值金额不得小于 1 ${this.config.coinName}!`) }
|
||||||
|
if (amount / this.config.ratio > 1000) { return this.logger.sender(sender, `§c充值异常 §4充值金额不得大于 ${this.config.ratio * 1000} ${this.config.coinName}!`) }
|
||||||
|
if (amount != Math.round(amount)) { return this.logger.sender(sender, `§c充值异常 §4充值金额必须为整数!`) }
|
||||||
|
try {
|
||||||
|
this.getPlayerAmount(sender)
|
||||||
|
} catch (error) {
|
||||||
|
return this.logger.sender(sender, error.message || error)
|
||||||
|
}
|
||||||
|
this.MiaoReward.sendTitle(sender, `§6充值 §a${amount} §6${this.config.coinName}`, '§c正在请求充值二维码 请稍候...')
|
||||||
|
let sync: any = { scaned: false, start: Math.round(Date.now() / 1000) }
|
||||||
|
let order = this.createOrder(sender, amount)
|
||||||
|
this.cacheMap.set(sender.getName(), order)
|
||||||
|
this.cacheSyncMap.set(sender.getName(), sync)
|
||||||
|
let order_id = order.order_id
|
||||||
|
this.MiaoReward.setItemAndTp(sender, order.url, sync, `充值 ${amount} ${this.config.coinName}`, `支付宝/微信/QQ 扫码支付`)
|
||||||
|
this.logger.sender(sender, [`§3请使用 §b支付宝§3/§a微信§3/§5QQ §3扫描二维码支付!`, `§c如未显示二维码 请打开下列网址完成充值!`, `§6地址: §3${order.url}`])
|
||||||
|
this.taskManager.create(() => {
|
||||||
|
try {
|
||||||
|
let status = this.queryStatus(order_id, 0, 55)
|
||||||
|
if (status.code != 200) { throw new Error('§c扫码超时 请重新充值!') }
|
||||||
|
this.MiaoReward.sendTitle(sender, '§a已扫码', `§3订单已创建 请及时支付!`)
|
||||||
|
this.MiaoReward.sendActionBar(sender, '§6订单号: §3' + order_id)
|
||||||
|
sync.scaned = true
|
||||||
|
sync.start = Math.round(Date.now() / 1000)
|
||||||
|
sync.paying = true
|
||||||
|
status = this.queryStatus(order_id, 1, 100)
|
||||||
|
if (status.code != 200) { throw new Error('§c支付超时 请重新充值!') }
|
||||||
|
if (status.data == 2) {
|
||||||
|
this.MiaoReward.sendTitle(sender, '§a已支付', `§3订单已支付 请等待充值到账...`)
|
||||||
|
this.MiaoReward.sendActionBar(sender, '§6订单号: §3' + order_id)
|
||||||
|
this.logger.sender(sender, `§6订单号: §3${order_id} §a支付成功!`)
|
||||||
|
this.recharge(sender, order)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
let cacheOrder = this.cacheMap.get(sender.getName())
|
||||||
|
if (cacheOrder && cacheOrder.order_id == order_id) {
|
||||||
|
this.MiaoReward.sendTitle(sender, '§4充值失败', error.message)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
sync.scaned = true
|
||||||
|
this.cacheMap.delete(sender.getName())
|
||||||
|
this.cacheSyncMap.delete(sender.getName())
|
||||||
|
}
|
||||||
|
}).async().submit()
|
||||||
|
this.MiaoReward.clearTitle(sender)
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdquery(sender: org.bukkit.entity.Player, id: string) {
|
||||||
|
if (!id) { return this.logger.sender(sender, '§c请输入订单号!') }
|
||||||
|
this.taskManager.create(() => {
|
||||||
|
let result = this.queryOrder(id, sender.getName(), sender.getUniqueId().toString())
|
||||||
|
if (result.code != 200) { return this.logger.sender(sender, `§c查询异常! §4ERROR: ${result.msg}`) }
|
||||||
|
let order = result.data
|
||||||
|
this.logger.sender(sender, [
|
||||||
|
`§6商户名称: §3${order.appname}`,
|
||||||
|
`§6订单号: §3${id}`,
|
||||||
|
`§6商品: §b${order.subject}`,
|
||||||
|
`§6金额: §e${order.amount}`,
|
||||||
|
`§6玩家: §a${order.username}`,
|
||||||
|
`§6状态: §c${order.status}`,
|
||||||
|
])
|
||||||
|
if (order.status > 1 && order.status < 4) {
|
||||||
|
this.logger.sender(sender, `§3当前订单已支付 尚未完成充值 开始补单操作...`)
|
||||||
|
this.recharge(sender, order)
|
||||||
|
}
|
||||||
|
}).async().submit()
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdcheck(sender: org.bukkit.entity.Player, force = 1) {
|
||||||
|
this.logger.sender(sender, `§3正在检查需要补单充值的订单 请稍候...`)
|
||||||
|
this.taskManager.create(() => {
|
||||||
|
let result = this.queryUnconverted(sender.getName(), force)
|
||||||
|
if (result.code != 200) { return this.logger.sender(sender, `§c订单查询失败: ${result.msg}`) }
|
||||||
|
let unconverteds = result.data
|
||||||
|
if (!unconverteds.length) { return this.logger.sender(sender, `§c未发现需要进行补单充值的订单!`) }
|
||||||
|
this.logger.sender(sender, `§3发现 §a${unconverteds.length}笔 §3未充值订单 §c正在充值 请稍候...`)
|
||||||
|
for (const unconverted of unconverteds) {
|
||||||
|
this.logger.sender(sender, `§3正在处理订单 §a${unconverted.order_id} §3请稍候...`)
|
||||||
|
this.recharge(sender, unconverted)
|
||||||
|
Thread.sleep(300)
|
||||||
|
}
|
||||||
|
}).async().submit()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 请在异步线程执行此方法
|
||||||
|
* @param amount 订单金额(非点券金额)
|
||||||
|
*/
|
||||||
|
recharge(sender: org.bukkit.entity.Player, order: Order) {
|
||||||
|
let order_id = order.order_id
|
||||||
|
let amount = order.amount
|
||||||
|
let point = this.safeMultiply(amount, this.config.ratio)
|
||||||
|
let finish = this.preFinishOrder(order_id)
|
||||||
|
if (finish.code != 200) {
|
||||||
|
this.sendError(sender, order_id, amount, '§4充值预标记异常!')
|
||||||
|
return this.logger.console(`§c充值系统异常 订单 §3${order_id} 预标记异常! §4${this.config.coinName}已停止充值 §c请手动补单!`)
|
||||||
|
}
|
||||||
|
this.taskManager.callSyncMethod(() => {
|
||||||
|
let prePoint = this.getPlayerAmount(sender)
|
||||||
|
let command = this.config.command.replace('%player_name%', sender.getName()).replace('%amount%', `${point}`).replace('%remark%', `${order_id}`)
|
||||||
|
if (!this.server.dispatchConsoleCommand(command)) {
|
||||||
|
return this.sendError(sender, order_id, amount, '§4充值命令执行异常!')
|
||||||
|
}
|
||||||
|
this.checkRecharge(sender, order_id, amount, prePoint, point)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
@Listener()
|
||||||
|
private PlayerJoinEvent(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||||
|
const player = event.getPlayer()
|
||||||
|
this.cmdcheck(player, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private checkRecharge(sender: org.bukkit.entity.Player, order_id: string, amount: number, prePoint: number, point: number) {
|
||||||
|
this.taskManager.create(() => {
|
||||||
|
let nowPoint = this.checkNowPoint(sender, point, prePoint)
|
||||||
|
if (nowPoint === false) {
|
||||||
|
return this.sendError(sender, order_id, amount, '§4充值结果检测异常!')
|
||||||
|
}
|
||||||
|
this.logger.sender(sender, [
|
||||||
|
`§6充值 §a${point} §6${this.config.coinName} §a成功 §6当前账户余额: §3${nowPoint} §6${this.config.coinName}`,
|
||||||
|
`§c如出现未到账的情况 请联系管理员!`
|
||||||
|
])
|
||||||
|
this.rewardOrder(sender, order_id, point)
|
||||||
|
let finish = this.finishOrder(order_id)
|
||||||
|
if (finish.code != 200) {
|
||||||
|
return this.logger.console(`§c充值系统异常 订单 §3${order_id} 完成标记异常! §4${this.config.coinName}可能重复到账!`)
|
||||||
|
}
|
||||||
|
}).async().submit()
|
||||||
|
}
|
||||||
|
|
||||||
|
private checkNowPoint(sender: org.bukkit.entity.Player, point: number, prePoint: number) {
|
||||||
|
let nowPoint = this.getPlayerAmount(sender)
|
||||||
|
if (nowPoint == prePoint + point) {
|
||||||
|
return nowPoint
|
||||||
|
}
|
||||||
|
Thread.sleep(100)
|
||||||
|
nowPoint = this.getPlayerAmount(sender)
|
||||||
|
if (nowPoint == prePoint + point) {
|
||||||
|
return nowPoint
|
||||||
|
}
|
||||||
|
Thread.sleep(200)
|
||||||
|
nowPoint = this.getPlayerAmount(sender)
|
||||||
|
if (nowPoint == prePoint + point) {
|
||||||
|
return nowPoint
|
||||||
|
}
|
||||||
|
Thread.sleep(300)
|
||||||
|
nowPoint = this.getPlayerAmount(sender)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
private rewardOrder(sender, order_id, point) {
|
||||||
|
this.taskManager.callSyncMethod(() => {
|
||||||
|
try {
|
||||||
|
if (this.config.reward['*']) {
|
||||||
|
let rewardCommands: string[] = this.config.reward['*']
|
||||||
|
for (const command of rewardCommands) {
|
||||||
|
this.dispatchConsoleCommand(sender, command, point, order_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let rewardCommands: string[] = this.config.reward[point]
|
||||||
|
if (rewardCommands && rewardCommands.length) {
|
||||||
|
for (const command of rewardCommands) {
|
||||||
|
this.dispatchConsoleCommand(sender, command, point, order_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('§4充值奖励命令执行错误: §c' + error)
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private dispatchConsoleCommand(sender, command, point, order_id) {
|
||||||
|
return this.server.dispatchConsoleCommand(command.replace('%player_name%', sender.getName()).replace('%amount%', `${point}`).replace('%remark%', `${order_id}`))
|
||||||
|
}
|
||||||
|
|
||||||
|
sendError(sender: org.bukkit.entity.Player, order_id: string, amount: number, error: string) {
|
||||||
|
return this.logger.sender(sender, [
|
||||||
|
`§c========== ${this.config.prefix}§4充值异常 §c==========`,
|
||||||
|
`§6异常订单: §3${order_id}`,
|
||||||
|
`§6订单金额: §3${amount}`,
|
||||||
|
`§6异常原因: §4${error}`,
|
||||||
|
`§6异常账号: §b${sender.getName()}`,
|
||||||
|
`§6异常时间: §a${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,
|
||||||
|
`§c如果已付款但${this.config.coinName}未到账 请截图发给腐竹!`,
|
||||||
|
`§c========== ${this.config.prefix}§4充值异常 §c==========`,
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Tab()
|
||||||
|
tabmpay() { }
|
||||||
|
|
||||||
|
private safeMultiply(a: number, b: number) {
|
||||||
|
return parseFloat((a * b).toFixed(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
private getPlayerAmount(sender: any): number {
|
||||||
|
let result = this.PlaceholderAPI.setPlaceholders(sender, this.config.check)
|
||||||
|
let amount = parseFloat(result)
|
||||||
|
if (isNaN(amount)) {
|
||||||
|
throw new Error(`§c读取玩家 §3${this.config.coinName} §c异常 §6请检查 §3check §6配置是否正确!
|
||||||
|
§6数据解析链路: §3${this.config.check} §6=> §3${result} §6=> §3${amount}`)
|
||||||
|
}
|
||||||
|
return amount
|
||||||
|
}
|
||||||
|
|
||||||
|
private queryStatus(id: string, wait: number, time = 60) {
|
||||||
|
return this.httpPost('/status', { id, wait, time })
|
||||||
|
}
|
||||||
|
|
||||||
|
private preFinishOrder(id: string) {
|
||||||
|
return this.httpPost('/preFinish', { id })
|
||||||
|
}
|
||||||
|
|
||||||
|
private finishOrder(id: string) {
|
||||||
|
return this.httpPost('/finish', { id })
|
||||||
|
}
|
||||||
|
|
||||||
|
private createOrder(sender: org.bukkit.entity.Player, amount: number): Order {
|
||||||
|
let serverName = this.MiaoReward.serverInfo.name
|
||||||
|
if (this.config.name) { serverName = `${serverName}(${this.config.name})` }
|
||||||
|
let result = this.httpPost('/create', {
|
||||||
|
subject: `${serverName} 充值 ${amount} ${this.config.coinName}`,
|
||||||
|
amount: amount / this.config.ratio,
|
||||||
|
username: sender.getName(),
|
||||||
|
unionId: sender.getUniqueId().toString()
|
||||||
|
})
|
||||||
|
if (result.code != 200) {
|
||||||
|
throw new Error(`订单创建失败: ${result.msg}`)
|
||||||
|
}
|
||||||
|
return result.data
|
||||||
|
}
|
||||||
|
|
||||||
|
private queryOrder(id: string, username: string, uuid: string) {
|
||||||
|
return this.httpPost('/query', { id, username, uuid })
|
||||||
|
}
|
||||||
|
|
||||||
|
private queryUnconverted(username: string, force: number) {
|
||||||
|
return this.httpPost('/unconverted', { username, force })
|
||||||
|
}
|
||||||
|
|
||||||
|
private httpPost(method: string, data: any) {
|
||||||
|
let startTime = Date.now()
|
||||||
|
data.appid = this.config.id
|
||||||
|
data.timestamp = Math.round(Date.now() / 1000)
|
||||||
|
data.sign = this.sign(data)
|
||||||
|
let url = `${this.apiGateWay}/api${method}`
|
||||||
|
let result = http.post(url, data)
|
||||||
|
console.debug(`
|
||||||
|
====== HTTP POST ======
|
||||||
|
REQUEST URL : ${url}
|
||||||
|
REQUEST DATA: ${JSON.stringify(data)}
|
||||||
|
RESPONSE : ${JSON.stringify(result)}
|
||||||
|
CAST TIME : ${Date.now() - startTime}`)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private http_build_query(params: any) {
|
||||||
|
return Object.keys(params).filter(key => key !== 'sign' && params[key] != undefined && params[key] != null)
|
||||||
|
.sort().map(key => key + '=' + params[key]).join('&')
|
||||||
|
}
|
||||||
|
|
||||||
|
private sign(params) {
|
||||||
|
// 排序后转换为字符串
|
||||||
|
let signStr = `${this.http_build_query(params)}&key=${this.config.secret}`
|
||||||
|
return CryptoJS.MD5(signStr).toString().toUpperCase()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,12 +52,13 @@ export class MiaoProtocol extends interfaces.Plugin {
|
|||||||
initPacketAdapter() {
|
initPacketAdapter() {
|
||||||
this.adapter = this.createPacketAdapter((event) => {
|
this.adapter = this.createPacketAdapter((event) => {
|
||||||
let integers = event.getPacket().getIntegers().getValues()
|
let integers = event.getPacket().getIntegers().getValues()
|
||||||
console.log(`ProtocolLib onPacketSending filter Map
|
// console.log(`ProtocolLib onPacketSending filter Map
|
||||||
Player: ${event.getPlayer()}
|
// Player: ${event.getPlayer()}
|
||||||
MapId: ${integers.get(0)}
|
// MapId: ${integers.get(0)}
|
||||||
Size: ${integers.get(3)}x${integers.get(4)}
|
// Short: ${event.getPacket().getShorts().read(0)}
|
||||||
Bytes: ${event.getPacket().getByteArrays().read(0).length}
|
// Bytes: ${event.getPacket().getByteArrays().read(0).length}
|
||||||
`)
|
// `)
|
||||||
|
//Size: ${integers.get(3)}x${integers.get(4)}
|
||||||
// org.bukkit.map.MapPalette.imageToBytes()
|
// org.bukkit.map.MapPalette.imageToBytes()
|
||||||
})
|
})
|
||||||
this.ProtocolLibrary.getProtocolManager().addPacketListener(this.adapter)
|
this.ProtocolLibrary.getProtocolManager().addPacketListener(this.adapter)
|
||||||
|
|||||||
@@ -8,18 +8,48 @@ import http from '@ccms/common/dist/http'
|
|||||||
|
|
||||||
const BufferedImage = Java.type('java.awt.image.BufferedImage')
|
const BufferedImage = Java.type('java.awt.image.BufferedImage')
|
||||||
const Color = Java.type('java.awt.Color')
|
const Color = Java.type('java.awt.Color')
|
||||||
|
const Bytes = Java.type('byte[]')
|
||||||
|
|
||||||
interface PlaceholderAPI {
|
interface PlaceholderAPI {
|
||||||
registerPlaceholderHook: (key: string, onPlaceholderRequest: (player, s) => string) => void
|
registerPlaceholderHook: (key: string, onPlaceholderRequest: (player, s) => string) => void
|
||||||
|
registerExpansion: (expansion: PlaceholderExpansion) => void
|
||||||
unregisterPlaceholderHook: (key: string) => void
|
unregisterPlaceholderHook: (key: string) => void
|
||||||
setPlaceholders: (player: any, str: string) => string
|
setPlaceholders: (player: any, str: string) => string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface PlaceholderExpansion {
|
||||||
|
getIdentifier: () => string
|
||||||
|
getAuthor: () => string
|
||||||
|
getVersion: () => string
|
||||||
|
persist: () => string
|
||||||
|
onPlaceholderRequest: (player, s) => string
|
||||||
|
}
|
||||||
|
|
||||||
interface UserInfo {
|
interface UserInfo {
|
||||||
balance: number
|
balance: number
|
||||||
sign: string
|
sign: string
|
||||||
video: string
|
video: string
|
||||||
box: string
|
box: string
|
||||||
|
block: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ServerInfo {
|
||||||
|
// 16,
|
||||||
|
id: number
|
||||||
|
// "圈云大陆",
|
||||||
|
name: string
|
||||||
|
// 1,
|
||||||
|
owner: number
|
||||||
|
// 48200,
|
||||||
|
score: number
|
||||||
|
// 1,
|
||||||
|
ratio: number
|
||||||
|
// 1,
|
||||||
|
audit: number
|
||||||
|
// 2,
|
||||||
|
status: number
|
||||||
|
// 0
|
||||||
|
today: number
|
||||||
}
|
}
|
||||||
|
|
||||||
let createPacketAdapterFunction = eval(`
|
let createPacketAdapterFunction = eval(`
|
||||||
@@ -29,9 +59,19 @@ function(cls, plugin, type, onPacketSending){
|
|||||||
}
|
}
|
||||||
}`)
|
}`)
|
||||||
|
|
||||||
@JSPlugin({ prefix: 'MRD', version: '1.4.1', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
const defaultConfig = {
|
||||||
|
prefix: '§6[§b广告系统§6]§r',
|
||||||
|
serverId: '',
|
||||||
|
serverToken: '',
|
||||||
|
drawCommand: 'points give %player_name% %amount%',
|
||||||
|
coinName: '点券',
|
||||||
|
joinTip: true
|
||||||
|
}
|
||||||
|
|
||||||
|
@JSPlugin({ prefix: 'MRD', version: '1.5.9', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], nativeDepends: ['ProtocolLib', 'PlaceholderAPI'], source: __filename })
|
||||||
export class MiaoReward extends interfaces.Plugin {
|
export class MiaoReward extends interfaces.Plugin {
|
||||||
private serverInfo: any
|
public serverInfo: ServerInfo
|
||||||
|
private notifyError = true
|
||||||
private cacheBindUuid = ''
|
private cacheBindUuid = ''
|
||||||
private zeroMapView = undefined
|
private zeroMapView = undefined
|
||||||
private playerImageCache = new Map<string, any>()
|
private playerImageCache = new Map<string, any>()
|
||||||
@@ -52,19 +92,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
private bungee: proxy.BungeeCord
|
private bungee: proxy.BungeeCord
|
||||||
|
|
||||||
@Config()
|
@Config()
|
||||||
private config: PluginConfig & {
|
private config: PluginConfig & typeof defaultConfig = defaultConfig
|
||||||
prefix: string
|
|
||||||
serverId: string
|
|
||||||
serverToken: string
|
|
||||||
drawCommand: string
|
|
||||||
coinName: string
|
|
||||||
} = {
|
|
||||||
prefix: '§6[§b广告系统§6]§r',
|
|
||||||
serverId: '',
|
|
||||||
serverToken: '',
|
|
||||||
drawCommand: 'p give %player_name% %amount%',
|
|
||||||
coinName: '点券'
|
|
||||||
}
|
|
||||||
|
|
||||||
@JSClass('org.bukkit.Bukkit')
|
@JSClass('org.bukkit.Bukkit')
|
||||||
private Bukkit: any
|
private Bukkit: any
|
||||||
@@ -73,6 +101,9 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
private PlaceholderAPI: PlaceholderAPI
|
private PlaceholderAPI: PlaceholderAPI
|
||||||
@JSClass('me.clip.placeholderapi.PlaceholderHook')
|
@JSClass('me.clip.placeholderapi.PlaceholderHook')
|
||||||
private PlaceholderHook: any
|
private PlaceholderHook: any
|
||||||
|
@JSClass('me.clip.placeholderapi.expansion.PlaceholderExpansion')
|
||||||
|
private PlaceholderExpansion: any
|
||||||
|
private expansion: any
|
||||||
|
|
||||||
@JSClass('com.comphenix.protocol.ProtocolLibrary')
|
@JSClass('com.comphenix.protocol.ProtocolLibrary')
|
||||||
private ProtocolLibrary: any
|
private ProtocolLibrary: any
|
||||||
@@ -90,18 +121,21 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
load() {
|
load() {
|
||||||
this.config.prefix = this.config.prefix || '§6[§b广告系统§6]§r'
|
this.config.prefix = this.config.prefix || '§6[§b广告系统§6]§r'
|
||||||
this.config.drawCommand = this.config.drawCommand || 'p give %player_name% %amount%'
|
this.config.drawCommand = this.config.drawCommand || 'p give %player_name% %amount%'
|
||||||
if (!this.config.coinName) {
|
if (this.config.coinName == undefined) {
|
||||||
this.config.coinName = '点券'
|
this.config.coinName = '点券'
|
||||||
this.config.save()
|
this.config.save()
|
||||||
}
|
}
|
||||||
|
if (this.config.joinTip == undefined) {
|
||||||
|
this.config.joinTip = true
|
||||||
|
this.config.save()
|
||||||
|
}
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
this.logger.prefix = this.config.prefix
|
this.logger.prefix = this.config.prefix
|
||||||
this.downgrade = this.Bukkit.server.class.name.split('.')[3] == "v1_7_R4"
|
this.downgrade = this.Bukkit.server.class.name.split('.')[3] == "v1_7_R4"
|
||||||
this.updateServerInfo()
|
this.updateServerInfo(null, () => this.updateOnlinePlayersInfo())
|
||||||
this.updateOnlinePlayersInfo()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateServerInfo(player?: any) {
|
private updateServerInfo(player?: any, cb?: () => void) {
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
if (this.config.serverId) {
|
if (this.config.serverId) {
|
||||||
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
||||||
@@ -111,6 +145,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
if (result.code == 200) {
|
if (result.code == 200) {
|
||||||
this.serverInfo = result.data
|
this.serverInfo = result.data
|
||||||
if (player) this.bungee.for(player).forward("ALL", "MiaoReward", { type: "updateServerInfo", data: result.data }).send()
|
if (player) this.bungee.for(player).forward("ALL", "MiaoReward", { type: "updateServerInfo", data: result.data }).send()
|
||||||
|
cb?.()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).async().submit()
|
}).async().submit()
|
||||||
@@ -169,21 +204,30 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
if (!this.PlaceholderAPI) {
|
if (!this.PlaceholderAPI) {
|
||||||
console.console("§cCan't found me.clip.placeholderapi.PlaceholderAPI variable will not be replaced!")
|
console.console("§cCan't found me.clip.placeholderapi.PlaceholderAPI variable will not be replaced!")
|
||||||
} else {
|
} else {
|
||||||
this.PlaceholderAPI.registerPlaceholderHook("mrd", new this.PlaceholderHook({
|
this.expansion = new this.PlaceholderExpansion({
|
||||||
onPlaceholderRequest: (player: any, s: string) => {
|
getIdentifier: () => 'mrd',
|
||||||
if (!this.playerInfoCache.has(player.getName())) { return '用户未绑定' }
|
persist: () => true,
|
||||||
|
getAuthor: () => 'MiaoWoo',
|
||||||
|
getVersion: () => '1.0.0',
|
||||||
|
onPlaceholderRequest: this.onPlaceholderRequest.bind(this)
|
||||||
|
})
|
||||||
|
this.taskManager.create(() => this.expansion.register()).submit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private onPlaceholderRequest(player: any, s: string) {
|
||||||
|
if (!this.playerInfoCache.has(player.getName())) { return '数据加载中' }
|
||||||
let data = this.playerInfoCache.get(player.getName())
|
let data = this.playerInfoCache.get(player.getName())
|
||||||
|
if (!data) { return '用户未绑定' }
|
||||||
switch (s.toLowerCase()) {
|
switch (s.toLowerCase()) {
|
||||||
case "balance": return data.balance
|
case "balance": return data.balance
|
||||||
case "sign": return data.sign
|
case "sign": return data.sign
|
||||||
case "video": return data.video
|
case "video": return data.video
|
||||||
case "box": return data.box
|
case "box": return data.box
|
||||||
|
case "block": return data.block
|
||||||
default: return "未知的参数: " + s
|
default: return "未知的参数: " + s
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private initZeroMap() {
|
private initZeroMap() {
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
@@ -196,19 +240,34 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
this.initPacketAdapter()
|
this.initPacketAdapter()
|
||||||
}
|
}
|
||||||
|
|
||||||
createPacketAdapter(onPacketSending: (event) => void) {
|
private createPacketAdapter(onPacketSending: (event) => void) {
|
||||||
return createPacketAdapterFunction(this.PacketAdapter, base.getInstance(), [this.PacketType.Play.Server.MAP], onPacketSending)
|
return createPacketAdapterFunction(this.PacketAdapter, base.getInstance(), [this.PacketType.Play.Server.MAP], onPacketSending)
|
||||||
}
|
}
|
||||||
|
|
||||||
initPacketAdapter() {
|
private initPacketAdapter() {
|
||||||
|
if (!this.ProtocolLibrary) {
|
||||||
|
return this.logger.console(`§4服务器未安装 ProtocolLib 无法扫码功能 请安装后重试!`)
|
||||||
|
}
|
||||||
this.adapter = this.createPacketAdapter((event) => {
|
this.adapter = this.createPacketAdapter((event) => {
|
||||||
let integers = event.getPacket().getIntegers().getValues()
|
let integers = event.getPacket().getIntegers().getValues()
|
||||||
let mapId = integers.get(0)
|
let mapId = integers.get(0)
|
||||||
let player = event.getPlayer()
|
let player = event.getPlayer()
|
||||||
if (mapId == this.zeroMapView.getId() && this.playerImageCache.has(player.getName())) {
|
if (mapId == this.zeroMapView.getId() && this.playerImageCache.has(player.getName())) {
|
||||||
event.getPacket().getByteArrays().write(0, org.bukkit.map.MapPalette.imageToBytes(this.playerImageCache.get(player.getName())))
|
let bytes = this.playerImageCache.get(player.getName())
|
||||||
|
if (!this.downgrade) {
|
||||||
|
event.getPacket().getByteArrays().write(0, bytes)
|
||||||
event.getPacket().getIntegers().write(3, 128)
|
event.getPacket().getIntegers().write(3, 128)
|
||||||
event.getPacket().getIntegers().write(4, 128)
|
event.getPacket().getIntegers().write(4, 128)
|
||||||
|
} else {
|
||||||
|
// let xbytes = new Bytes(131)
|
||||||
|
let origin = event.getPacket().getByteArrays().read(0)
|
||||||
|
// xbytes[1] = origin[1]
|
||||||
|
// xbytes[2] = origin[2]
|
||||||
|
for (let y = 0; y < 128; ++y) {
|
||||||
|
origin[y + 3] = bytes[y * 128 + origin[1]]
|
||||||
|
}
|
||||||
|
event.getPacket().getByteArrays().write(0, origin)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
this.ProtocolLibrary.getProtocolManager().addPacketListener(this.adapter)
|
this.ProtocolLibrary.getProtocolManager().addPacketListener(this.adapter)
|
||||||
@@ -222,10 +281,19 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
java.util.Arrays.fill(arritemStack, new org.bukkit.inventory.ItemStack(org.bukkit.Material.AIR))
|
java.util.Arrays.fill(arritemStack, new org.bukkit.inventory.ItemStack(org.bukkit.Material.AIR))
|
||||||
arritemStack[36 + player.getInventory().getHeldItemSlot()] = mapItem
|
arritemStack[36 + player.getInventory().getHeldItemSlot()] = mapItem
|
||||||
var packetContainer = protocolManager.createPacket(this.PacketType.Play.Server.WINDOW_ITEMS)
|
var packetContainer = protocolManager.createPacket(this.PacketType.Play.Server.WINDOW_ITEMS)
|
||||||
if (packetContainer.getItemArrayModifier().size() > 0) {
|
try {
|
||||||
packetContainer.getItemArrayModifier().write(0, arritemStack)
|
packetContainer.getItemArrayModifier().write(0, arritemStack)
|
||||||
} else {
|
} catch (error) {
|
||||||
|
try {
|
||||||
packetContainer.getItemListModifier().write(0, java.util.Arrays.asList(arritemStack))
|
packetContainer.getItemListModifier().write(0, java.util.Arrays.asList(arritemStack))
|
||||||
|
} catch (error) {
|
||||||
|
if (this.notifyError) {
|
||||||
|
console.console('§4发送虚拟物品包失败 可能是ProtocolLib版本不兼容!')
|
||||||
|
console.ex(error)
|
||||||
|
this.notifyError = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
protocolManager.sendServerPacket(player, packetContainer)
|
protocolManager.sendServerPacket(player, packetContainer)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
@@ -234,14 +302,14 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
disable() {
|
disable() {
|
||||||
this.PlaceholderAPI?.unregisterPlaceholderHook("mrd")
|
try { this.expansion?.unregister() } catch (error) { }
|
||||||
this.adapter && this.ProtocolLibrary.getProtocolManager().removePacketListener(this.adapter)
|
this.adapter && this.ProtocolLibrary.getProtocolManager().removePacketListener(this.adapter)
|
||||||
Java.from(this.server.getOnlinePlayers()).forEach(p => this.checkAndClear(p))
|
Java.from(this.server.getOnlinePlayers()).forEach(p => this.checkAndClear(p))
|
||||||
this.channelOff?.off()
|
this.channelOff?.off()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Cmd()
|
@Cmd()
|
||||||
mrd(sender: any, command: string, args: string[]) {
|
private mrd(sender: any, command: string, args: string[]) {
|
||||||
let cmd = args[0] || 'help'
|
let cmd = args[0] || 'help'
|
||||||
let cmdKey = 'cmd' + cmd
|
let cmdKey = 'cmd' + cmd
|
||||||
if (!this[cmdKey]) {
|
if (!this[cmdKey]) {
|
||||||
@@ -253,7 +321,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
this.taskManager.create(() => this[cmdKey](sender, ...args)).async().submit()
|
this.taskManager.create(() => this[cmdKey](sender, ...args)).async().submit()
|
||||||
}
|
}
|
||||||
|
|
||||||
private scanAuth(sender: org.bukkit.entity.Player, scanType: string, scanObj: { title: string, content: string }, success: (token: string, user: any) => void, cancel?: () => void) {
|
public scanAuth(sender: org.bukkit.entity.Player, scanType: string, scanObj: { title: string, content: string }, success: (token: string, user: any) => void, cancel?: () => void) {
|
||||||
this.logger.sender(sender, '§a正在获取授权二维码...')
|
this.logger.sender(sender, '§a正在获取授权二维码...')
|
||||||
let scan = this.httpPost('https://reward.yumc.pw/auth/scan', { ...scanObj, type: scanType })
|
let scan = this.httpPost('https://reward.yumc.pw/auth/scan', { ...scanObj, type: scanType })
|
||||||
if (scan.code == 200) {
|
if (scan.code == 200) {
|
||||||
@@ -300,6 +368,9 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private bindCheck(sender: org.bukkit.entity.Player) {
|
private bindCheck(sender: org.bukkit.entity.Player) {
|
||||||
|
if (!this.ProtocolLibrary) {
|
||||||
|
return this.logger.sender(sender, `§4服务器未安装 ProtocolLib 无法扫码功能 请安装后重试!`)
|
||||||
|
}
|
||||||
let scanning = this.playerTaskCache.has(sender.getName())
|
let scanning = this.playerTaskCache.has(sender.getName())
|
||||||
if (scanning) {
|
if (scanning) {
|
||||||
this.logger.sender(sender, "§4当前正在进行扫码 请稍候重试!")
|
this.logger.sender(sender, "§4当前正在进行扫码 请稍候重试!")
|
||||||
@@ -307,21 +378,27 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
return scanning
|
return scanning
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdbind(sender: org.bukkit.entity.Player, server: boolean) {
|
private cmdopen(sender: org.bukkit.entity.Player) {
|
||||||
if (this.bindCheck(sender)) return
|
if (this.bindCheck(sender)) return
|
||||||
|
this.logger.sender(sender, '§a正在获取小程序二维码...')
|
||||||
|
let sync = { scaned: false }
|
||||||
|
this.setItemAndTp(sender, 'https://m.q.qq.com/a/p/1110360279?s=' + encodeURIComponent(`pages/my/index`), sync)
|
||||||
|
this.taskManager.create(() => sync.scaned = true).later(20 * 50).submit()
|
||||||
|
}
|
||||||
|
|
||||||
|
private cmdbind(sender: org.bukkit.entity.Player, server: boolean) {
|
||||||
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
||||||
|
if (this.bindCheck(sender)) return
|
||||||
if (server) {
|
if (server) {
|
||||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4您没有配置服务器的权限!') }
|
|
||||||
this.bindServer(sender)
|
this.bindServer(sender)
|
||||||
} else {
|
} else {
|
||||||
if (!this.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
|
||||||
this.bindUser(sender)
|
this.bindUser(sender)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cmddraw(sender: org.bukkit.entity.Player, amount: number) {
|
private cmddraw(sender: org.bukkit.entity.Player, amount: number) {
|
||||||
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
||||||
if (!this.playerInfoCache.has(sender.getName())) { return this.logger.sender(sender, '§c当前用户尚未绑定服务器玩家账号 请先执行 /mrd bind 绑定账号!') }
|
if (!this.playerInfoCache.get(sender.getName())) { return this.logger.sender(sender, '§c当前用户尚未绑定服务器玩家账号 请先执行 /mrd bind 绑定账号!') }
|
||||||
amount = Number(amount)
|
amount = Number(amount)
|
||||||
if (!Number.isInteger(amount)) {
|
if (!Number.isInteger(amount)) {
|
||||||
return this.logger.sender(sender, '§4金额必须是数字!')
|
return this.logger.sender(sender, '§4金额必须是数字!')
|
||||||
@@ -337,7 +414,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
"是否授权 " + this.serverInfo.name + " 兑换喵币",
|
"是否授权 " + this.serverInfo.name + " 兑换喵币",
|
||||||
"兑换玩家: " + sender.getName(),
|
"兑换玩家: " + sender.getName(),
|
||||||
"兑换数量: " + amount,
|
"兑换数量: " + amount,
|
||||||
"兑换比例: " + parseFloat(this.serverInfo.ratio),
|
"兑换比例: " + this.serverInfo.ratio,
|
||||||
"预计到帐: " + (amount * this.serverInfo.ratio).toFixed(0),
|
"预计到帐: " + (amount * this.serverInfo.ratio).toFixed(0),
|
||||||
"注意: 数据可能更新不及时 请以实际到账金额为准!"
|
"注意: 数据可能更新不及时 请以实际到账金额为准!"
|
||||||
].join('\n')
|
].join('\n')
|
||||||
@@ -371,6 +448,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
this.logger.sender(sender, draw.msg.split('\n').map(s => s.replace('点券', this.config.coinName)))
|
this.logger.sender(sender, draw.msg.split('\n').map(s => s.replace('点券', this.config.coinName)))
|
||||||
this.sendBroadcast(sender, `${this.config.prefix}§6玩家 §b${sender.getName()} §6成功将 §a${amount}喵币 §6兑换成 §c${draw.data}${this.config.coinName}!`)
|
this.sendBroadcast(sender, `${this.config.prefix}§6玩家 §b${sender.getName()} §6成功将 §a${amount}喵币 §6兑换成 §c${draw.data}${this.config.coinName}!`)
|
||||||
this.sendBroadcast(sender, `${this.config.prefix}§c/mrd help §b查看广告系统帮助 §6快来一起看广告赚${this.config.coinName}吧!`)
|
this.sendBroadcast(sender, `${this.config.prefix}§c/mrd help §b查看广告系统帮助 §6快来一起看广告赚${this.config.coinName}吧!`)
|
||||||
|
this.queryUser(sender)
|
||||||
}).submit()
|
}).submit()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -385,7 +463,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdrank(sender: any, boardcast: boolean) {
|
private cmdrank(sender: any, boardcast: boolean) {
|
||||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
||||||
let result = this.httpPost(`https://reward.yumc.pw/server/rank`, {
|
let result = this.httpPost(`https://reward.yumc.pw/server/rank`, {
|
||||||
id: this.config.serverId,
|
id: this.config.serverId,
|
||||||
@@ -406,7 +484,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdserver(sender: any) {
|
private cmdserver(sender: any) {
|
||||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
||||||
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
||||||
id: this.config.serverId,
|
id: this.config.serverId,
|
||||||
@@ -426,7 +504,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdratio(sender: any, ratioStr: string, confirm: string) {
|
private cmdratio(sender: any, ratioStr: string, confirm: string) {
|
||||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
||||||
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
||||||
let [ratio, mbr, msg] = this.ratio2string(ratioStr)
|
let [ratio, mbr, msg] = this.ratio2string(ratioStr)
|
||||||
@@ -465,7 +543,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdreload() {
|
private cmdreload() {
|
||||||
this.config.reload()
|
this.config.reload()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -484,6 +562,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private bindServer(sender: org.bukkit.entity.Player) {
|
private bindServer(sender: org.bukkit.entity.Player) {
|
||||||
|
if (!sender.isOp()) { return this.logger.sender(sender, '§4您没有配置服务器的权限!') }
|
||||||
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
||||||
let scanObj = http.get(`https://reward.yumc.pw/server/scan`)
|
let scanObj = http.get(`https://reward.yumc.pw/server/scan`)
|
||||||
if (scanObj.code !== 200) {
|
if (scanObj.code !== 200) {
|
||||||
@@ -510,8 +589,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private bindUser(sender: org.bukkit.entity.Player) {
|
private bindUser(sender: org.bukkit.entity.Player) {
|
||||||
if (!this.config.serverId || !this.config.serverToken) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
if (!this.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||||
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
|
||||||
let check = this.httpPost(`https://reward.yumc.pw/server/query`, {
|
let check = this.httpPost(`https://reward.yumc.pw/server/query`, {
|
||||||
id: this.config.serverId,
|
id: this.config.serverId,
|
||||||
token: this.config.serverToken
|
token: this.config.serverToken
|
||||||
@@ -521,8 +599,10 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
let queryUser = this.queryUser(sender)
|
let queryUser = this.queryUser(sender)
|
||||||
if (queryUser.code == 200) {
|
if (queryUser.code == 200) {
|
||||||
return this.logger.sender(sender, ['§4当前用户已绑定! §c如需解绑 请联系腐竹!', '§b如需看广告请进QQ群 §a点击聊天框上的圈云盒子!'])
|
this.logger.sender(sender, ['§a当前用户已绑定! §3如需看广告请扫码进入!'])
|
||||||
|
return this.cmdopen(sender)
|
||||||
}
|
}
|
||||||
|
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
||||||
let bindUrl = 'https://m.q.qq.com/a/p/1110360279?s=' + encodeURIComponent(`pages/my/index?bindType=user&serverId=${this.config.serverId}&uuid=${sender.getUniqueId().toString()}&username=${sender.getName()}`)
|
let bindUrl = 'https://m.q.qq.com/a/p/1110360279?s=' + encodeURIComponent(`pages/my/index?bindType=user&serverId=${this.config.serverId}&uuid=${sender.getUniqueId().toString()}&username=${sender.getName()}`)
|
||||||
let sync = { scaned: false, timeout: false }
|
let sync = { scaned: false, timeout: false }
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
@@ -535,66 +615,76 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
this.setItemAndTp(sender, bindUrl, sync)
|
this.setItemAndTp(sender, bindUrl, sync)
|
||||||
}
|
}
|
||||||
|
|
||||||
private sendActionBar(sender, message) {
|
public sendActionBar(sender, message) {
|
||||||
if (!this.downgrade) {
|
if (!this.downgrade) {
|
||||||
this.chat.sendActionBar(sender, message)
|
this.chat.sendActionBar(sender, message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private sendTitle(sender, title, subtitle?) {
|
public sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
||||||
if (!title) return
|
if (!title) return
|
||||||
if (this.downgrade) {
|
if (this.downgrade) {
|
||||||
this.logger.sender(sender, `${title}${subtitle ? ` ${subtitle}` : ''}`)
|
this.logger.sender(sender, `${title}${subtitle ? ` ${subtitle}` : ''}`)
|
||||||
} else {
|
} else {
|
||||||
this.chat.sendTitle(sender, title, subtitle)
|
this.chat.sendTitle(sender, title, subtitle, fadeIn, time, fadeOut)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private setItemAndTp(sender: org.bukkit.entity.Player, content: string, sync: { scaned: boolean }) {
|
public clearTitle(sender) {
|
||||||
|
this.chat.clearTitle(sender)
|
||||||
|
}
|
||||||
|
|
||||||
|
public setItemAndTp(sender: org.bukkit.entity.Player, content: string, sync: { scaned: boolean, left?: number, cancelled?: boolean }, name: string = '手机QQ扫描二维码', tip: string = '手机QQ扫描二维码') {
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
let bindingLeftTime = 55
|
if (!sync.left) { sync.left = 55 }
|
||||||
|
sync.cancelled = false
|
||||||
let task = this.taskManager.create(() => {
|
let task = this.taskManager.create(() => {
|
||||||
try {
|
try {
|
||||||
if (sync.scaned || !sender.isOnline() || !this.isHoldQrCodeItem(sender) || --bindingLeftTime < 0) {
|
if (sync.scaned || !sender.isOnline() || !this.isHoldQrCodeItem(sender) || --sync.left < 0) {
|
||||||
if (bindingLeftTime < 0) {
|
if (sync.left < 0) {
|
||||||
this.logger.sender(sender, '§c二维码已过期 请重新获取 如已扫码请忽略!')
|
this.logger.sender(sender, '§c二维码已过期 请重新获取 如已扫码请忽略!')
|
||||||
task.cancel()
|
task.cancel()
|
||||||
}
|
}
|
||||||
this.cancelTask(sender)
|
this.cancelTask(sender)
|
||||||
|
sync.cancelled = true
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
this.sendActionBar(sender, `§c§l手机QQ扫描二维码 剩余 ${bindingLeftTime} 秒...`)
|
this.sendActionBar(sender, `§c§l${tip} 剩余 ${sync.left} 秒...`)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
}
|
}
|
||||||
}, this).async().later(20).timer(20).submit()
|
}, this).async().later(20).timer(20).submit()
|
||||||
this.playerTaskCache.set(sender.getName(), task)
|
this.playerTaskCache.set(sender.getName(), task)
|
||||||
this.playerImageCache.set(sender.getName(), this.createQrcode(content))
|
if (this.downgrade) { this.downgradeTask(sender) }
|
||||||
if (this.downgrade) {
|
this.playerImageCache.set(sender.getName(), org.bukkit.map.MapPalette.imageToBytes(this.createQrcode(content)))
|
||||||
this.logger.sender(sender, '§c低版本客户端 二维码渲染中 请等待 6 秒 稍候扫码!')
|
if (!this.downgrade) {
|
||||||
|
let temp = sender.getLocation()
|
||||||
|
temp.setPitch(90)
|
||||||
|
sender.teleport(temp)
|
||||||
|
}
|
||||||
|
this.sendWindowItems(sender, this.createQrCodeMapItem(name))
|
||||||
|
sender.sendMap(this.zeroMapView)
|
||||||
|
this.taskManager.create(() => this.sendWindowItems(sender, this.createQrCodeMapItem(name))).later(20).async().submit()
|
||||||
|
}).submit()
|
||||||
|
}
|
||||||
|
|
||||||
|
private downgradeTask(sender) {
|
||||||
|
this.logger.sender(sender, '§c低版本客户端 二维码渲染中 请等待 3 秒 稍候扫码!')
|
||||||
let waitTask = this.taskManager.create(() => {
|
let waitTask = this.taskManager.create(() => {
|
||||||
let temp = sender.getLocation()
|
let temp = sender.getLocation()
|
||||||
temp.setPitch(-90)
|
temp.setPitch(-90)
|
||||||
sender.teleport(temp)
|
sender.teleport(temp)
|
||||||
}, this).later(20).timer(20).submit()
|
}, this).later(0).timer(20).submit()
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
waitTask.cancel()
|
waitTask.cancel()
|
||||||
let temp = sender.getLocation()
|
let temp = sender.getLocation()
|
||||||
temp.setPitch(90)
|
temp.setPitch(90)
|
||||||
sender.teleport(temp)
|
sender.teleport(temp)
|
||||||
}).later(150).submit()
|
}).later(80).submit()
|
||||||
} else {
|
|
||||||
let temp = sender.getLocation()
|
|
||||||
temp.setPitch(90)
|
|
||||||
sender.teleport(temp)
|
|
||||||
}
|
|
||||||
this.sendWindowItems(sender, this.createQrCodeMapItem())
|
|
||||||
sender.sendMap(this.zeroMapView)
|
|
||||||
}).submit()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private queryUser(sender: org.bukkit.entity.Player, sync = false) {
|
private queryUser(sender: org.bukkit.entity.Player, sync = false) {
|
||||||
if (!this.config.serverId || !this.config.serverToken) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
if (!this.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||||
let result = this.httpPost(`https://reward.yumc.pw/server/queryUser`, {
|
let result = this.httpPost(`https://reward.yumc.pw/server/queryUser`, {
|
||||||
id: this.config.serverId,
|
id: this.config.serverId,
|
||||||
token: this.config.serverToken,
|
token: this.config.serverToken,
|
||||||
@@ -602,13 +692,11 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
username: sender.getName(),
|
username: sender.getName(),
|
||||||
sync
|
sync
|
||||||
})
|
})
|
||||||
if (result?.code == 200) {
|
this.playerInfoCache.set(sender.getName(), result?.code == 200 ? result.data : null)
|
||||||
this.playerInfoCache.set(sender.getName(), result.data)
|
|
||||||
}
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdquery(sender: org.bukkit.entity.Player) {
|
private cmdquery(sender: org.bukkit.entity.Player) {
|
||||||
let info = this.queryUser(sender)
|
let info = this.queryUser(sender)
|
||||||
if (info.code !== 200) {
|
if (info.code !== 200) {
|
||||||
return this.logger.sender(sender, '§4查询异常! §cError: ' + info.msg)
|
return this.logger.sender(sender, '§4查询异常! §cError: ' + info.msg)
|
||||||
@@ -626,11 +714,12 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
`§6签 到: §b${data.sign}`,
|
`§6签 到: §b${data.sign}`,
|
||||||
`§6视频广告: §b${data.video}`,
|
`§6视频广告: §b${data.video}`,
|
||||||
`§6盒子广告: §b${data.box}`,
|
`§6盒子广告: §b${data.box}`,
|
||||||
|
`§6积木广告: §b${data.block}`,
|
||||||
'§6==========================='
|
'§6==========================='
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
private httpPost(url, data) {
|
public httpPost(url, data) {
|
||||||
let startTime = Date.now()
|
let startTime = Date.now()
|
||||||
let result = http.post(url, data)
|
let result = http.post(url, data)
|
||||||
console.debug(`
|
console.debug(`
|
||||||
@@ -642,7 +731,7 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
private createQrCodeMapItem() {
|
private createQrCodeMapItem(name: string = '手机QQ扫描二维码') {
|
||||||
let item: org.bukkit.inventory.ItemStack
|
let item: org.bukkit.inventory.ItemStack
|
||||||
item = new org.bukkit.inventory.ItemStack(org.bukkit.Material.FILLED_MAP || org.bukkit.Material.MAP)
|
item = new org.bukkit.inventory.ItemStack(org.bukkit.Material.FILLED_MAP || org.bukkit.Material.MAP)
|
||||||
let meta = <org.bukkit.inventory.meta.MapMeta>item.getItemMeta()
|
let meta = <org.bukkit.inventory.meta.MapMeta>item.getItemMeta()
|
||||||
@@ -653,7 +742,7 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
} else {
|
} else {
|
||||||
item.setDurability(this.zeroMapView.getId())
|
item.setDurability(this.zeroMapView.getId())
|
||||||
}
|
}
|
||||||
meta.setDisplayName('§c请使用手机QQ扫描二维码!')
|
meta.setDisplayName(`§c${name}`)
|
||||||
meta.setLore(["QRCODE"])
|
meta.setLore(["QRCODE"])
|
||||||
item.setItemMeta(meta)
|
item.setItemMeta(meta)
|
||||||
return item
|
return item
|
||||||
@@ -692,30 +781,33 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Listener()
|
@Listener()
|
||||||
PlayerJoinEvent(event: org.bukkit.event.player.PlayerJoinEvent) {
|
private PlayerJoinEvent(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||||
const player = event.getPlayer()
|
const player = event.getPlayer()
|
||||||
this.bungeeCordDetect(player)
|
this.bungeeCordDetect(player)
|
||||||
this.updatePlayerInfo(player)
|
this.updatePlayerInfo(player)
|
||||||
|
if (this.config.joinTip) {
|
||||||
|
this.taskManager.create(() => this.logger.sender(player, `§a本服已使用喵式奖励 §3可以看广告赚${this.config.coinName} §c/mrd help §b查看帮助!`)).later(50).submit()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Listener()
|
@Listener()
|
||||||
PlayerDropItemEvent(event: org.bukkit.event.player.PlayerDropItemEvent) {
|
private PlayerDropItemEvent(event: org.bukkit.event.player.PlayerDropItemEvent) {
|
||||||
if (this.checkAndClear(event.getPlayer())) {
|
if (this.checkAndClear(event.getPlayer())) {
|
||||||
event.setCancelled(true)
|
event.setCancelled(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Listener()
|
@Listener()
|
||||||
PlayerItemHeldEvent(event: org.bukkit.event.player.PlayerItemHeldEvent) {
|
private PlayerItemHeldEvent(event: org.bukkit.event.player.PlayerItemHeldEvent) {
|
||||||
this.checkAndClear(event.getPlayer())
|
this.checkAndClear(event.getPlayer())
|
||||||
}
|
}
|
||||||
|
|
||||||
@Listener()
|
@Listener()
|
||||||
PlayerQuitEvent(event: org.bukkit.event.player.PlayerQuitEvent) {
|
private PlayerQuitEvent(event: org.bukkit.event.player.PlayerQuitEvent) {
|
||||||
this.checkAndClear(event.getPlayer())
|
this.checkAndClear(event.getPlayer())
|
||||||
}
|
}
|
||||||
|
|
||||||
private cancelTask(player) {
|
public cancelTask(player) {
|
||||||
if (!this.playerTaskCache.has(player.getName())) { return }
|
if (!this.playerTaskCache.has(player.getName())) { return }
|
||||||
this.checkAndClear(player)
|
this.checkAndClear(player)
|
||||||
this.sendActionBar(player, "")
|
this.sendActionBar(player, "")
|
||||||
@@ -737,10 +829,11 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdhelp(sender: any) {
|
private cmdhelp(sender: any) {
|
||||||
let help = [
|
let help = [
|
||||||
`§6====== ${this.config.prefix} §a帮助菜单 §6======`,
|
`§6====== ${this.config.prefix} §a帮助菜单 §6======`,
|
||||||
`§6/mrd bind §a绑定圈云盒子`,
|
`§6/mrd bind §a绑定圈云盒子`,
|
||||||
|
`§6/mrd open §a打开圈云盒子`,
|
||||||
`§6/mrd query §a查询当前账户`,
|
`§6/mrd query §a查询当前账户`,
|
||||||
`§6/mrd draw §e<兑换数量> §a兑换${this.config.coinName}`
|
`§6/mrd draw §e<兑换数量> §a兑换${this.config.coinName}`
|
||||||
]
|
]
|
||||||
@@ -761,7 +854,7 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Tab()
|
@Tab()
|
||||||
tabmrd(sender: any, _command: any, args: string | any[]) {
|
private tabmrd(sender: any, _command: any, args: string | any[]) {
|
||||||
if (args.length === 1) return ['help', 'bind', 'show', 'statistic', 'query', 'draw', 'ratio', 'rank', 'server']
|
if (args.length === 1) return ['help', 'bind', 'show', 'statistic', 'query', 'draw', 'ratio', 'rank', 'server']
|
||||||
if (args.length === 2 && args[0] === "bind" && sender.isOp()) return ['server']
|
if (args.length === 2 && args[0] === "bind" && sender.isOp()) return ['server']
|
||||||
}
|
}
|
||||||
|
|||||||
95
packages/plugins/src/MiaoRobot.ts
Normal file
95
packages/plugins/src/MiaoRobot.ts
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
/// <reference types="@javatypes/bungee-api" />
|
||||||
|
/// <reference types="@javatypes/bukkit-api" />
|
||||||
|
/// <reference types="@javatypes/sponge-api" />
|
||||||
|
/// <reference types="typescript" />
|
||||||
|
// @ts-ignore
|
||||||
|
require.clear('websocket/client')
|
||||||
|
import { server } from '@ccms/api'
|
||||||
|
import { Autowired, Container, ContainerInstance } from '@ccms/container'
|
||||||
|
import { Cmd, JSPlugin, Tab, interfaces, PluginConfig, Config } from '@ccms/plugin'
|
||||||
|
import { WebSocket } from '@ccms/websocket'
|
||||||
|
|
||||||
|
const defaultConfig = {
|
||||||
|
address: '',
|
||||||
|
token: ''
|
||||||
|
}
|
||||||
|
//https://github3.mk-proxy.ml/-----https://github.com/Mrs4s/go-cqhttp/releases/download/v0.9.34/go-cqhttp-v0.9.34-linux-amd64
|
||||||
|
@JSPlugin({ version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
|
export class MiaoRobot extends interfaces.Plugin {
|
||||||
|
@Autowired()
|
||||||
|
private server: server.Server
|
||||||
|
|
||||||
|
private client: WebSocket
|
||||||
|
|
||||||
|
@Config()
|
||||||
|
private config: PluginConfig & typeof defaultConfig = defaultConfig
|
||||||
|
|
||||||
|
load() {
|
||||||
|
}
|
||||||
|
|
||||||
|
private downloadRobot() {
|
||||||
|
//https://api.github.com/repos/Mrs4s/go-cqhttp/releases?per_page=1&page=1
|
||||||
|
}
|
||||||
|
|
||||||
|
enable() {
|
||||||
|
}
|
||||||
|
|
||||||
|
disable() {
|
||||||
|
this.cmdclose(this.server.getConsoleSender())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Cmd({ autoMain: true })
|
||||||
|
mbot() { }
|
||||||
|
|
||||||
|
cmdconnect(sender: org.bukkit.entity.Player, address: string = this.config.address, token: string = this.config.token) {
|
||||||
|
if (!address || !token) {
|
||||||
|
return this.logger.sender(sender, '§4错误 请配置服务器地址和Token!')
|
||||||
|
}
|
||||||
|
this.cmdclose(sender)
|
||||||
|
try {
|
||||||
|
this.client = new WebSocket(address, '', { Authorization: `Bearer ${token}` })
|
||||||
|
this.initRobot(this.client)
|
||||||
|
} catch (error) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private initRobot(client: WebSocket) {
|
||||||
|
client.onopen = () => {
|
||||||
|
this.logger.console(`§3连接到 §b${client.url} §a成功!`)
|
||||||
|
}
|
||||||
|
client.onmessage = (event) => {
|
||||||
|
let messageEvent = JSON.parse(event.data)
|
||||||
|
switch (messageEvent.post_type) {
|
||||||
|
case "message":
|
||||||
|
this.logger.console(`§6接收到 §3群 §b${messageEvent.group_id} §2成员 §a${messageEvent.sender.nickname} §6的消息: §r${messageEvent.message}`)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
client.onclose = (event) => {
|
||||||
|
this.logger.console(`§4连接已断开 §6Code: §3${event.code} §6原因: §c${event.reason}!`)
|
||||||
|
}
|
||||||
|
client.onerror = (event) => {
|
||||||
|
this.logger.console(`§4发生错误: §r${event.error}`)
|
||||||
|
console.ex(event.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdclose(sender: org.bukkit.entity.Player) {
|
||||||
|
if (this.client && this.client.readyState != WebSocket.CLOSED) {
|
||||||
|
this.client.close(0, 'plugin close socket')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdsend(sender: org.bukkit.entity.Player, text: string) {
|
||||||
|
if (this.client) {
|
||||||
|
this.client.send(text)
|
||||||
|
this.logger.sender(sender, '§a发送成功!')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Tab()
|
||||||
|
tabmbot(_sender: any, _command: string, _args: string[]) {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,12 +11,14 @@ let help = [
|
|||||||
'§6========= §6[§aMiaoScriptPackageManager§6] 帮助 §aBy §bMiaoWoo §6=========',
|
'§6========= §6[§aMiaoScriptPackageManager§6] 帮助 §aBy §bMiaoWoo §6=========',
|
||||||
'§6/mspm §ainstall §e<插件名称> §6- §3安装仓库插件',
|
'§6/mspm §ainstall §e<插件名称> §6- §3安装仓库插件',
|
||||||
'§6/mspm §aload §e<插件名称> §6- §3安装本地插件',
|
'§6/mspm §aload §e<插件名称> §6- §3安装本地插件',
|
||||||
'§6/mspm §aunload §e<插件名称> §6- §3卸载已安装插件',
|
'§6/mspm §cunload §e<插件名称> §6- §3卸载已安装插件',
|
||||||
'§6/mspm §areload §e<插件名称> §6- §3重载已安装插件(无名称则重载自身)',
|
'§6/mspm §areload §e<插件名称> §6- §3重载已安装插件(无名称则重载自身)',
|
||||||
|
'§6/mspm §cdelete §e<插件名称> §6- §3删除已安装插件',
|
||||||
'§6/mspm §alist [i] §6- §3列出仓库插件[已安装的插件]',
|
'§6/mspm §alist [i] §6- §3列出仓库插件[已安装的插件]',
|
||||||
'§6/mspm §aupdate §e[插件名称] §6- §3更新插件(无名称则更新源)',
|
'§6/mspm §aupdate §e[插件名称] §6- §3更新插件(无名称则更新源)',
|
||||||
'§6/mspm §aupgrade §e[插件名称] §6- §3升级插件/框架(§4无名称则升级框架§3)',
|
'§6/mspm §aupgrade §e[插件名称|system] §6- §3升级插件/§4框架(§csystem§3)',
|
||||||
'§6/mspm §arun §e<JS代码> §6- §3运行JS代码',
|
'§6/mspm §arun §e[插件名称] §3<JS代码> §6- §3运行JS代码',
|
||||||
|
'§6/mspm §aprun §e<JS代码> §6- §3运行JS代码',
|
||||||
'§6/mspm §adeploy §e<插件名称> §6- §3发布插件',
|
'§6/mspm §adeploy §e<插件名称> §6- §3发布插件',
|
||||||
'§6/mspm §crestart §6- §4重启MiaoScript脚本引擎'
|
'§6/mspm §crestart §6- §4重启MiaoScript脚本引擎'
|
||||||
]
|
]
|
||||||
@@ -43,7 +45,7 @@ let langMap = {
|
|||||||
'plugin.name.empty': '§c请输入插件名称!',
|
'plugin.name.empty': '§c请输入插件名称!',
|
||||||
'cloud.update.finish': '§6成功从 §aMiaoScriptPackageCenter §6获取到 §a{length} §6个插件!',
|
'cloud.update.finish': '§6成功从 §aMiaoScriptPackageCenter §6获取到 §a{length} §6个插件!',
|
||||||
'cloud.not.exists': '§6当前 §aMiaoScriptPackageCenter §c不存在 §a{name} §c插件!',
|
'cloud.not.exists': '§6当前 §aMiaoScriptPackageCenter §c不存在 §a{name} §c插件!',
|
||||||
'cloud.update.exists': '§6插件 §b{name} §a发现新版本 §3{new_version} §6当前版本 §3{old_version}!',
|
'cloud.update.exists': '§6插件 §b{name} §6版本 §3{old_version} §a发现更新 §3{new_version} §r{changelog}§6!',
|
||||||
'download.start': '§6开始下载插件: §b{name} §6版本 §3{version}',
|
'download.start': '§6开始下载插件: §b{name} §6版本 §3{version}',
|
||||||
'download.url': '§6插件下载地址: §b{url}',
|
'download.url': '§6插件下载地址: §b{url}',
|
||||||
'download.finish': '§6插件 §b{name} §6版本 §3{version} §a下载完毕 开始加载 ...',
|
'download.finish': '§6插件 §b{name} §6版本 §3{version} §a下载完毕 开始加载 ...',
|
||||||
@@ -105,7 +107,7 @@ class SpongeFakeSender extends FakeSender {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@JSPlugin({ prefix: 'PM', version: '1.3.1', author: 'MiaoWoo', source: __filename })
|
@JSPlugin({ prefix: 'PM', version: '1.4.0', author: 'MiaoWoo', source: __filename })
|
||||||
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||||
@Autowired()
|
@Autowired()
|
||||||
private pluginManager: pluginApi.PluginManager
|
private pluginManager: pluginApi.PluginManager
|
||||||
@@ -132,6 +134,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
public serverName: string
|
public serverName: string
|
||||||
private translate: Translate
|
private translate: Translate
|
||||||
private channelOff: { off: () => void }
|
private channelOff: { off: () => void }
|
||||||
|
private subCommandCache = []
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
this.translate = new Translate({
|
this.translate = new Translate({
|
||||||
@@ -139,6 +142,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
fallbackMap
|
fallbackMap
|
||||||
})
|
})
|
||||||
this.updateRepo(this.server.getConsoleSender())
|
this.updateRepo(this.server.getConsoleSender())
|
||||||
|
this.subCommandCache = Object.keys(this).filter(c => c.startsWith('cmd') && typeof this[c] == "function")
|
||||||
}
|
}
|
||||||
|
|
||||||
@enable({ servers: [constants.ServerType.Bukkit, constants.ServerType.Sponge] })
|
@enable({ servers: [constants.ServerType.Bukkit, constants.ServerType.Sponge] })
|
||||||
@@ -329,6 +333,8 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
try {
|
try {
|
||||||
this.i18n(sender, 'upgrade.start')
|
this.i18n(sender, 'upgrade.start')
|
||||||
base.delete(enginePath)
|
base.delete(enginePath)
|
||||||
|
// @ts-ignore
|
||||||
|
require.setUpgradeMode?.(true)
|
||||||
this.cmdrestart(sender)
|
this.cmdrestart(sender)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
if (global.debug) {
|
if (global.debug) {
|
||||||
@@ -356,6 +362,15 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cmddelete(sender: any, name: string) {
|
||||||
|
if (this.checkPlugin(sender, name)) {
|
||||||
|
let plugin = this.pluginManager.getPlugins().get(name)
|
||||||
|
this.i18n(sender, 'plugin.delete.start', { name, version: plugin.description.version })
|
||||||
|
base.delete(plugin.description.source)
|
||||||
|
this.i18n(sender, 'plugin.delete.finish', { name, version: plugin.description.version })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
cmdreload(sender: any, name: string) {
|
cmdreload(sender: any, name: string) {
|
||||||
name = name || this.description.name
|
name = name || this.description.name
|
||||||
this.reload(sender, name)
|
this.reload(sender, name)
|
||||||
@@ -383,7 +398,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cmdrestart(sender: any) {
|
cmdrestart(sender: any) {
|
||||||
setTimeout(() => {
|
this.taskManager.callSyncMethod(() => {
|
||||||
if (this.serverType === "sponge") {
|
if (this.serverType === "sponge") {
|
||||||
this.server.dispatchConsoleCommand('sponge plugins reload')
|
this.server.dispatchConsoleCommand('sponge plugins reload')
|
||||||
return
|
return
|
||||||
@@ -392,13 +407,16 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
this.logger.sender(sender, '§6Reloading §3MiaoScript Engine...')
|
this.logger.sender(sender, '§6Reloading §3MiaoScript Engine...')
|
||||||
ScriptEngineContextHolder.disableEngine()
|
ScriptEngineContextHolder.disableEngine()
|
||||||
Packages.java.lang.System.gc()
|
Packages.java.lang.System.gc()
|
||||||
|
if (ScriptEngineContextHolder.loadEngine) {
|
||||||
|
ScriptEngineContextHolder.loadEngine()
|
||||||
|
}
|
||||||
ScriptEngineContextHolder.enableEngine()
|
ScriptEngineContextHolder.enableEngine()
|
||||||
this.logger.sender(sender, '§3MiaoScript Engine §6Reload §aSuccessful...')
|
this.logger.sender(sender, '§3MiaoScript Engine §6Reload §aSuccessful...')
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
this.logger.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex)
|
this.logger.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex)
|
||||||
this.logger.sender(sender, this.logger.stack(ex))
|
this.logger.sender(sender, this.logger.stack(ex))
|
||||||
}
|
}
|
||||||
}, 0)
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdrun(sender: any, ...args: any[]) {
|
cmdrun(sender: any, ...args: any[]) {
|
||||||
@@ -477,7 +495,7 @@ return eval(${JSON.stringify(code)});`)
|
|||||||
|
|
||||||
@Tab({ alias: ['gmspm', 'bungeemspm'] })
|
@Tab({ alias: ['gmspm', 'bungeemspm'] })
|
||||||
tabmspm(_sender: any, _command: any, args: string | any[]) {
|
tabmspm(_sender: any, _command: any, args: string | any[]) {
|
||||||
if (args.length === 1) { return ['list', 'install', 'update', 'upgrade', 'reload', 'restart', 'run', 'prun', 'sudo', 'help', 'create', 'deploy'] }
|
if (args.length === 1) { return ['list', 'install', 'update', 'load', 'unload', 'upgrade', 'reload', 'restart', 'run', 'prun', 'sudo', 'help', 'create', 'deploy'] }
|
||||||
if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
switch (args[0]) {
|
switch (args[0]) {
|
||||||
case "list":
|
case "list":
|
||||||
@@ -514,7 +532,12 @@ return eval(${JSON.stringify(code)});`)
|
|||||||
let cloudPlugin = this.packageCache[p.description.name]
|
let cloudPlugin = this.packageCache[p.description.name]
|
||||||
//§6插件名称: §b{name}\n§6版本: §a{version}\n§6作者: §3{author}\§6更新时间: §9{updated_at}
|
//§6插件名称: §b{name}\n§6版本: §a{version}\n§6作者: §3{author}\§6更新时间: §9{updated_at}
|
||||||
if (cloudPlugin && cloudPlugin.version != p.description.version) {
|
if (cloudPlugin && cloudPlugin.version != p.description.version) {
|
||||||
this.i18n(sender, 'cloud.update.exists', { name: p.description.name, new_version: cloudPlugin.version, old_version: p.description.version })
|
this.i18n(sender, 'cloud.update.exists', {
|
||||||
|
name: p.description.name,
|
||||||
|
new_version: cloudPlugin.version,
|
||||||
|
old_version: p.description.version,
|
||||||
|
changelog: cloudPlugin.changelog || ''
|
||||||
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}).async().submit()
|
}).async().submit()
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ export class MiaoSpring extends interfaces.Plugin {
|
|||||||
preHandle: (ctx: Context) => {
|
preHandle: (ctx: Context) => {
|
||||||
const index = foundMap.indexOf(ctx.request.getRequestURI())
|
const index = foundMap.indexOf(ctx.request.getRequestURI())
|
||||||
if (index != -1) {
|
if (index != -1) {
|
||||||
return this.ResponseEntity.status(this.HttpStatus.FOUND).header('Location', foundMap[index + 1]).build()
|
return this.ResponseEntity.status(org.springframework.http.HttpStatus.FOUND).header('Location', foundMap[index + 1]).build()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/ployfill",
|
"name": "@ccms/polyfill",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript ployfill package",
|
"description": "MiaoScript polyfill package",
|
||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
@@ -14,14 +14,14 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/i18n": "^0.10.0",
|
"@ccms/i18n": "^0.14.1",
|
||||||
"@ccms/nodejs": "^0.10.0",
|
"@ccms/nodejs": "^0.14.0",
|
||||||
"core-js": "^3.6.5"
|
"core-js": "^3.9.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.10.0",
|
"@ccms/nashorn": "^0.14.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
/// <reference types="@ccms/nashorn" />
|
||||||
import '@ccms/nodejs'
|
import '@ccms/nodejs'
|
||||||
import i18n from '@ccms/i18n'
|
import i18n from '@ccms/i18n'
|
||||||
let ployfillStartTime = new Date().getTime()
|
let polyfillStartTime = new Date().getTime()
|
||||||
i18n.initialize()
|
i18n.initialize()
|
||||||
console.i18n("ms.ployfill.initialize")
|
console.i18n("ms.polyfill.initialize")
|
||||||
require('./es5-ext')
|
import './es5-ext'
|
||||||
require('./node-shim')
|
import './node-shim'
|
||||||
require('core-js')
|
import 'core-js'
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
process.on('exit', () => require.disable())
|
process.on('exit', () => require.disable())
|
||||||
global.setGlobal('Proxy', require('./proxy').Proxy)
|
global.setGlobal('Proxy', require('./proxy').Proxy)
|
||||||
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
|
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
|
||||||
global.setGlobal('Blob', require('blob-polyfill').Blob)
|
global.setGlobal('Blob', require('blob-polyfill').Blob)
|
||||||
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 })
|
console.i18n("ms.polyfill.completed", { time: (new Date().getTime() - polyfillStartTime) / 1000 })
|
||||||
207
packages/polyfill/src/node-shim.ts
Normal file
207
packages/polyfill/src/node-shim.ts
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
import { EventEmitter } from 'events'
|
||||||
|
|
||||||
|
const System = Java.type('java.lang.System')
|
||||||
|
const Thread = Java.type('java.lang.Thread')
|
||||||
|
const InterruptedException = Java.type('java.lang.InterruptedException')
|
||||||
|
const ThreadGroup = Java.type("java.lang.ThreadGroup")
|
||||||
|
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||||
|
const Callable = Java.type('java.util.concurrent.Callable')
|
||||||
|
const ThreadFactory = Java.type("java.util.concurrent.ThreadFactory")
|
||||||
|
const TimeoutException = Java.type('java.util.concurrent.TimeoutException')
|
||||||
|
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
|
||||||
|
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
|
||||||
|
const TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||||
|
const DelayQueue = Java.type('java.util.concurrent.DelayQueue')
|
||||||
|
const JavaScriptTask = Java.type(base.getJavaScriptTaskClass().name)
|
||||||
|
|
||||||
|
const threadCount = new AtomicInteger(0)
|
||||||
|
const threadGroup = new ThreadGroup("@ccms/ployfill-micro-task")
|
||||||
|
const microTaskPool = new ThreadPoolExecutor(
|
||||||
|
100, 200, 60, TimeUnit.SECONDS,
|
||||||
|
new LinkedBlockingQueue(300),
|
||||||
|
new ThreadFactory((run: any) => new Thread(threadGroup, run, "@ccms/micro-task-" + threadCount.incrementAndGet()))
|
||||||
|
)
|
||||||
|
class Process extends EventEmitter {
|
||||||
|
env = {
|
||||||
|
__noSuchProperty__: (prop) => {
|
||||||
|
return System.getenv(prop)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
platform = System.getProperty("os.name")
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
this.on('exit', () => {
|
||||||
|
console.log(`await microTaskPool termination! queueTask: ${microTaskPool.shutdownNow().size()} remainTask: ${threadGroup.activeCount()}`)
|
||||||
|
microTaskPool.awaitTermination(3000, TimeUnit.MILLISECONDS)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void) {
|
||||||
|
return super.on(event, (...args) => {
|
||||||
|
try {
|
||||||
|
listener(...args)
|
||||||
|
} catch (error) {
|
||||||
|
try {
|
||||||
|
super.emit('error', error)
|
||||||
|
} catch (error) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
nextTick(func: Function) {
|
||||||
|
microTaskPool.execute(func)
|
||||||
|
}
|
||||||
|
exit(code: number) {
|
||||||
|
console.log(`process exit by code ${code}!`)
|
||||||
|
this.emit('exit', code)
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return "[object process]"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class EventLoop {
|
||||||
|
private eventLoopMainThread = undefined
|
||||||
|
private eventLoopTaskQueue = new DelayQueue()
|
||||||
|
private taskExecTimeout = 3
|
||||||
|
private fixedThreadPool = undefined
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.taskExecTimeout = parseInt(process.env.MS_NODE_EVENT_LOOP_TIMEOUT) || 3
|
||||||
|
this.fixedThreadPool = new ThreadPoolExecutor(
|
||||||
|
1, 1, 0, TimeUnit.SECONDS,
|
||||||
|
new LinkedBlockingQueue(300),
|
||||||
|
new ThreadFactory((run: any) => {
|
||||||
|
let thread = new Thread(run, "@ccms/node-shim/event-loop-exec")
|
||||||
|
thread.setDaemon(true)
|
||||||
|
return thread
|
||||||
|
}))
|
||||||
|
this.eventLoopMainThread = new Thread(() => {
|
||||||
|
let task = undefined
|
||||||
|
try {
|
||||||
|
while (!this.eventLoopMainThread.isInterrupted()) {
|
||||||
|
task = this.eventLoopTaskQueue.take()
|
||||||
|
try {
|
||||||
|
task.getTask()()
|
||||||
|
} catch (cause) {
|
||||||
|
try {
|
||||||
|
process.emit('error', cause)
|
||||||
|
} catch (error) {
|
||||||
|
console.error(cause)
|
||||||
|
console.ex(cause)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.log(`EventLoop Thread isInterrupted exit! remainTask: ${this.eventLoopTaskQueue.size()}`)
|
||||||
|
this.eventLoopTaskQueue.clear()
|
||||||
|
this.eventLoopTaskQueue = undefined
|
||||||
|
this.timeoutCount = undefined
|
||||||
|
this.timeoutTasks = undefined
|
||||||
|
this.intervalCount = undefined
|
||||||
|
this.intervalTasks = undefined
|
||||||
|
this.eventLoopMainThread = undefined
|
||||||
|
}
|
||||||
|
}, "@ccms/node-shim/event-loop")
|
||||||
|
this.eventLoopMainThread.setDaemon(true)
|
||||||
|
process.on('exit', () => {
|
||||||
|
this.eventLoopMainThread.interrupt()
|
||||||
|
this.fixedThreadPool.shutdownNow()
|
||||||
|
console.log(`await fixedThreadPool termination!`)
|
||||||
|
this.fixedThreadPool.awaitTermination(3000, TimeUnit.MILLISECONDS)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
startEventLoop() {
|
||||||
|
this.eventLoopMainThread.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private putDelayTask(id: number, callback: Function, ms: number) {
|
||||||
|
this.eventLoopTaskQueue.put(new JavaScriptTask(id, callback, ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
private limitTimeTask(name: string, callback: Function, ...args: any[]) {
|
||||||
|
if (!callback) {
|
||||||
|
throw new Error(`task ${name} callback function can't be null!`)
|
||||||
|
}
|
||||||
|
if (this.fixedThreadPool.isShutdown()) { return console.warn(`FixedThreadPool isTerminated! ignore Task ${name}!`) }
|
||||||
|
try {
|
||||||
|
this.fixedThreadPool.submit(new Callable({
|
||||||
|
call: () => {
|
||||||
|
try {
|
||||||
|
callback.apply(undefined, args)
|
||||||
|
} catch (cause) {
|
||||||
|
cause = cause.getCause && cause.getCause() || cause
|
||||||
|
try {
|
||||||
|
process.emit('error', cause)
|
||||||
|
} catch (error) {
|
||||||
|
console.error(cause)
|
||||||
|
console.ex(cause)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})).get(this.taskExecTimeout, TimeUnit.SECONDS)
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof InterruptedException) {
|
||||||
|
return console.warn(`FixedThreadPool isInterrupted exit! Task ${name} exec exit!`)
|
||||||
|
}
|
||||||
|
if (error instanceof TimeoutException) {
|
||||||
|
return console.warn(`Task ${name} => ${callback} exec time greater than ${this.taskExecTimeout}s!`)
|
||||||
|
}
|
||||||
|
throw error.getCause && error.getCause() || error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private timeoutCount = new AtomicInteger(0)
|
||||||
|
private timeoutTasks = []
|
||||||
|
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]) {
|
||||||
|
let taskId = this.timeoutCount.incrementAndGet()
|
||||||
|
this.timeoutTasks[taskId] = callback
|
||||||
|
console.trace(`create setTimeout task ${taskId} => ${callback}`)
|
||||||
|
this.putDelayTask(taskId, () => {
|
||||||
|
if (this.timeoutTasks[taskId]) {
|
||||||
|
this.limitTimeTask(`setTimeout-${taskId}`, callback, ...args)
|
||||||
|
} else {
|
||||||
|
console.trace(`ignore setTimeout ${ms}ms task ${taskId} because it's cancelled!`)
|
||||||
|
}
|
||||||
|
}, ms)
|
||||||
|
return taskId
|
||||||
|
}
|
||||||
|
clearTimeout(taskId: number) {
|
||||||
|
delete this.timeoutTasks[taskId]
|
||||||
|
}
|
||||||
|
|
||||||
|
private intervalCount = new AtomicInteger(0)
|
||||||
|
private intervalTasks = []
|
||||||
|
setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]) {
|
||||||
|
let taskId = this.intervalCount.incrementAndGet()
|
||||||
|
this.intervalTasks[taskId] = callback
|
||||||
|
console.trace(`create setInterval ${ms}ms task ${taskId} => ${callback}`)
|
||||||
|
let intervalTask = () => {
|
||||||
|
if (this.intervalTasks[taskId]) {
|
||||||
|
this.limitTimeTask(`setInterval-${taskId}`, callback, ...args)
|
||||||
|
this.putDelayTask(taskId, intervalTask, ms)
|
||||||
|
} else {
|
||||||
|
console.trace(`ignore setInterval task ${taskId} because it's cancelled!`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.putDelayTask(taskId, intervalTask, ms)
|
||||||
|
return taskId
|
||||||
|
}
|
||||||
|
clearInterval(taskId: number) {
|
||||||
|
delete this.intervalTasks[taskId]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
global.setGlobal('process', new Process(), {})
|
||||||
|
Object.defineProperty(process, require('core-js/es/symbol/to-string-tag'), { value: '[object process]' })
|
||||||
|
const eventLoop = new EventLoop()
|
||||||
|
Object.defineProperty(process, 'eventLoop', { value: eventLoop })
|
||||||
|
eventLoop.startEventLoop()
|
||||||
|
global.setGlobal('queueMicrotask', (func: any) => microTaskPool.execute(func), {})
|
||||||
|
global.setGlobal('setTimeout', eventLoop.setTimeout.bind(eventLoop), {})
|
||||||
|
global.setGlobal('clearTimeout', eventLoop.clearTimeout.bind(eventLoop), {})
|
||||||
|
global.setGlobal('setInterval', eventLoop.setInterval.bind(eventLoop), {})
|
||||||
|
global.setGlobal('clearInterval', eventLoop.clearInterval.bind(eventLoop), {})
|
||||||
|
global.setGlobal('setImmediate', (callback: (...args: any[]) => void, ...args: any[]) => eventLoop.setTimeout(callback, 0, ...args), { writable: true })
|
||||||
|
global.setGlobal('clearImmediate ', eventLoop.clearTimeout.bind(eventLoop), { writable: true })
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ProxyHandle } from '@ccms/nashorn'
|
import type { ProxyHandle } from '@ccms/nashorn'
|
||||||
|
|
||||||
// Nashorn JSAdapter See https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-JSAdapterconstructor
|
// Nashorn JSAdapter See https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-JSAdapterconstructor
|
||||||
let createProxy = eval(`
|
let createProxy = eval(`
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/protocol",
|
"name": "@ccms/protocol",
|
||||||
"version": "0.10.0",
|
"version": "0.14.0",
|
||||||
"description": "MiaoScript protocol package",
|
"description": "MiaoScript protocol package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,6 +22,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/sponge",
|
"name": "@ccms/sponge",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/sponge-api": "^0.0.3",
|
"@javatypes/sponge-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/common": "^0.10.0",
|
"@ccms/common": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0"
|
"@ccms/container": "^0.14.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,12 @@ import './chat'
|
|||||||
import './task'
|
import './task'
|
||||||
import './event'
|
import './event'
|
||||||
import './server'
|
import './server'
|
||||||
|
import { SpongeNativePluginManager } from './plugin'
|
||||||
import './command'
|
import './command'
|
||||||
import './channel'
|
import './channel'
|
||||||
|
import './particle'
|
||||||
|
|
||||||
export default function SpongeImpl(container: Container) {
|
export default function SpongeImpl(container: Container) {
|
||||||
container.bind(server.Console).toConstantValue(SpongeConsole)
|
container.bind(server.Console).toConstantValue(SpongeConsole)
|
||||||
|
container.rebind(server.NativePluginManager).toConstantValue(new SpongeNativePluginManager())
|
||||||
}
|
}
|
||||||
|
|||||||
32
packages/sponge/src/particle.ts
Normal file
32
packages/sponge/src/particle.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { provideSingleton } from '@ccms/container'
|
||||||
|
import { particle, plugin } from '@ccms/api'
|
||||||
|
|
||||||
|
@provideSingleton(particle.ParticleManager)
|
||||||
|
export class SpongeParticleManager extends particle.ParticleManager {
|
||||||
|
private globalSpawner = new SpongeParticleSpawner()
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
particle.ParticleManager.globalSpawner = this.globalSpawner
|
||||||
|
}
|
||||||
|
protected getGlobalSpawner() {
|
||||||
|
return this.globalSpawner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export class SpongeParticleSpawner extends particle.ParticleSpawner {
|
||||||
|
spawnParticle(location: org.spongepowered.api.world.Location<any>, particle: any, count: number = 1) {
|
||||||
|
location.getPosition()
|
||||||
|
// location.getWorld().spawnParticle(particle, location, count)
|
||||||
|
}
|
||||||
|
spawn(location: any, particle: particle.Particle) {
|
||||||
|
location.getWorld().spawnParticle(
|
||||||
|
particle.getParticle(),
|
||||||
|
location,
|
||||||
|
particle.getCount(),
|
||||||
|
particle.getOffsetX(),
|
||||||
|
particle.getOffsetY(),
|
||||||
|
particle.getOffsetZ(),
|
||||||
|
particle.getExtra(),
|
||||||
|
particle.getData()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
12
packages/sponge/src/plugin.ts
Normal file
12
packages/sponge/src/plugin.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { server } from '@ccms/api'
|
||||||
|
|
||||||
|
const Sponge = org.spongepowered.api.Sponge
|
||||||
|
|
||||||
|
export class SpongeNativePluginManager extends server.NativePluginManager {
|
||||||
|
has(name: string) {
|
||||||
|
return !!this.get(name)
|
||||||
|
}
|
||||||
|
get(name: string) {
|
||||||
|
return Sponge.getPluginManager().getPlugin(name).orElse(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,6 @@ import { provideSingleton } from '@ccms/container'
|
|||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
const Sponge = org.spongepowered.api.Sponge
|
const Sponge = org.spongepowered.api.Sponge
|
||||||
const TextSerializers = org.spongepowered.api.text.serializer.TextSerializers
|
|
||||||
const File = Java.type("java.io.File")
|
const File = Java.type("java.io.File")
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
@@ -35,10 +34,10 @@ export class SpongeServer extends server.ReflectServer {
|
|||||||
if (typeof sender === 'string') {
|
if (typeof sender === 'string') {
|
||||||
sender = this.getPlayer(sender)
|
sender = this.getPlayer(sender)
|
||||||
}
|
}
|
||||||
return Sponge.getCommandManager().process(sender, command).getSuccessCount().get() != 0
|
return Sponge.getCommandManager().process(sender, command).getSuccessCount().orElse(0) != 0
|
||||||
}
|
}
|
||||||
dispatchConsoleCommand(command: string): boolean {
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getSuccessCount().get() != 0
|
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getSuccessCount().orElse(0) != 0
|
||||||
}
|
}
|
||||||
getPluginsFolder(): string {
|
getPluginsFolder(): string {
|
||||||
return this.pluginsFolder
|
return this.pluginsFolder
|
||||||
|
|||||||
@@ -9,24 +9,21 @@ const TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class SpongeTaskManager extends task.TaskManager {
|
export class SpongeTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
|
||||||
private pluginInstance: any
|
|
||||||
private syncExecutor: any
|
private syncExecutor: any
|
||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
initialize() {
|
initialize() {
|
||||||
this.syncExecutor = Sponge.getScheduler().createSyncExecutor(this.pluginInstance)
|
this.syncExecutor = Sponge.getScheduler().createSyncExecutor(base.getInstance())
|
||||||
}
|
}
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
return new SpongeTask(this.pluginInstance, func)
|
return new SpongeTask(owner, func, id)
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
// @ts-ignore
|
return this.syncExecutor.execute(() => func())
|
||||||
return this.syncExecutor.schedule(new Callable({ call: () => func() }), java.lang.Long.valueOf(0), TimeUnit.NANOSECONDS).get()
|
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
Sponge.getScheduler().getScheduledTasks(this.pluginInstance).forEach((task: task.Cancelable) => task.cancel())
|
Sponge.getScheduler().getScheduledTasks(base.getInstance()).forEach((task: task.Cancelable) => task.cancel())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +33,6 @@ export class SpongeTask extends task.Task {
|
|||||||
if (this.isAsync) { run.async() }
|
if (this.isAsync) { run.async() }
|
||||||
if (this.laterTime) { run.delayTicks(this.laterTime) }
|
if (this.laterTime) { run.delayTicks(this.laterTime) }
|
||||||
if (this.interval) { run.intervalTicks(this.interval) }
|
if (this.interval) { run.intervalTicks(this.interval) }
|
||||||
return run.submit(this.plugin)
|
return run.submit(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/spring",
|
"name": "@ccms/spring",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript spring package",
|
"description": "MiaoScript spring package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,12 +21,12 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/common": "^0.10.0",
|
"@ccms/common": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0",
|
"@ccms/container": "^0.14.0",
|
||||||
"@ccms/database": "^0.10.0"
|
"@ccms/database": "^0.14.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { task, plugin } from '@ccms/api'
|
|||||||
import { inject, provideSingleton } from '@ccms/container'
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
import thread_pool from '@ccms/common/dist/thread-pool'
|
import thread_pool from '@ccms/common/dist/thread-pool'
|
||||||
|
|
||||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
|
||||||
const AtomicBoolean = Java.type("java.util.concurrent.atomic.AtomicBoolean")
|
const AtomicBoolean = Java.type("java.util.concurrent.atomic.AtomicBoolean")
|
||||||
const Thread = Java.type('java.lang.Thread')
|
const Thread = Java.type('java.lang.Thread')
|
||||||
|
|
||||||
@@ -11,21 +10,19 @@ export class SpringTaskManager extends task.TaskManager {
|
|||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
|
|
||||||
private taskId: any
|
|
||||||
private tasks: { [s: string]: task.Cancelable }
|
private tasks: { [s: string]: task.Cancelable }
|
||||||
private executor: java.util.concurrent.ThreadPoolExecutor
|
private executor: java.util.concurrent.ThreadPoolExecutor
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super()
|
super()
|
||||||
this.taskId = new AtomicInteger(0)
|
|
||||||
this.tasks = {}
|
this.tasks = {}
|
||||||
this.executor = thread_pool.create({
|
this.executor = thread_pool.create({
|
||||||
groupName: '@ccms/spring'
|
groupName: '@ccms/spring'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
return new SpringTask(this.pluginInstance, func, this)
|
return new SpringTask(owner, func, id, this)
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func()
|
return func()
|
||||||
@@ -51,8 +48,8 @@ export class SpringTask extends task.Task {
|
|||||||
private taskManager: SpringTaskManager
|
private taskManager: SpringTaskManager
|
||||||
private running = new AtomicBoolean(true)
|
private running = new AtomicBoolean(true)
|
||||||
|
|
||||||
constructor(plugin: any, func: Function, taskManager: SpringTaskManager) {
|
constructor(owner: plugin.Plugin, func: Function, id: number, taskManager: SpringTaskManager) {
|
||||||
super(plugin, func)
|
super(owner, func, id)
|
||||||
this.id = taskManager.nextId()
|
this.id = taskManager.nextId()
|
||||||
this.taskManager = taskManager
|
this.taskManager = taskManager
|
||||||
}
|
}
|
||||||
@@ -83,19 +80,16 @@ export class SpringTask extends task.Task {
|
|||||||
this.cancel()
|
this.cancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
cancel0(): any {
|
cancel0() {
|
||||||
var wasRunning = this.running.getAndSet(false)
|
var wasRunning = this.running.getAndSet(false)
|
||||||
if (wasRunning) {
|
if (wasRunning) {
|
||||||
this.taskManager.cancel(this.id)
|
this.taskManager.cancel(this.id)
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
submit0(...args: any[]) {
|
submit0(...args: any[]) {
|
||||||
this.taskManager.submit(this.id, this, () => this.run(...args))
|
this.taskManager.submit(this.id, this, () => this.run(...args))
|
||||||
return {
|
|
||||||
cancel: () => {
|
|
||||||
return this.cancel0()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/web",
|
"name": "@ccms/web",
|
||||||
"version": "0.10.0",
|
"version": "0.14.1",
|
||||||
"description": "MiaoScript web package",
|
"description": "MiaoScript web package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -26,10 +26,10 @@
|
|||||||
"@javatypes/tomcat": "^0.0.3",
|
"@javatypes/tomcat": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.10.0",
|
"@ccms/api": "^0.14.1",
|
||||||
"@ccms/container": "^0.10.0"
|
"@ccms/container": "^0.14.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/websocket",
|
"name": "@ccms/websocket",
|
||||||
"version": "0.10.0",
|
"version": "0.14.0",
|
||||||
"description": "MiaoScript websocket package",
|
"description": "MiaoScript websocket package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,10 +19,10 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.10.0",
|
"@ccms/nashorn": "^0.14.0",
|
||||||
"@javatypes/tomcat-websocket-api": "^0.0.3",
|
"@javatypes/tomcat-websocket-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
98
packages/websocket/src/client/index.ts
Normal file
98
packages/websocket/src/client/index.ts
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
|
||||||
|
import { EventEmitter } from 'events'
|
||||||
|
import { Transport } from './transport'
|
||||||
|
import { CloseEvent, ErrorEvent, Event, EventType, MessageEvent, WebSocketHeader } from './interface'
|
||||||
|
|
||||||
|
export class WebSocketManager {
|
||||||
|
private clients = new Map<string, WebSocket>()
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
process.on('exit', () => {
|
||||||
|
for (const client of this.clients.values()) {
|
||||||
|
client.close(0, `client ${client.id} close connect`)
|
||||||
|
}
|
||||||
|
this.clients.clear()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
add(client: WebSocket) {
|
||||||
|
this.clients.set(client.id, client)
|
||||||
|
}
|
||||||
|
del(client: WebSocket) {
|
||||||
|
this.clients.delete(client.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const managers = new WebSocketManager()
|
||||||
|
|
||||||
|
export class WebSocket extends EventEmitter {
|
||||||
|
public static CONNECTING = 0
|
||||||
|
public static OPEN = 1
|
||||||
|
public static CLOSING = 2
|
||||||
|
public static CLOSED = 3
|
||||||
|
public binaryType: 'blob' | 'arraybuffer'
|
||||||
|
|
||||||
|
protected _url: string
|
||||||
|
protected _headers: WebSocketHeader = {}
|
||||||
|
|
||||||
|
private client: Transport
|
||||||
|
|
||||||
|
constructor(url: string, subProtocol: string = '', headers: WebSocketHeader = {}) {
|
||||||
|
super()
|
||||||
|
this._url = url
|
||||||
|
this._headers = headers
|
||||||
|
try {
|
||||||
|
let TransportImpl = require('./netty').NettyWebSocket
|
||||||
|
this.client = new TransportImpl(url, subProtocol, headers)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('create websocket impl error: ' + error)
|
||||||
|
console.ex(error)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.client.on('open', (event) => {
|
||||||
|
this.onopen?.(event)
|
||||||
|
managers.add(this)
|
||||||
|
})
|
||||||
|
this.client.on('message', (event) => this.onmessage?.(event))
|
||||||
|
this.client.on('close', (event) => {
|
||||||
|
this.onclose?.(event)
|
||||||
|
managers.del(this)
|
||||||
|
})
|
||||||
|
this.client.on('error', (event) => this.onerror?.(event))
|
||||||
|
setTimeout(() => this.client.connect(), 20)
|
||||||
|
}
|
||||||
|
get id() {
|
||||||
|
return this.client.id
|
||||||
|
}
|
||||||
|
get bufferedAmount() {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
get extensions() {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
get protocol() {
|
||||||
|
return this.client.protocol
|
||||||
|
}
|
||||||
|
get readyState() {
|
||||||
|
return this.client.readyStatus
|
||||||
|
}
|
||||||
|
get url() {
|
||||||
|
return this._url
|
||||||
|
}
|
||||||
|
public onopen: (event: Event) => void
|
||||||
|
public onmessage: (event: MessageEvent) => void
|
||||||
|
public onclose: (event: CloseEvent) => void
|
||||||
|
public onerror: (event: ErrorEvent) => void
|
||||||
|
|
||||||
|
addEventListener(event: EventType, callback: () => void) {
|
||||||
|
this[`on${event.toLowerCase()}`] = callback
|
||||||
|
this.client.on(event, callback)
|
||||||
|
}
|
||||||
|
public send(data: any) {
|
||||||
|
this.client.send(data)
|
||||||
|
}
|
||||||
|
public close(code?: number, reason?: string) {
|
||||||
|
this.client.close(code, reason)
|
||||||
|
this.removeAllListeners()
|
||||||
|
}
|
||||||
|
}
|
||||||
27
packages/websocket/src/client/interface.ts
Normal file
27
packages/websocket/src/client/interface.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
|
||||||
|
export interface WebSocketHeader {
|
||||||
|
[key: string]: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EventType =
|
||||||
|
| 'close'
|
||||||
|
| 'error'
|
||||||
|
| 'message'
|
||||||
|
| 'open'
|
||||||
|
export interface Event {
|
||||||
|
|
||||||
|
}
|
||||||
|
export interface MessageEvent extends Event {
|
||||||
|
data: any
|
||||||
|
origin?: string
|
||||||
|
lastEventId?: string
|
||||||
|
source?: string
|
||||||
|
ports?: string
|
||||||
|
}
|
||||||
|
export interface ErrorEvent extends Event {
|
||||||
|
error: Error
|
||||||
|
}
|
||||||
|
export interface CloseEvent extends Event {
|
||||||
|
code: number
|
||||||
|
reason: string
|
||||||
|
}
|
||||||
24
packages/websocket/src/client/netty/adapter/handler.ts
Normal file
24
packages/websocket/src/client/netty/adapter/handler.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
||||||
|
export abstract class WebSocketClientHandlerAdapter {
|
||||||
|
private _Handler
|
||||||
|
constructor() {
|
||||||
|
let WebSocketClientHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
||||||
|
isSharable: this.isSharable.bind(this),
|
||||||
|
handlerAdded: this.handlerAdded.bind(this),
|
||||||
|
channelActive: this.channelActive.bind(this),
|
||||||
|
channelInactive: this.channelInactive.bind(this),
|
||||||
|
channelRead0: this.channelRead0.bind(this),
|
||||||
|
exceptionCaught: this.exceptionCaught.bind(this)
|
||||||
|
})
|
||||||
|
this._Handler = new WebSocketClientHandlerAdapterImpl()
|
||||||
|
}
|
||||||
|
abstract isSharable(): void
|
||||||
|
abstract handlerAdded(ctx: any): void
|
||||||
|
abstract channelActive(ctx: any): void
|
||||||
|
abstract channelInactive(ctx: any): void
|
||||||
|
abstract channelRead0(ctx: any, msg: any): void
|
||||||
|
abstract exceptionCaught(ctx: any, cause: Error): void
|
||||||
|
getHandler() {
|
||||||
|
return this._Handler
|
||||||
|
}
|
||||||
|
}
|
||||||
63
packages/websocket/src/client/netty/handler.ts
Normal file
63
packages/websocket/src/client/netty/handler.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import { EventEmitter } from 'events'
|
||||||
|
import { NettyWebSocket } from '.'
|
||||||
|
import { WebSocketClientHandlerAdapter } from './adapter/handler'
|
||||||
|
|
||||||
|
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
|
||||||
|
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
|
||||||
|
const CloseWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.CloseWebSocketFrame')
|
||||||
|
const FullHttpResponse = Java.type('io.netty.handler.codec.http.FullHttpResponse')
|
||||||
|
|
||||||
|
export class WebSocketClientHandler extends WebSocketClientHandlerAdapter {
|
||||||
|
public handshaker: any
|
||||||
|
public handshakeFuture: any//ChannelPromise
|
||||||
|
private client: NettyWebSocket
|
||||||
|
constructor(handshaker: any, client: NettyWebSocket) {
|
||||||
|
super()
|
||||||
|
this.handshaker = handshaker
|
||||||
|
this.client = client
|
||||||
|
}
|
||||||
|
isSharable() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
handlerAdded(ctx: any) {
|
||||||
|
console.trace(`${ctx} handlerAdded`)
|
||||||
|
this.handshakeFuture = ctx.newPromise()
|
||||||
|
}
|
||||||
|
channelActive(ctx: any) {
|
||||||
|
console.trace(`${ctx} channelActive`)
|
||||||
|
this.handshaker.handshake(ctx.channel())
|
||||||
|
}
|
||||||
|
channelInactive(ctx: any) {
|
||||||
|
console.trace(`${ctx} channelInactive`)
|
||||||
|
this.client.onclose({ code: 0, reason: 'server connection channel inactive!' })
|
||||||
|
}
|
||||||
|
channelRead0(ctx: any, msg: any) {
|
||||||
|
console.trace(`${ctx} channelRead0 ${msg}`)
|
||||||
|
let ch = ctx.channel()
|
||||||
|
if (!this.handshaker.isHandshakeComplete()) {
|
||||||
|
// web socket client connected
|
||||||
|
this.handshaker.finishHandshake(ch, msg)
|
||||||
|
this.handshakeFuture.setSuccess()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg instanceof FullHttpResponse) {
|
||||||
|
let response = msg
|
||||||
|
throw new Error(`Unexpected FullHttpResponse (getStatus=${response.getStatus()}, content=${response.content().toString(CharsetUtil.UTF_8)})`)
|
||||||
|
}
|
||||||
|
|
||||||
|
let frame = msg
|
||||||
|
if (frame instanceof TextWebSocketFrame) {
|
||||||
|
this.client.onmessage({ data: frame.text() })
|
||||||
|
} else if (frame instanceof CloseWebSocketFrame) {
|
||||||
|
this.client.onclose({ code: 0, reason: 'server send CloseWebSocketFrame!' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exceptionCaught(ctx: any, cause: Error) {
|
||||||
|
console.trace(`${ctx} exceptionCaught ${cause}`)
|
||||||
|
this.client.onerror({ error: cause })
|
||||||
|
if (!this.handshakeFuture.isDone()) {
|
||||||
|
this.handshakeFuture.setFailure(cause)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
88
packages/websocket/src/client/netty/index.ts
Normal file
88
packages/websocket/src/client/netty/index.ts
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
|
||||||
|
import { WebSocketHeader } from '../interface'
|
||||||
|
import { Transport } from '../transport'
|
||||||
|
import { WebSocketClientHandler } from './handler'
|
||||||
|
|
||||||
|
const URI = Java.type('java.net.URI')
|
||||||
|
const Epoll = Java.type('io.netty.channel.epoll.Epoll')
|
||||||
|
const Bootstrap = Java.type('io.netty.bootstrap.Bootstrap')
|
||||||
|
const ChannelFutureListener = Java.type('io.netty.channel.ChannelFutureListener')
|
||||||
|
|
||||||
|
const NioEventLoopGroup = Java.type('io.netty.channel.nio.NioEventLoopGroup')
|
||||||
|
const NioSocketChannel = Java.type('io.netty.channel.socket.nio.NioSocketChannel')
|
||||||
|
|
||||||
|
const EpollEventLoopGroup = Java.type('io.netty.channel.epoll.EpollEventLoopGroup')
|
||||||
|
const EpollSocketChannel = Java.type('io.netty.channel.epoll.EpollSocketChannel')
|
||||||
|
|
||||||
|
const WebSocketClientHandshakerFactory = Java.type('io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory')
|
||||||
|
const WebSocketVersion = Java.type('io.netty.handler.codec.http.websocketx.WebSocketVersion')
|
||||||
|
|
||||||
|
const HttpClientCodec = Java.type('io.netty.handler.codec.http.HttpClientCodec')
|
||||||
|
const HttpObjectAggregator = Java.type('io.netty.handler.codec.http.HttpObjectAggregator')
|
||||||
|
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
|
||||||
|
const CloseWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.CloseWebSocketFrame')
|
||||||
|
|
||||||
|
const ChannelInitializer = Java.type('io.netty.channel.ChannelInitializer')
|
||||||
|
const DefaultHttpHeaders = Java.type('io.netty.handler.codec.http.DefaultHttpHeaders')
|
||||||
|
|
||||||
|
const epull = Epoll.isAvailable()
|
||||||
|
const group = epull ? new EpollEventLoopGroup() : new NioEventLoopGroup()
|
||||||
|
const socketChannelClass = epull ? EpollSocketChannel.class : NioSocketChannel.class
|
||||||
|
process.on('exit', () => group.shutdownGracefully())
|
||||||
|
|
||||||
|
export class NettyWebSocket extends Transport {
|
||||||
|
private channel: any
|
||||||
|
private b = new Bootstrap();
|
||||||
|
|
||||||
|
constructor(url: string, subProtocol: string = '', headers: WebSocketHeader = {}) {
|
||||||
|
super(url, subProtocol, headers)
|
||||||
|
}
|
||||||
|
getId() {
|
||||||
|
return this.channel?.id() + ''
|
||||||
|
}
|
||||||
|
doConnect() {
|
||||||
|
let uri = URI.create(this._url)
|
||||||
|
let headers = new DefaultHttpHeaders()
|
||||||
|
for (const key of Object.getOwnPropertyNames(this._headers || {})) {
|
||||||
|
headers.add(key, this._headers[key])
|
||||||
|
}
|
||||||
|
// Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
|
||||||
|
// If you change it to V00, ping is not supported and remember to change
|
||||||
|
// HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
|
||||||
|
let handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
|
||||||
|
.newHandshaker(uri, WebSocketVersion.V13, null, false, headers), this)
|
||||||
|
this.b.group(group)
|
||||||
|
.channel(socketChannelClass)
|
||||||
|
.handler(new ChannelInitializer({
|
||||||
|
initChannel: (ch: any) => {
|
||||||
|
let pipeline = ch.pipeline()
|
||||||
|
pipeline.addLast("http-codec", new HttpClientCodec())
|
||||||
|
pipeline.addLast("aggregator", new HttpObjectAggregator(65536))
|
||||||
|
pipeline.addLast("websocket", handler.getHandler())
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
this.b.connect(uri.getHost(), uri.getPort()).addListener(new ChannelFutureListener((future: any) => {
|
||||||
|
this.channel = future.sync().channel()
|
||||||
|
this.onconnection({})
|
||||||
|
handler.handshakeFuture.addListener(new ChannelFutureListener((future: any) => {
|
||||||
|
try {
|
||||||
|
future.sync()
|
||||||
|
this.onconnect({})
|
||||||
|
} catch (error) {
|
||||||
|
console.debug(error)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
doSend(text: string) {
|
||||||
|
this.channel.writeAndFlush(new TextWebSocketFrame(text))
|
||||||
|
}
|
||||||
|
doClose(code: number, reason: string) {
|
||||||
|
this.channel.writeAndFlush(new CloseWebSocketFrame())
|
||||||
|
this.channel.close()
|
||||||
|
this.channel.closeFuture().addListener(new ChannelFutureListener(() => console.debug(`NettyWebSocket close code: ${code} reason: ${reason}`)))
|
||||||
|
}
|
||||||
|
getChannel() {
|
||||||
|
return this.channel
|
||||||
|
}
|
||||||
|
}
|
||||||
100
packages/websocket/src/client/transport.ts
Normal file
100
packages/websocket/src/client/transport.ts
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
import { EventEmitter } from 'events'
|
||||||
|
import { WebSocket } from './index'
|
||||||
|
import { CloseEvent, ErrorEvent, Event, MessageEvent, WebSocketHeader } from './interface'
|
||||||
|
|
||||||
|
export abstract class Transport extends EventEmitter {
|
||||||
|
protected _url: string
|
||||||
|
protected _state: number = WebSocket.CONNECTING
|
||||||
|
protected _protocol: string
|
||||||
|
protected _headers: WebSocketHeader = {}
|
||||||
|
|
||||||
|
constructor(uri: string, subProtocol: string = '', headers: WebSocketHeader = {}) {
|
||||||
|
super()
|
||||||
|
this._url = uri
|
||||||
|
this._protocol = subProtocol
|
||||||
|
this._headers = headers
|
||||||
|
}
|
||||||
|
|
||||||
|
get id() {
|
||||||
|
return this.getId()
|
||||||
|
}
|
||||||
|
|
||||||
|
get protocol() {
|
||||||
|
return this._protocol
|
||||||
|
}
|
||||||
|
|
||||||
|
get readyStatus() {
|
||||||
|
return this._state
|
||||||
|
}
|
||||||
|
|
||||||
|
set readyStatus(state: number) {
|
||||||
|
this._state = state
|
||||||
|
}
|
||||||
|
|
||||||
|
connect() {
|
||||||
|
try {
|
||||||
|
this.doConnect()
|
||||||
|
} catch (error) {
|
||||||
|
this.onerror({ error })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
send(text: string) {
|
||||||
|
try {
|
||||||
|
this.doSend(text)
|
||||||
|
} catch (error) {
|
||||||
|
this.onerror({ error })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close(code: number = 0, reason: string = '') {
|
||||||
|
if (this.readyStatus != WebSocket.CLOSING && this.readyStatus != WebSocket.CLOSED) {
|
||||||
|
this.readyStatus = WebSocket.CLOSING
|
||||||
|
try {
|
||||||
|
this.onclose({ code, reason })
|
||||||
|
this.doClose(code, reason)
|
||||||
|
} catch (error) {
|
||||||
|
this.onerror({ error })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.debug(`${this.id} call close but state is ${this.readyStatus}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onconnection(event: Event) {
|
||||||
|
this._state == WebSocket.CONNECTING
|
||||||
|
this.emit('connecting', event)
|
||||||
|
}
|
||||||
|
|
||||||
|
onconnect(event: Event) {
|
||||||
|
console.debug(`${this.id} call onconnect`)
|
||||||
|
if (this.readyStatus != WebSocket.OPEN) {
|
||||||
|
this.readyStatus = WebSocket.OPEN
|
||||||
|
this.emit('open', event)
|
||||||
|
} else {
|
||||||
|
console.debug(`${this.id} call onconnect but state is ${this.readyStatus}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onmessage(event: MessageEvent) {
|
||||||
|
this.emit('message', event)
|
||||||
|
}
|
||||||
|
|
||||||
|
onerror(event: ErrorEvent) {
|
||||||
|
this.emit('error', event)
|
||||||
|
}
|
||||||
|
|
||||||
|
onclose(event: CloseEvent) {
|
||||||
|
if (this.readyStatus != WebSocket.CLOSED) {
|
||||||
|
this.readyStatus = WebSocket.CLOSED
|
||||||
|
this.emit('close', event)
|
||||||
|
this.removeAllListeners()
|
||||||
|
} else {
|
||||||
|
console.debug(`${this.id} call onclose but state is ${this.readyStatus} CloseEvent[code: ${event.code}, reason: ${event.reason}]`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
abstract getId()
|
||||||
|
abstract doConnect()
|
||||||
|
abstract doSend(text: string)
|
||||||
|
abstract doClose(code: number, reason: string)
|
||||||
|
}
|
||||||
@@ -14,20 +14,20 @@ interface SocketIOStatic {
|
|||||||
* @param srv The HTTP server that we're going to bind to
|
* @param srv The HTTP server that we're going to bind to
|
||||||
* @param opts An optional parameters object
|
* @param opts An optional parameters object
|
||||||
*/
|
*/
|
||||||
(srv: any, opts?: ServerOptions): Server
|
(srv: any, opts?: Partial<ServerOptions>): Server
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new Server
|
* Creates a new Server
|
||||||
* @param port A port to bind to, as a number, or a string
|
* @param port A port to bind to, as a number, or a string
|
||||||
* @param An optional parameters object
|
* @param An optional parameters object
|
||||||
*/
|
*/
|
||||||
(port: string | number, opts?: ServerOptions): Server
|
(port: string | number, opts?: Partial<ServerOptions>): Server
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new Server
|
* Creates a new Server
|
||||||
* @param A parameters object
|
* @param A parameters object
|
||||||
*/
|
*/
|
||||||
(opts: ServerOptions): Server
|
(opts: Partial<ServerOptions>): Server
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Backwards compatibility
|
* Backwards compatibility
|
||||||
@@ -39,9 +39,12 @@ interface SocketIOStatic {
|
|||||||
type SocketStatic = SocketIOStatic & { Instance?: symbol }
|
type SocketStatic = SocketIOStatic & { Instance?: symbol }
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
let io: SocketStatic = function (pipeline: any, options: ServerOptions) {
|
let io: SocketStatic = function (pipeline: any, options: Partial<ServerOptions>) {
|
||||||
return new Server(pipeline, options)
|
return new Server(pipeline, options)
|
||||||
}
|
}
|
||||||
io.Instance = Symbol("@ccms/websocket")
|
io.Instance = Symbol("@ccms/websocket")
|
||||||
export default io
|
export default io
|
||||||
export * from './socket-io'
|
export * from './socket-io'
|
||||||
|
export * from './client'
|
||||||
|
export * from './server'
|
||||||
|
export * from './transport'
|
||||||
|
|||||||
21
packages/websocket/src/netty/adapter/httprequest.ts
Normal file
21
packages/websocket/src/netty/adapter/httprequest.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
|
||||||
|
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
||||||
|
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
|
||||||
|
|
||||||
|
export abstract class HttpRequestHandlerAdapter {
|
||||||
|
private _Handler
|
||||||
|
constructor() {
|
||||||
|
let HttpRequestHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
||||||
|
isSharable: () => true,
|
||||||
|
acceptInboundMessage: (msg: any) => {
|
||||||
|
return FullHttpRequestMatcher.match(msg)
|
||||||
|
},
|
||||||
|
channelRead0: this.channelRead0.bind(this)
|
||||||
|
})
|
||||||
|
this._Handler = new HttpRequestHandlerAdapterImpl()
|
||||||
|
}
|
||||||
|
abstract channelRead0(ctx: any, request: any)
|
||||||
|
getHandler() {
|
||||||
|
return this._Handler
|
||||||
|
}
|
||||||
|
}
|
||||||
3
packages/websocket/src/netty/adapter/index.ts
Normal file
3
packages/websocket/src/netty/adapter/index.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export * from './text_websocket_frame'
|
||||||
|
export * from './websocket'
|
||||||
|
export * from './httprequest'
|
||||||
25
packages/websocket/src/netty/adapter/text_websocket_frame.ts
Normal file
25
packages/websocket/src/netty/adapter/text_websocket_frame.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
|
||||||
|
const TextWebSocketFrameMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.websocketx.TextWebSocketFrame'))
|
||||||
|
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
||||||
|
|
||||||
|
export abstract class TextWebSocketFrameHandlerAdapter {
|
||||||
|
private _Handler
|
||||||
|
constructor() {
|
||||||
|
let TextWebSocketFrameHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
||||||
|
isSharable: () => true,
|
||||||
|
userEventTriggered: this.userEventTriggered.bind(this),
|
||||||
|
acceptInboundMessage: (msg: any) => {
|
||||||
|
return TextWebSocketFrameMatcher.match(msg)
|
||||||
|
},
|
||||||
|
channelRead0: this.channelRead0.bind(this),
|
||||||
|
exceptionCaught: this.exceptionCaught.bind(this)
|
||||||
|
})
|
||||||
|
this._Handler = new TextWebSocketFrameHandlerAdapterImpl()
|
||||||
|
}
|
||||||
|
abstract userEventTriggered(ctx: any, evt: any)
|
||||||
|
abstract channelRead0(ctx: any, msg: any)
|
||||||
|
abstract exceptionCaught(ctx: any, cause: Error)
|
||||||
|
getHandler() {
|
||||||
|
return this._Handler
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,26 @@
|
|||||||
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
|
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
|
||||||
|
|
||||||
export abstract class WebSocketHandlerAdapter {
|
export abstract class WebSocketHandlerAdapter {
|
||||||
private _Handler;
|
private _Handler
|
||||||
constructor() {
|
constructor() {
|
||||||
let ChannelInboundHandlerAdapterImpl = Java.extend(ChannelInboundHandlerAdapter, {
|
let ChannelInboundHandlerAdapterImpl = Java.extend(ChannelInboundHandlerAdapter, {
|
||||||
|
isSharable: () => true,
|
||||||
channelRead: this.channelRead.bind(this),
|
channelRead: this.channelRead.bind(this),
|
||||||
|
channelInactive: this.channelInactive.bind(this),
|
||||||
|
channelUnregistered: this.exceptionCaught.bind(this),
|
||||||
exceptionCaught: this.exceptionCaught.bind(this)
|
exceptionCaught: this.exceptionCaught.bind(this)
|
||||||
})
|
})
|
||||||
this._Handler = new ChannelInboundHandlerAdapterImpl()
|
this._Handler = new ChannelInboundHandlerAdapterImpl()
|
||||||
}
|
}
|
||||||
abstract channelRead(ctx: any, channel: any);
|
abstract channelRead(ctx: any, channel: any)
|
||||||
abstract exceptionCaught(ctx: any, cause: Error);
|
channelInactive(ctx: any) {
|
||||||
|
ctx.fireChannelInactive()
|
||||||
|
}
|
||||||
|
channelUnregistered(ctx: any) {
|
||||||
|
ctx.fireChannelUnregistered()
|
||||||
|
}
|
||||||
|
abstract exceptionCaught(ctx: any, cause: Error)
|
||||||
getHandler() {
|
getHandler() {
|
||||||
return this._Handler;
|
return this._Handler
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
24
packages/websocket/src/netty/client.ts
Normal file
24
packages/websocket/src/netty/client.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { Transport } from '../transport'
|
||||||
|
import { AttributeKeys } from './constants'
|
||||||
|
|
||||||
|
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
|
||||||
|
|
||||||
|
export class NettyClient extends Transport {
|
||||||
|
private channel: any
|
||||||
|
|
||||||
|
constructor(server: any, channel: any) {
|
||||||
|
super(server)
|
||||||
|
this.remoteAddress = channel.remoteAddress() + ''
|
||||||
|
this.request = channel.attr(AttributeKeys.Request).get()
|
||||||
|
|
||||||
|
this._id = channel.id() + ''
|
||||||
|
this.channel = channel
|
||||||
|
}
|
||||||
|
|
||||||
|
doSend(text: string) {
|
||||||
|
this.channel.writeAndFlush(new TextWebSocketFrame(text))
|
||||||
|
}
|
||||||
|
doClose() {
|
||||||
|
this.channel.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,20 +1,61 @@
|
|||||||
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
|
import { HttpRequestHandlerAdapter } from './adapter'
|
||||||
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
import { AttributeKeys } from './constants'
|
||||||
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
|
import { ServerOptions } from 'socket-io'
|
||||||
|
|
||||||
export abstract class HttpRequestHandlerAdapter {
|
const DefaultHttpResponse = Java.type('io.netty.handler.codec.http.DefaultHttpResponse')
|
||||||
private _Handler;
|
const DefaultFullHttpResponse = Java.type('io.netty.handler.codec.http.DefaultFullHttpResponse')
|
||||||
constructor() {
|
const HttpHeaders = Java.type('io.netty.handler.codec.http.HttpHeaders')
|
||||||
let HttpRequestHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
const HttpVersion = Java.type('io.netty.handler.codec.http.HttpVersion')
|
||||||
acceptInboundMessage: (msg: any) => {
|
const HttpResponseStatus = Java.type('io.netty.handler.codec.http.HttpResponseStatus')
|
||||||
return FullHttpRequestMatcher.match(msg)
|
const LastHttpContent = Java.type('io.netty.handler.codec.http.LastHttpContent')
|
||||||
},
|
|
||||||
channelRead0: this.channelRead0.bind(this)
|
const File = Java.type('java.io.File')
|
||||||
})
|
const Runnable = Java.type('java.lang.Runnable')
|
||||||
this._Handler = new HttpRequestHandlerAdapterImpl();
|
const RandomAccessFile = Java.type('java.io.RandomAccessFile')
|
||||||
|
const DefaultFileRegion = Java.type('io.netty.channel.DefaultFileRegion')
|
||||||
|
const ChannelFutureListener = Java.type('io.netty.channel.ChannelFutureListener')
|
||||||
|
|
||||||
|
export class HttpRequestHandler extends HttpRequestHandlerAdapter {
|
||||||
|
private ws: string
|
||||||
|
private root: string
|
||||||
|
constructor(options: ServerOptions) {
|
||||||
|
super()
|
||||||
|
this.root = options.root
|
||||||
|
this.ws = options.path
|
||||||
|
}
|
||||||
|
channelRead0(ctx: any, request: any) {
|
||||||
|
if (request.getUri().startsWith(this.ws)) {
|
||||||
|
ctx.channel().attr(AttributeKeys.Request).set(request)
|
||||||
|
ctx.fireChannelRead(request.retain())
|
||||||
|
} else {
|
||||||
|
ctx.executor().execute(new Runnable({
|
||||||
|
run: () => {
|
||||||
|
if (HttpHeaders.is100ContinueExpected(request)) {
|
||||||
|
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE))
|
||||||
|
}
|
||||||
|
let filename = request.getUri().split('?')[0].substr(1)
|
||||||
|
let file = new File(this.root, filename || 'index.html')
|
||||||
|
if (!file.exists() || !file.isFile()) {
|
||||||
|
ctx.write(new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND))
|
||||||
|
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK)
|
||||||
|
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html charset=UTF-8")
|
||||||
|
let raf = new RandomAccessFile(file, 'r')
|
||||||
|
let keepAlive = HttpHeaders.isKeepAlive(request)
|
||||||
|
if (keepAlive) {
|
||||||
|
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length())
|
||||||
|
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
|
||||||
|
}
|
||||||
|
ctx.write(response)
|
||||||
|
ctx.write(new DefaultFileRegion(raf.getChannel(), 0, raf.length()))
|
||||||
|
let future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)
|
||||||
|
if (!keepAlive) {
|
||||||
|
future.addListener(ChannelFutureListener.CLOSE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
abstract channelRead0(ctx: any, request: any);
|
|
||||||
getHandler() {
|
|
||||||
return this._Handler;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,69 @@
|
|||||||
export * from './text_websocket_frame'
|
import { EventEmitter } from 'events'
|
||||||
export * from './websocket'
|
|
||||||
export * from './httprequest'
|
import { ServerOptions } from '../socket-io'
|
||||||
|
import { ServerEvent } from '../socket-io/constants'
|
||||||
|
|
||||||
|
import { NettyClient } from './client'
|
||||||
|
import { Keys } from './constants'
|
||||||
|
import { WebSocketDetect } from './websocket_detect'
|
||||||
|
import { WebSocketHandler } from './websocket_handler'
|
||||||
|
|
||||||
|
class NettyWebSocketServer extends EventEmitter {
|
||||||
|
private pipeline: any
|
||||||
|
private clients: Map<string, NettyClient>
|
||||||
|
|
||||||
|
constructor(pipeline: any, options: ServerOptions) {
|
||||||
|
super()
|
||||||
|
this.clients = new Map()
|
||||||
|
this.pipeline = pipeline
|
||||||
|
let connectEvent = options.event
|
||||||
|
try { this.pipeline.remove(Keys.Detect) } catch (error) { }
|
||||||
|
this.pipeline.addFirst(Keys.Detect, new WebSocketDetect(connectEvent).getHandler())
|
||||||
|
connectEvent.on(ServerEvent.detect, (ctx, channel) => {
|
||||||
|
channel.pipeline().addFirst(Keys.Handler, new WebSocketHandler(options).getHandler())
|
||||||
|
ctx.fireChannelRead(channel)
|
||||||
|
})
|
||||||
|
connectEvent.on(ServerEvent.connect, (ctx) => {
|
||||||
|
let cid = ctx?.channel().id() + ''
|
||||||
|
let nettyClient = new NettyClient(this, ctx.channel())
|
||||||
|
this.clients.set(cid, nettyClient)
|
||||||
|
this.emit(ServerEvent.connect, nettyClient)
|
||||||
|
})
|
||||||
|
connectEvent.on(ServerEvent.message, (ctx, msg) => {
|
||||||
|
let cid = ctx?.channel().id() + ''
|
||||||
|
if (this.clients.has(cid)) {
|
||||||
|
this.emit(ServerEvent.message, this.clients.get(cid), msg.text())
|
||||||
|
} else {
|
||||||
|
console.error(`unknow client ${ctx} reciver message ${msg.text()}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
connectEvent.on(ServerEvent.disconnect, (ctx, cause) => {
|
||||||
|
let cid = ctx?.channel().id() + ''
|
||||||
|
if (this.clients.has(cid)) {
|
||||||
|
this.emit(ServerEvent.disconnect, this.clients.get(cid), cause)
|
||||||
|
} else {
|
||||||
|
console.error(`unknow client ${ctx} disconnect cause ${cause}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
connectEvent.on(ServerEvent.error, (ctx, cause) => {
|
||||||
|
let cid = ctx?.channel().id() + ''
|
||||||
|
if (this.clients.has(cid)) {
|
||||||
|
this.emit(ServerEvent.error, this.clients.get(cid), cause)
|
||||||
|
} else {
|
||||||
|
console.error(`unknow client ${ctx} cause error ${cause}`)
|
||||||
|
console.ex(cause)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
close() {
|
||||||
|
if (this.pipeline.names().contains(Keys.Detect)) {
|
||||||
|
this.pipeline.remove(Keys.Detect)
|
||||||
|
}
|
||||||
|
this.clients.forEach(client => client.close())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
NettyWebSocketServer,
|
||||||
|
NettyClient
|
||||||
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user