Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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.12.0",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/amqp",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript amqp package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,17 +19,17 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/common": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/common": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.10.0",
|
||||
"@ccms/nashorn": "^0.12.0",
|
||||
"@javatypes/amqp-client": "^0.0.3",
|
||||
"@javatypes/spring-amqp": "^0.0.3",
|
||||
"@javatypes/spring-rabbit": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/api",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,16 +19,16 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/common": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0",
|
||||
"@ccms/ployfill": "^0.10.0",
|
||||
"base64-js": "^1.3.1",
|
||||
"@ccms/common": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0",
|
||||
"@ccms/ployfill": "^0.12.0",
|
||||
"base64-js": "^1.5.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/base64-js": "^1.3.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,8 @@ export class MiaoScriptConsole implements Console {
|
||||
private _level: LogLevel = LogLevel.INFO
|
||||
|
||||
protected logger: any
|
||||
protected prefix: string = '§6[§bMiaoScript§6]§r '
|
||||
|
||||
public prefix: string = '§6[§bMiaoScript§6]§r '
|
||||
|
||||
constructor(name?: string) {
|
||||
this.name = name
|
||||
@@ -47,10 +48,10 @@ export class MiaoScriptConsole implements Console {
|
||||
set name(name: string) {
|
||||
if (name) {
|
||||
this._name = `[${name}] `
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
||||
}
|
||||
}
|
||||
|
||||
log(...args: any[]): void {
|
||||
this.logger.info(this.name + args.join(' '))
|
||||
}
|
||||
@@ -133,6 +134,7 @@ export class MiaoScriptConsole implements Console {
|
||||
}
|
||||
}
|
||||
stack(ex: Error, color: boolean = true): string[] {
|
||||
if (!ex) return []
|
||||
let stack = ex.getStackTrace()
|
||||
let cache = [(color ? '§c' : '') + ex]
|
||||
//@ts-ignore
|
||||
@@ -157,9 +159,11 @@ export class MiaoScriptConsole implements Console {
|
||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
} else {
|
||||
for (let prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
return
|
||||
if (!global.debug) {
|
||||
for (let prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,4 +12,5 @@ export * from './console'
|
||||
export * from './channel'
|
||||
export * from './command'
|
||||
export * from './database'
|
||||
export * from './particle'
|
||||
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")
|
||||
@injectable()
|
||||
export abstract class NativePluginManager {
|
||||
list(): any[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
has(name: string): boolean {
|
||||
return true
|
||||
}
|
||||
get(name: string): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
load(name: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
|
||||
@@ -1,34 +1,66 @@
|
||||
import { plugin } from './index'
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
|
||||
export namespace task {
|
||||
@injectable()
|
||||
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) {
|
||||
if (!this.cacheTasks.has(plugin.description.name)) {
|
||||
this.cacheTasks.set(plugin.description.name, [])
|
||||
if (!this.pluginCacheTasks.has(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
|
||||
}
|
||||
|
||||
protected pluginDisable(plugin: plugin.Plugin) {
|
||||
if (this.cacheTasks.has(plugin.description.name)) {
|
||||
this.cacheTasks.get(plugin.description.name).forEach(task => task.cancel())
|
||||
this.cacheTasks.delete(plugin.description.name)
|
||||
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
||||
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => {
|
||||
task.cancel()
|
||||
})
|
||||
this.pluginCacheTasks.delete(plugin.description.name)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得自增的任务ID
|
||||
*/
|
||||
protected nextId() {
|
||||
return this.taskId.incrementAndGet()
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建任务
|
||||
* @param func 任务内容
|
||||
*/
|
||||
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
||||
let task = this.create0(func)
|
||||
let task = this.create0(plugin, func, this.nextId())
|
||||
this.cacheTasks.set(task.getTaskId(), task)
|
||||
if (plugin) { return this.pluginCreate(plugin, 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 执行内容
|
||||
@@ -41,22 +73,33 @@ export namespace task {
|
||||
if (plugin) { return this.pluginDisable(plugin) }
|
||||
this.disable0()
|
||||
}
|
||||
protected abstract create0(func: Function): task.Task
|
||||
protected abstract create0(owner: plugin.Plugin, func: Function, id: number): task.Task
|
||||
protected abstract disable0()
|
||||
}
|
||||
/**
|
||||
* 任务抽象
|
||||
*/
|
||||
export abstract class Task {
|
||||
protected plugin: any
|
||||
export abstract class Task implements Cancelable {
|
||||
protected func: Function
|
||||
protected isAsync: boolean = false;
|
||||
protected laterTime: number = 0;
|
||||
protected interval: number = 0;
|
||||
protected owner: plugin.Plugin
|
||||
protected taskId: number
|
||||
protected innerTask: any
|
||||
|
||||
constructor(plugin: any, func: Function) {
|
||||
this.plugin = plugin
|
||||
constructor(owner: plugin.Plugin, func: Function, id: number) {
|
||||
this.owner = owner
|
||||
this.func = func
|
||||
this.taskId = id
|
||||
}
|
||||
|
||||
getOwner() {
|
||||
return this.owner
|
||||
}
|
||||
|
||||
getTaskId() {
|
||||
return this.taskId
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,12 +133,15 @@ export namespace task {
|
||||
* 取消任务
|
||||
*/
|
||||
cancel(): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
let result = this.cancel0()
|
||||
process.emit('task.finish', this)
|
||||
return result
|
||||
}
|
||||
|
||||
protected run(...args: any[]): void {
|
||||
try {
|
||||
this.func(...args)
|
||||
!this.interval && process.emit('task.finish', this)
|
||||
} catch (ex) {
|
||||
console.console('§4插件执行任务时发生错误', ex)
|
||||
console.ex(ex)
|
||||
@@ -106,17 +152,22 @@ export namespace task {
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
*/
|
||||
submit(...args: any[]): Cancelable {
|
||||
let cancelable = this.submit0(...args)
|
||||
this.cancel = cancelable.cancel
|
||||
return cancelable
|
||||
submit(...args: any[]): task.Task {
|
||||
this.innerTask = this.submit0(...args)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交任务
|
||||
* @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",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/spigot-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/common": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/common": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,12 @@ import './chat'
|
||||
import './task'
|
||||
import './event'
|
||||
import './server'
|
||||
import { BukkitNativePluginManager } from './plugin'
|
||||
import './command'
|
||||
import './channel'
|
||||
import './particle'
|
||||
|
||||
export default function BukkitImpl(container: Container) {
|
||||
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)
|
||||
export class BukkitTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
create0(func: Function): task.Task {
|
||||
return new BukkitTask(this.pluginInstance, func)
|
||||
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||
return new BukkitTask(owner, func, id)
|
||||
}
|
||||
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() {
|
||||
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 funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||
return run[funcName](base.getInstance(), this.laterTime, this.interval)
|
||||
} else {
|
||||
return run[funcName](this.plugin, this.laterTime)
|
||||
return run[funcName](base.getInstance(), this.laterTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bungee",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/bungee-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/common": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/common": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,13 +3,15 @@
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
import { BungeeConsole } from './console';
|
||||
import './event';
|
||||
import './server';
|
||||
import './command';
|
||||
import './channel';
|
||||
import './task';
|
||||
import { BungeeConsole } from './console'
|
||||
import './task'
|
||||
import './event'
|
||||
import './server'
|
||||
import { BungeeNativePluginManager } from './plugin'
|
||||
import './command'
|
||||
import './channel'
|
||||
|
||||
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)
|
||||
export class BungeeTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
create0(func: Function): task.Task {
|
||||
return new BungeeTask(this.pluginInstance, func)
|
||||
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||
return new BungeeTask(owner, func, id)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func()
|
||||
}
|
||||
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 {
|
||||
let run = new Runnable({ run: () => this.run(...args) })
|
||||
if (this.isAsync) {
|
||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||
return base.getInstance().getProxy().getScheduler().runAsync(base.getInstance(), run)
|
||||
}
|
||||
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 {
|
||||
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,
|
||||
"name": "@ccms/client",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript client package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,10 +22,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"minecraft-protocol": "^1.16.0"
|
||||
"minecraft-protocol": "^1.19.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/common",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,11 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.10.0",
|
||||
"@ccms/nashorn": "^0.12.0",
|
||||
"@javatypes/jdk": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/compile",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,6 +21,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/container",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,10 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.10.0",
|
||||
"@ccms/nashorn": "^0.12.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"inversify": "^5.0.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/core",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -1,25 +1,23 @@
|
||||
let containerStartTime = Date.now()
|
||||
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
||||
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 })
|
||||
import http from '@ccms/common/dist/http'
|
||||
|
||||
@provideSingleton(MiaoScriptCore)
|
||||
class MiaoScriptCore {
|
||||
@inject(server.Console)
|
||||
@Autowired(server.Console)
|
||||
private Console: Console
|
||||
@inject(task.TaskManager)
|
||||
private taskManager: task.TaskManager
|
||||
@inject(plugin.PluginFolder)
|
||||
@Autowired(plugin.PluginFolder)
|
||||
private pluginFolder: string
|
||||
@inject(plugin.PluginManager)
|
||||
@Autowired()
|
||||
private taskManager: task.TaskManager
|
||||
@Autowired()
|
||||
private pluginManager: plugin.PluginManager
|
||||
|
||||
enable() {
|
||||
this.loadServerConsole()
|
||||
this.loadTaskFunction()
|
||||
global.level = "TRACE"
|
||||
this.loadPlugins()
|
||||
return () => this.disable()
|
||||
}
|
||||
@@ -29,15 +27,6 @@ class MiaoScriptCore {
|
||||
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() {
|
||||
let loadPluginStartTime = new Date().getTime()
|
||||
console.i18n("ms.core.plugin.initialize")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/database",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript database package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,10 +22,10 @@
|
||||
"@javatypes/spring-jdbc": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/i18n",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript i18n package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,11 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.10.0",
|
||||
"@ccms/nashorn": "^0.12.0",
|
||||
"@types/js-yaml": "^3.12.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "^3.14.0"
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
import * as yaml from 'js-yaml'
|
||||
|
||||
const File = Java.type("java.io.File");
|
||||
const separatorChar = File.separatorChar;
|
||||
const File = Java.type("java.io.File")
|
||||
const separatorChar = File.separatorChar
|
||||
type TranslateParam = { [key: string]: any }
|
||||
|
||||
declare global {
|
||||
interface Console {
|
||||
i18n(name: string, param?: TranslateParam);
|
||||
i18n(name: string, param?: TranslateParam)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,20 +23,20 @@ export class Translate {
|
||||
|
||||
constructor(root: string | TranslateContent) {
|
||||
if (typeof root == 'string') {
|
||||
this.root = root;
|
||||
this.root = root
|
||||
} else {
|
||||
this.langMap = root.langMap;
|
||||
this.fallbackMap = root.fallbackMap || {};
|
||||
this.langMap = root.langMap
|
||||
this.fallbackMap = root.fallbackMap || {}
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
for (const key in param) {
|
||||
langText = langText.replace(new RegExp("{" + key + "}", 'gm'), param[key])
|
||||
}
|
||||
return langText;
|
||||
return langText
|
||||
}
|
||||
|
||||
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
||||
@@ -49,7 +49,7 @@ export class Translate {
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/keyvalue",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript keyvalue package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,18 +19,18 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/common": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/common": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.10.0",
|
||||
"@ccms/nashorn": "^0.12.0",
|
||||
"@javatypes/amqp-client": "^0.0.3",
|
||||
"@javatypes/spring-amqp": "^0.0.3",
|
||||
"@javatypes/spring-rabbit": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nashorn",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,6 +22,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,12 +67,14 @@ declare global {
|
||||
interface Core {
|
||||
getClass(name: String): any
|
||||
getProxyClass(): any
|
||||
getJavaScriptTaskClass(): any
|
||||
getInstance(): any
|
||||
read(path: string): string
|
||||
save(path: string, content: string): void
|
||||
delete(path: string): void
|
||||
}
|
||||
interface Console {
|
||||
prefix: string
|
||||
ex(err: Error): void
|
||||
stack(err: Error, color?: boolean): string[]
|
||||
sender(sender: any, ...args: any): void
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nodejs",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript nodejs package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,10 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.10.0",
|
||||
"@ccms/nashorn": "^0.12.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nukkit",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript nukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/nukkit-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/common": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/common": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
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')
|
||||
|
||||
export class NukkitConsole extends MiaoScriptConsole {
|
||||
sender(sender, ...args) {
|
||||
if (!(sender instanceof CommandSender)) {
|
||||
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]") {
|
||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||
} else {
|
||||
sender.sendMessage(this.prefix + args.join(' '));
|
||||
sender.sendMessage(this.prefix + args.join(' '))
|
||||
}
|
||||
}
|
||||
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 { Container } from '@ccms/container'
|
||||
|
||||
import { NukkitConsole } from './console';
|
||||
import './event';
|
||||
import './server';
|
||||
import './command';
|
||||
import './task';
|
||||
import { NukkitConsole } from './console'
|
||||
import './task'
|
||||
import './event'
|
||||
import './server'
|
||||
import { NukkitNativePluginManager } from './plugin'
|
||||
import './command'
|
||||
|
||||
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)
|
||||
export class NukkitTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
create0(func: Function): task.Task {
|
||||
return new NukkitTask(this.pluginInstance, func)
|
||||
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||
return new NukkitTask(owner, func, id)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func()
|
||||
}
|
||||
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 funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||
return run[funcName](base.getInstance(), this.laterTime, this.interval)
|
||||
} else {
|
||||
return run[funcName](this.plugin, this.laterTime)
|
||||
return run[funcName](base.getInstance(), this.laterTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/ployfill",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript ployfill package",
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
@@ -14,14 +14,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/i18n": "^0.10.0",
|
||||
"@ccms/nodejs": "^0.10.0",
|
||||
"core-js": "^3.6.5"
|
||||
"@ccms/i18n": "^0.12.0",
|
||||
"@ccms/nodejs": "^0.12.0",
|
||||
"core-js": "^3.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.10.0",
|
||||
"@ccms/nashorn": "^0.12.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,16 +5,18 @@ 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 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(
|
||||
10, 100, 60, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue(500),
|
||||
100, 200, 60, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue(300),
|
||||
(run: any) => new Thread(threadGroup, run, "@ccms/micro-task-" + threadCount.incrementAndGet()),
|
||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
||||
)
|
||||
|
||||
class Process extends EventEmitter {
|
||||
env = {
|
||||
__noSuchProperty__: (prop) => {
|
||||
@@ -22,16 +24,120 @@ class Process extends EventEmitter {
|
||||
}
|
||||
}
|
||||
platform = Packages.java.lang.System.getProperty("os.name")
|
||||
nextTick(func: Function) {
|
||||
microTaskPool.execute(func)
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
queueMicrotask(func: Function) {
|
||||
nextTick(func: Function) {
|
||||
microTaskPool.execute(func)
|
||||
}
|
||||
exit(code: number) {
|
||||
process.emit('exit', code)
|
||||
microTaskPool.shutdown()
|
||||
console.log(`process exit await microTaskPool termination! queueTask: ${microTaskPool.shutdownNow().size()} remainTask: ${threadGroup.activeCount()}`)
|
||||
microTaskPool.awaitTermination(3000, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
}
|
||||
|
||||
class EventLoop {
|
||||
private eventLoopMainThread = undefined
|
||||
private eventLoopTaskQueue = new DelayQueue()
|
||||
|
||||
constructor() {
|
||||
this.eventLoopMainThread = new Thread(() => {
|
||||
let task = undefined
|
||||
try {
|
||||
while ((task = this.eventLoopTaskQueue.take()) != undefined) {
|
||||
try {
|
||||
task.getTask()()
|
||||
} catch (error) {
|
||||
try {
|
||||
process.emit('error', error)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
} 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())
|
||||
}
|
||||
|
||||
startEventLoop() {
|
||||
this.eventLoopMainThread.start()
|
||||
}
|
||||
|
||||
private putDelayTask(callback: Function, ms: number) {
|
||||
this.eventLoopTaskQueue.put(new JavaScriptTask(callback, ms))
|
||||
}
|
||||
|
||||
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(() => {
|
||||
if (this.timeoutTasks[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]) {
|
||||
callback(...args)
|
||||
this.putDelayTask(intervalTask, ms)
|
||||
} else {
|
||||
console.trace(`ignore setInterval task ${taskId} because it's cancelled!`)
|
||||
}
|
||||
}
|
||||
this.putDelayTask(intervalTask, ms)
|
||||
return taskId
|
||||
}
|
||||
clearInterval(taskId: number) {
|
||||
delete this.intervalTasks[taskId]
|
||||
}
|
||||
}
|
||||
global.setGlobal('process', new Process(), {})
|
||||
const eventLoop = new EventLoop()
|
||||
global.setGlobal('eventLoop', 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('setImmediate', (callback: (...args: any[]) => void, ...args: any[]) => eventLoop.setTimeout(callback, 0, ...args), {})
|
||||
global.setGlobal('clearImmediate ', eventLoop.clearTimeout.bind(eventLoop), {})
|
||||
global.setGlobal('setInterval', eventLoop.setInterval.bind(eventLoop), {})
|
||||
global.setGlobal('clearInterval', eventLoop.clearInterval.bind(eventLoop), {})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/plugin",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,13 +22,13 @@
|
||||
"@types/js-yaml": "^3.12.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/common": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0",
|
||||
"@ccms/i18n": "^0.10.0",
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/common": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0",
|
||||
"@ccms/i18n": "^0.12.0",
|
||||
"js-yaml": "^3.14.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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'
|
||||
|
||||
@provideSingleton(PluginCommandManager)
|
||||
@@ -23,11 +24,10 @@ export class PluginCommandManager {
|
||||
continue
|
||||
}
|
||||
for (let command of [cmd.name, ...cmd.alias]) {
|
||||
let [cmdExecutor, cmdCompleter] = this.generateAutoMainCommand(pluginInstance, cmd, tabs.get(command))
|
||||
this.CommandManager.on(pluginInstance, command, {
|
||||
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
||||
tab: tabs.has(command) ?
|
||||
pluginInstance[tabs.get(command).executor].bind(pluginInstance) :
|
||||
console.debug(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`)
|
||||
cmd: cmdExecutor.bind(pluginInstance),
|
||||
tab: cmdCompleter?.bind(pluginInstance)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -37,4 +37,29 @@ export class PluginCommandManager {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
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]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,10 @@ export namespace interfaces {
|
||||
* 参数列表
|
||||
*/
|
||||
paramtypes?: string[]
|
||||
/**
|
||||
* 自动化主命令
|
||||
*/
|
||||
autoMain?: boolean
|
||||
}
|
||||
export interface ListenerMetadata extends ExecMetadata {
|
||||
/**
|
||||
|
||||
@@ -233,21 +233,25 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
}
|
||||
|
||||
private checkDepends(depends: string | string[]) {
|
||||
if (!depends) return true
|
||||
for (const depend of depends) { if (!this.metadataMap.has(depend)) return false }
|
||||
return true
|
||||
if (!depends) return []
|
||||
let loseDepends = []
|
||||
for (const depend of depends) { if (!this.metadataMap.has(depend)) loseDepends.push(depend) }
|
||||
return loseDepends
|
||||
}
|
||||
private checkNativeDepends(depends: string | string[]) {
|
||||
if (!depends) return true
|
||||
for (const depend of depends) { if (!this.nativePluginManager.has(depend)) return false }
|
||||
return true
|
||||
if (!depends) return []
|
||||
let loseDepends = []
|
||||
for (const depend of depends) { if (!this.nativePluginManager.has(depend)) loseDepends.push(depend) }
|
||||
return loseDepends
|
||||
}
|
||||
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.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.checkDepends(metadata.depends)) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查依赖 §3${metadata.depends.join(',')} §4是否安装完整!`) }
|
||||
if (!this.checkNativeDepends(metadata.nativeDepends)) { throw new Error(`§4无法加载插件 §b${metadata.name} §4请检查插件依赖 §3${metadata.nativeDepends.join(',')} §4是否安装完整!`) }
|
||||
let loseDepends = this.checkDepends(metadata.depends) || []
|
||||
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)
|
||||
if (!pluginInstance) { throw new Error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`) }
|
||||
this.instanceMap.set(metadata.name, pluginInstance)
|
||||
|
||||
@@ -7,7 +7,7 @@ export class PluginTaskManager {
|
||||
private taskManager: task.TaskManager
|
||||
|
||||
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) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ccms/plugins",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript plugins package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -20,16 +20,19 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"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-web": "^0.0.3",
|
||||
"@javatypes/tomcat": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0",
|
||||
"@ccms/plugin": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0",
|
||||
"@ccms/plugin": "^0.12.0"
|
||||
}
|
||||
}
|
||||
|
||||
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']
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
|
||||
import { plugin as pluginApi, server, task, constants, command } from '@ccms/api'
|
||||
import { plugin, interfaces, cmd, tab, enable, config, disable } from '@ccms/plugin'
|
||||
import { inject, ContainerInstance, Container } from '@ccms/container'
|
||||
import { plugin, interfaces, cmd, tab, enable, config, disable, PluginConfig } from '@ccms/plugin'
|
||||
import { ContainerInstance, Container, Autowired } from '@ccms/container'
|
||||
import io, { Server as SocketIOServer, Socket as SocketIOSocket } from '@ccms/websocket'
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
@@ -19,22 +19,22 @@ let help = [
|
||||
'§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.0.0', author: 'MiaoWoo', servers: ['!nukkit'], source: __filename })
|
||||
export class MiaoConsole extends interfaces.Plugin {
|
||||
@inject(ContainerInstance)
|
||||
@Autowired(ContainerInstance)
|
||||
private container: Container
|
||||
@inject(server.ServerType)
|
||||
@Autowired(server.ServerType)
|
||||
private serverType: string
|
||||
@inject(server.Server)
|
||||
private server: server.Server
|
||||
@inject(command.Command)
|
||||
private command: command.Command
|
||||
@inject(task.TaskManager)
|
||||
private task: task.TaskManager
|
||||
@inject(pluginApi.PluginManager)
|
||||
private pluginManager: pluginApi.PluginManager
|
||||
@inject(pluginApi.PluginFolder)
|
||||
@Autowired(pluginApi.PluginFolder)
|
||||
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 instance: any
|
||||
@@ -46,7 +46,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
private logCache: string[] = []
|
||||
|
||||
@config()
|
||||
private secret = { token: undefined }
|
||||
private secret: PluginConfig = { token: undefined }
|
||||
|
||||
load() {
|
||||
if (this.secret.token) {
|
||||
@@ -90,6 +90,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
cmdtoken(sender: any, sub: string, token: string) {
|
||||
if (sub == "set") {
|
||||
this.secret.token = this.token = token
|
||||
this.secret.save()
|
||||
this.logger.sender(sender, '§a已保存§6服务器登录Token:§3', this.token, '§4请勿分享给其他人 防止服务器被攻击!')
|
||||
return
|
||||
}
|
||||
@@ -216,6 +217,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
root: fs.concat(root, 'wwwroot')
|
||||
})
|
||||
this.container.bind(io.Instance).toConstantValue(this.socketIOServer)
|
||||
process.emit('websocket.create', this.socketIOServer)
|
||||
}
|
||||
|
||||
startSocketIOServer() {
|
||||
@@ -224,20 +226,19 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
namespace.on('connect', (client: SocketIOSocket) => {
|
||||
if (!this.token) {
|
||||
this.logger.console(`§6客户端 §b${client.id} §a请求连接 §4服务器尚未设置 Token 无法连接!`)
|
||||
client.emit('unauthorized')
|
||||
client.disconnect(true)
|
||||
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)
|
||||
client.emit('unauthorized', () => client.disconnect(true))
|
||||
return
|
||||
}
|
||||
this.initWebSocketClient(client)
|
||||
this.logCache.forEach(msg => client.emit('log', msg))
|
||||
this.logger.console(`§6客户端 §b${client.id} §a新建连接 ${this.rootLogger ? '启动日志转发' : '§4转发日志启动失败'}...`)
|
||||
})
|
||||
process.emit('websocket.start', this.socketIOServer)
|
||||
}
|
||||
|
||||
private initWebSocketClient(client: SocketIOSocket) {
|
||||
@@ -280,7 +281,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
if (!dir.isDirectory()) {
|
||||
return fn(undefined, `${file} 不是一个目录!`)
|
||||
}
|
||||
fn(fs.list(dir))
|
||||
fn(fs.list(dir).map(f => f.name))
|
||||
})
|
||||
client.on('error', (error) => {
|
||||
this.logger.console(`§6客户端 §b${client.id} §c触发异常: ${error}`)
|
||||
|
||||
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('connect', (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']
|
||||
}
|
||||
}
|
||||
@@ -52,12 +52,13 @@ export class MiaoProtocol extends interfaces.Plugin {
|
||||
initPacketAdapter() {
|
||||
this.adapter = this.createPacketAdapter((event) => {
|
||||
let integers = event.getPacket().getIntegers().getValues()
|
||||
console.log(`ProtocolLib onPacketSending filter Map
|
||||
Player: ${event.getPlayer()}
|
||||
MapId: ${integers.get(0)}
|
||||
Size: ${integers.get(3)}x${integers.get(4)}
|
||||
Bytes: ${event.getPacket().getByteArrays().read(0).length}
|
||||
`)
|
||||
// console.log(`ProtocolLib onPacketSending filter Map
|
||||
// Player: ${event.getPlayer()}
|
||||
// MapId: ${integers.get(0)}
|
||||
// Short: ${event.getPacket().getShorts().read(0)}
|
||||
// Bytes: ${event.getPacket().getByteArrays().read(0).length}
|
||||
// `)
|
||||
//Size: ${integers.get(3)}x${integers.get(4)}
|
||||
// org.bukkit.map.MapPalette.imageToBytes()
|
||||
})
|
||||
this.ProtocolLibrary.getProtocolManager().addPacketListener(this.adapter)
|
||||
|
||||
@@ -8,6 +8,7 @@ import http from '@ccms/common/dist/http'
|
||||
|
||||
const BufferedImage = Java.type('java.awt.image.BufferedImage')
|
||||
const Color = Java.type('java.awt.Color')
|
||||
const Bytes = Java.type('byte[]')
|
||||
|
||||
interface PlaceholderAPI {
|
||||
registerPlaceholderHook: (key: string, onPlaceholderRequest: (player, s) => string) => void
|
||||
@@ -29,7 +30,7 @@ function(cls, plugin, type, onPacketSending){
|
||||
}
|
||||
}`)
|
||||
|
||||
@JSPlugin({ prefix: 'MRD', version: '1.4.1', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||
@JSPlugin({ prefix: 'MRD', version: '1.4.2', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||
export class MiaoReward extends interfaces.Plugin {
|
||||
private serverInfo: any
|
||||
private cacheBindUuid = ''
|
||||
@@ -97,11 +98,10 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
//@ts-ignore
|
||||
this.logger.prefix = this.config.prefix
|
||||
this.downgrade = this.Bukkit.server.class.name.split('.')[3] == "v1_7_R4"
|
||||
this.updateServerInfo()
|
||||
this.updateOnlinePlayersInfo()
|
||||
this.updateServerInfo(null, () => this.updateOnlinePlayersInfo())
|
||||
}
|
||||
|
||||
private updateServerInfo(player?: any) {
|
||||
private updateServerInfo(player?: any, cb?: () => void) {
|
||||
this.taskManager.create(() => {
|
||||
if (this.config.serverId) {
|
||||
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
||||
@@ -111,6 +111,7 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
if (result.code == 200) {
|
||||
this.serverInfo = result.data
|
||||
if (player) this.bungee.for(player).forward("ALL", "MiaoReward", { type: "updateServerInfo", data: result.data }).send()
|
||||
cb?.()
|
||||
}
|
||||
}
|
||||
}).async().submit()
|
||||
@@ -206,9 +207,21 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
let mapId = integers.get(0)
|
||||
let player = event.getPlayer()
|
||||
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())))
|
||||
event.getPacket().getIntegers().write(3, 128)
|
||||
event.getPacket().getIntegers().write(4, 128)
|
||||
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(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)
|
||||
@@ -307,14 +320,20 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
return scanning
|
||||
}
|
||||
|
||||
cmdbind(sender: org.bukkit.entity.Player, server: boolean) {
|
||||
cmdopen(sender: org.bukkit.entity.Player) {
|
||||
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()
|
||||
}
|
||||
|
||||
cmdbind(sender: org.bukkit.entity.Player, server: boolean) {
|
||||
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
||||
if (this.bindCheck(sender)) return
|
||||
if (server) {
|
||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4您没有配置服务器的权限!') }
|
||||
this.bindServer(sender)
|
||||
} else {
|
||||
if (!this.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||
this.bindUser(sender)
|
||||
}
|
||||
}
|
||||
@@ -484,6 +503,7 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
}
|
||||
|
||||
private bindServer(sender: org.bukkit.entity.Player) {
|
||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4您没有配置服务器的权限!') }
|
||||
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
||||
let scanObj = http.get(`https://reward.yumc.pw/server/scan`)
|
||||
if (scanObj.code !== 200) {
|
||||
@@ -510,8 +530,7 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
}
|
||||
|
||||
private bindUser(sender: org.bukkit.entity.Player) {
|
||||
if (!this.config.serverId || !this.config.serverToken) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
||||
if (!this.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||
let check = this.httpPost(`https://reward.yumc.pw/server/query`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken
|
||||
@@ -521,8 +540,10 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
}
|
||||
let queryUser = this.queryUser(sender)
|
||||
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 sync = { scaned: false, timeout: false }
|
||||
this.taskManager.create(() => {
|
||||
@@ -569,21 +590,22 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
}
|
||||
}, this).async().later(20).timer(20).submit()
|
||||
this.playerTaskCache.set(sender.getName(), task)
|
||||
this.playerImageCache.set(sender.getName(), this.createQrcode(content))
|
||||
if (this.downgrade) {
|
||||
this.logger.sender(sender, '§c低版本客户端 二维码渲染中 请等待 6 秒 稍候扫码!')
|
||||
this.logger.sender(sender, '§c低版本客户端 二维码渲染中 请等待 3 秒 稍候扫码!')
|
||||
let waitTask = this.taskManager.create(() => {
|
||||
let temp = sender.getLocation()
|
||||
temp.setPitch(-90)
|
||||
sender.teleport(temp)
|
||||
}, this).later(20).timer(20).submit()
|
||||
}, this).later(0).timer(20).submit()
|
||||
this.taskManager.create(() => {
|
||||
waitTask.cancel()
|
||||
let temp = sender.getLocation()
|
||||
temp.setPitch(90)
|
||||
sender.teleport(temp)
|
||||
}).later(150).submit()
|
||||
} else {
|
||||
}).later(80).submit()
|
||||
}
|
||||
this.playerImageCache.set(sender.getName(), org.bukkit.map.MapPalette.imageToBytes(this.createQrcode(content)))
|
||||
if (!this.downgrade) {
|
||||
let temp = sender.getLocation()
|
||||
temp.setPitch(90)
|
||||
sender.teleport(temp)
|
||||
@@ -594,7 +616,7 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
}
|
||||
|
||||
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`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken,
|
||||
@@ -696,6 +718,7 @@ CAST TIME : ${Date.now() - startTime}`)
|
||||
const player = event.getPlayer()
|
||||
this.bungeeCordDetect(player)
|
||||
this.updatePlayerInfo(player)
|
||||
this.taskManager.create(() => this.logger.sender(player, `§a本服已使用喵式奖励 §3可以看广告赚${this.config.coinName} §c/mrd help §b查看帮助!`)).later(50).submit()
|
||||
}
|
||||
|
||||
@Listener()
|
||||
@@ -741,6 +764,7 @@ CAST TIME : ${Date.now() - startTime}`)
|
||||
let help = [
|
||||
`§6====== ${this.config.prefix} §a帮助菜单 §6======`,
|
||||
`§6/mrd bind §a绑定圈云盒子`,
|
||||
`§6/mrd open §a打开圈云盒子`,
|
||||
`§6/mrd query §a查询当前账户`,
|
||||
`§6/mrd draw §e<兑换数量> §a兑换${this.config.coinName}`
|
||||
]
|
||||
|
||||
@@ -94,7 +94,7 @@ export class MiaoSpring extends interfaces.Plugin {
|
||||
preHandle: (ctx: Context) => {
|
||||
const index = foundMap.indexOf(ctx.request.getRequestURI())
|
||||
if (index != -1) {
|
||||
return this.ResponseEntity.status(this.HttpStatus.FOUND).header('Location', foundMap[index + 1]).build()
|
||||
return this.ResponseEntity.status(org.springframework.http.HttpStatus.FOUND).header('Location', foundMap[index + 1]).build()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/protocol",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript protocol package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,6 +22,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/sponge",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/sponge-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/common": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/common": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,12 @@ import './chat'
|
||||
import './task'
|
||||
import './event'
|
||||
import './server'
|
||||
import { SpongeNativePluginManager } from './plugin'
|
||||
import './command'
|
||||
import './channel'
|
||||
import './particle'
|
||||
|
||||
export default function SpongeImpl(container: Container) {
|
||||
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'
|
||||
|
||||
const Sponge = org.spongepowered.api.Sponge
|
||||
const TextSerializers = org.spongepowered.api.text.serializer.TextSerializers
|
||||
const File = Java.type("java.io.File")
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
@@ -35,10 +34,10 @@ export class SpongeServer extends server.ReflectServer {
|
||||
if (typeof sender === 'string') {
|
||||
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 {
|
||||
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 {
|
||||
return this.pluginsFolder
|
||||
|
||||
@@ -9,24 +9,21 @@ const TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class SpongeTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
private syncExecutor: any
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
this.syncExecutor = Sponge.getScheduler().createSyncExecutor(this.pluginInstance)
|
||||
this.syncExecutor = Sponge.getScheduler().createSyncExecutor(base.getInstance())
|
||||
}
|
||||
|
||||
create0(func: Function): task.Task {
|
||||
return new SpongeTask(this.pluginInstance, func)
|
||||
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||
return new SpongeTask(owner, func, id)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
// @ts-ignore
|
||||
return this.syncExecutor.schedule(new Callable({ call: () => func() }), java.lang.Long.valueOf(0), TimeUnit.NANOSECONDS).get()
|
||||
return this.syncExecutor.execute(() => func())
|
||||
}
|
||||
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.laterTime) { run.delayTicks(this.laterTime) }
|
||||
if (this.interval) { run.intervalTicks(this.interval) }
|
||||
return run.submit(this.plugin)
|
||||
return run.submit(base.getInstance())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/spring",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript spring package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,12 +21,12 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/common": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0",
|
||||
"@ccms/database": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/common": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0",
|
||||
"@ccms/database": "^0.12.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
import thread_pool from '@ccms/common/dist/thread-pool'
|
||||
|
||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
const AtomicBoolean = Java.type("java.util.concurrent.atomic.AtomicBoolean")
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
|
||||
@@ -11,21 +10,19 @@ export class SpringTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
private taskId: any
|
||||
private tasks: { [s: string]: task.Cancelable }
|
||||
private executor: java.util.concurrent.ThreadPoolExecutor
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this.taskId = new AtomicInteger(0)
|
||||
this.tasks = {}
|
||||
this.executor = thread_pool.create({
|
||||
groupName: '@ccms/spring'
|
||||
})
|
||||
}
|
||||
|
||||
create0(func: Function): task.Task {
|
||||
return new SpringTask(this.pluginInstance, func, this)
|
||||
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||
return new SpringTask(owner, func, id, this)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func()
|
||||
@@ -51,8 +48,8 @@ export class SpringTask extends task.Task {
|
||||
private taskManager: SpringTaskManager
|
||||
private running = new AtomicBoolean(true)
|
||||
|
||||
constructor(plugin: any, func: Function, taskManager: SpringTaskManager) {
|
||||
super(plugin, func)
|
||||
constructor(owner: plugin.Plugin, func: Function, id: number, taskManager: SpringTaskManager) {
|
||||
super(owner, func, id)
|
||||
this.id = taskManager.nextId()
|
||||
this.taskManager = taskManager
|
||||
}
|
||||
@@ -83,19 +80,16 @@ export class SpringTask extends task.Task {
|
||||
this.cancel()
|
||||
}
|
||||
|
||||
cancel0(): any {
|
||||
cancel0() {
|
||||
var wasRunning = this.running.getAndSet(false)
|
||||
if (wasRunning) {
|
||||
this.taskManager.cancel(this.id)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
submit0(...args: any[]) {
|
||||
this.taskManager.submit(this.id, this, () => this.run(...args))
|
||||
return {
|
||||
cancel: () => {
|
||||
return this.cancel0()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/web",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript web package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -26,10 +26,10 @@
|
||||
"@javatypes/tomcat": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.10.0",
|
||||
"@ccms/container": "^0.10.0"
|
||||
"@ccms/api": "^0.12.0",
|
||||
"@ccms/container": "^0.12.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/websocket",
|
||||
"version": "0.10.0",
|
||||
"version": "0.12.0",
|
||||
"description": "MiaoScript websocket package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,10 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.10.0",
|
||||
"@ccms/nashorn": "^0.12.0",
|
||||
"@javatypes/tomcat-websocket-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,43 +4,43 @@
|
||||
import { Server, ServerOptions } from './socket-io'
|
||||
|
||||
interface SocketIOStatic {
|
||||
/**
|
||||
* Default Server constructor
|
||||
*/
|
||||
(): Server
|
||||
/**
|
||||
* Default Server constructor
|
||||
*/
|
||||
(): Server
|
||||
|
||||
/**
|
||||
* Creates a new Server
|
||||
* @param srv The HTTP server that we're going to bind to
|
||||
* @param opts An optional parameters object
|
||||
*/
|
||||
(srv: any, opts?: ServerOptions): Server
|
||||
/**
|
||||
* Creates a new Server
|
||||
* @param srv The HTTP server that we're going to bind to
|
||||
* @param opts An optional parameters object
|
||||
*/
|
||||
(srv: any, opts?: Partial<ServerOptions>): Server
|
||||
|
||||
/**
|
||||
* Creates a new Server
|
||||
* @param port A port to bind to, as a number, or a string
|
||||
* @param An optional parameters object
|
||||
*/
|
||||
(port: string | number, opts?: ServerOptions): Server
|
||||
/**
|
||||
* Creates a new Server
|
||||
* @param port A port to bind to, as a number, or a string
|
||||
* @param An optional parameters object
|
||||
*/
|
||||
(port: string | number, opts?: Partial<ServerOptions>): Server
|
||||
|
||||
/**
|
||||
* Creates a new Server
|
||||
* @param A parameters object
|
||||
*/
|
||||
(opts: ServerOptions): Server
|
||||
/**
|
||||
* Creates a new Server
|
||||
* @param A parameters object
|
||||
*/
|
||||
(opts: Partial<ServerOptions>): Server
|
||||
|
||||
/**
|
||||
* Backwards compatibility
|
||||
* @see io().listen()
|
||||
*/
|
||||
listen?: SocketIOStatic
|
||||
/**
|
||||
* Backwards compatibility
|
||||
* @see io().listen()
|
||||
*/
|
||||
listen?: SocketIOStatic
|
||||
}
|
||||
|
||||
type SocketStatic = SocketIOStatic & { Instance?: symbol }
|
||||
|
||||
// @ts-ignore
|
||||
let io: SocketStatic = function (pipeline: any, options: ServerOptions) {
|
||||
return new Server(pipeline, options)
|
||||
let io: SocketStatic = function (pipeline: any, options: Partial<ServerOptions>) {
|
||||
return new Server(pipeline, options)
|
||||
}
|
||||
io.Instance = Symbol("@ccms/websocket")
|
||||
export default io
|
||||
|
||||
20
packages/websocket/src/netty/adapter/httprequest.ts
Normal file
20
packages/websocket/src/netty/adapter/httprequest.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
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, {
|
||||
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'
|
||||
24
packages/websocket/src/netty/adapter/text_websocket_frame.ts
Normal file
24
packages/websocket/src/netty/adapter/text_websocket_frame.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
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, {
|
||||
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,25 @@
|
||||
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
|
||||
|
||||
export abstract class WebSocketHandlerAdapter {
|
||||
private _Handler;
|
||||
private _Handler
|
||||
constructor() {
|
||||
let ChannelInboundHandlerAdapterImpl = Java.extend(ChannelInboundHandlerAdapter, {
|
||||
channelRead: this.channelRead.bind(this),
|
||||
channelInactive: this.channelInactive.bind(this),
|
||||
channelUnregistered: this.exceptionCaught.bind(this),
|
||||
exceptionCaught: this.exceptionCaught.bind(this)
|
||||
})
|
||||
this._Handler = new ChannelInboundHandlerAdapterImpl()
|
||||
}
|
||||
abstract channelRead(ctx: any, channel: any);
|
||||
abstract exceptionCaught(ctx: any, cause: Error);
|
||||
abstract channelRead(ctx: any, channel: any)
|
||||
channelInactive(ctx: any) {
|
||||
ctx.fireChannelInactive()
|
||||
}
|
||||
channelUnregistered(ctx: any) {
|
||||
ctx.fireChannelUnregistered()
|
||||
}
|
||||
abstract exceptionCaught(ctx: any, cause: Error)
|
||||
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')
|
||||
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
||||
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
|
||||
import { HttpRequestHandlerAdapter } from './adapter'
|
||||
import { AttributeKeys } from './constants'
|
||||
import { ServerOptions } from 'socket-io'
|
||||
|
||||
export abstract class HttpRequestHandlerAdapter {
|
||||
private _Handler;
|
||||
constructor() {
|
||||
let HttpRequestHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
||||
acceptInboundMessage: (msg: any) => {
|
||||
return FullHttpRequestMatcher.match(msg)
|
||||
},
|
||||
channelRead0: this.channelRead0.bind(this)
|
||||
})
|
||||
this._Handler = new HttpRequestHandlerAdapterImpl();
|
||||
const DefaultHttpResponse = Java.type('io.netty.handler.codec.http.DefaultHttpResponse')
|
||||
const DefaultFullHttpResponse = Java.type('io.netty.handler.codec.http.DefaultFullHttpResponse')
|
||||
const HttpHeaders = Java.type('io.netty.handler.codec.http.HttpHeaders')
|
||||
const HttpVersion = Java.type('io.netty.handler.codec.http.HttpVersion')
|
||||
const HttpResponseStatus = Java.type('io.netty.handler.codec.http.HttpResponseStatus')
|
||||
const LastHttpContent = Java.type('io.netty.handler.codec.http.LastHttpContent')
|
||||
|
||||
const File = Java.type('java.io.File')
|
||||
const Runnable = Java.type('java.lang.Runnable')
|
||||
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
|
||||
}
|
||||
abstract channelRead0(ctx: any, request: any);
|
||||
getHandler() {
|
||||
return this._Handler;
|
||||
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)
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,70 @@
|
||||
export * from './text_websocket_frame'
|
||||
export * from './websocket'
|
||||
export * from './httprequest'
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
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,
|
||||
ServerEvent,
|
||||
NettyClient
|
||||
}
|
||||
|
||||
@@ -1,24 +1,23 @@
|
||||
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')
|
||||
import { EventEmitter } from 'events'
|
||||
import { ServerOptions } from '../socket-io'
|
||||
import { ServerEvent } from '../socket-io/constants'
|
||||
import { TextWebSocketFrameHandlerAdapter } from './adapter'
|
||||
|
||||
export abstract class TextWebSocketFrameHandlerAdapter {
|
||||
private _Handler;
|
||||
constructor() {
|
||||
let TextWebSocketFrameHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
||||
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();
|
||||
export class TextWebSocketFrameHandler extends TextWebSocketFrameHandlerAdapter {
|
||||
private event: EventEmitter
|
||||
constructor(options: ServerOptions) {
|
||||
super()
|
||||
this.event = options.event
|
||||
}
|
||||
abstract userEventTriggered(ctx: any, evt: any);
|
||||
abstract channelRead0(ctx: any, msg: any);
|
||||
abstract exceptionCaught(ctx: any, cause: Error);
|
||||
getHandler() {
|
||||
return this._Handler;
|
||||
userEventTriggered(ctx: any, evt: any) {
|
||||
if (evt == 'HANDSHAKE_COMPLETE') {
|
||||
this.event.emit(ServerEvent.connect, ctx)
|
||||
}
|
||||
}
|
||||
channelRead0(ctx: any, msg: any) {
|
||||
this.event.emit(ServerEvent.message, ctx, msg)
|
||||
}
|
||||
exceptionCaught(ctx: any, cause: Error) {
|
||||
this.event.emit(ServerEvent.error, ctx, cause)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { EventEmitter } from 'events'
|
||||
import { WebSocketHandlerAdapter } from "../netty"
|
||||
import { WebSocketHandlerAdapter } from "./adapter"
|
||||
import { ServerEvent } from '../socket-io/constants'
|
||||
|
||||
export class WebSocketDetect extends WebSocketHandlerAdapter {
|
||||
private event: EventEmitter;
|
||||
private event: EventEmitter
|
||||
constructor(event: EventEmitter) {
|
||||
super()
|
||||
this.event = event;
|
||||
this.event = event
|
||||
}
|
||||
channelRead(ctx: any, channel: any) {
|
||||
this.event.emit(ServerEvent.detect, ctx, channel);
|
||||
this.event.emit(ServerEvent.detect, ctx, channel)
|
||||
}
|
||||
exceptionCaught(ctx: any, cause: Error) {
|
||||
this.event.emit(ServerEvent.error, ctx, cause);
|
||||
this.event.emit(ServerEvent.error, ctx, cause)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { ServerEvent } from '../socket-io/constants'
|
||||
|
||||
import { Keys } from './constants'
|
||||
import { HttpRequestHandler } from './httprequest'
|
||||
import { WebSocketHandlerAdapter } from "../netty"
|
||||
import { WebSocketHandlerAdapter } from "./adapter"
|
||||
import { TextWebSocketFrameHandler } from './text_websocket_frame'
|
||||
|
||||
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
|
||||
@@ -13,10 +13,10 @@ const HttpObjectAggregator = Java.type('io.netty.handler.codec.http.HttpObjectAg
|
||||
const WebSocketServerProtocolHandler = Java.type('io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler')
|
||||
|
||||
export class WebSocketHandler extends WebSocketHandlerAdapter {
|
||||
private options: ServerOptions;
|
||||
private options: ServerOptions
|
||||
constructor(options: ServerOptions) {
|
||||
super()
|
||||
this.options = options;
|
||||
this.options = options
|
||||
}
|
||||
channelRead(ctx: any, msg: any) {
|
||||
msg.markReaderIndex()
|
||||
@@ -32,6 +32,7 @@ export class WebSocketHandler extends WebSocketHandlerAdapter {
|
||||
pipeline.addLast('chunk', new ChunkedWriteHandler())
|
||||
pipeline.addLast('httpobj', new HttpObjectAggregator(64 * 1024))
|
||||
pipeline.addLast('http_request', new HttpRequestHandler(this.options).getHandler())
|
||||
// this.options.path, null, false, 655360, false, true, false, 10000
|
||||
pipeline.addLast('websocket', new WebSocketServerProtocolHandler(this.options.path, true))
|
||||
pipeline.addLast('websocket_handler', new TextWebSocketFrameHandler(this.options).getHandler())
|
||||
}
|
||||
@@ -39,6 +40,19 @@ export class WebSocketHandler extends WebSocketHandlerAdapter {
|
||||
msg.resetReaderIndex()
|
||||
ctx.fireChannelRead(msg)
|
||||
}
|
||||
|
||||
channelInactive(ctx: any) {
|
||||
console.debug('WebSocketHandler channelInactive ' + ctx)
|
||||
this.options.event.emit(ServerEvent.disconnect, ctx, 'netty channelInactive')
|
||||
super.channelInactive(ctx)
|
||||
}
|
||||
|
||||
channelUnregistered(ctx: any) {
|
||||
console.debug('WebSocketHandler channelUnregistered ' + ctx)
|
||||
this.options.event.emit(ServerEvent.disconnect, ctx, 'netty channelUnregistered')
|
||||
super.channelUnregistered(ctx)
|
||||
}
|
||||
|
||||
exceptionCaught(ctx: any, cause: Error) {
|
||||
this.options.event.emit(ServerEvent.error, ctx, cause)
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { EventEmitter } from 'events'
|
||||
import { SocketIO } from '../socket-io/interfaces';
|
||||
import { AttributeKeys } from './constants';
|
||||
|
||||
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
|
||||
|
||||
export class NettyClient extends EventEmitter implements SocketIO.EngineSocket {
|
||||
private _id: string;
|
||||
private channel: any
|
||||
|
||||
server: any;
|
||||
readyState: string;
|
||||
remoteAddress: string;
|
||||
upgraded: boolean;
|
||||
request: any;
|
||||
transport: any;
|
||||
|
||||
constructor(server: any, channel: any) {
|
||||
super();
|
||||
this.server = server;
|
||||
this.readyState = 'open';
|
||||
this.remoteAddress = channel.remoteAddress() + ''
|
||||
this.upgraded = true;
|
||||
this.request = channel.attr(AttributeKeys.Request).get();
|
||||
this.transport = null;
|
||||
|
||||
this.channel = channel;
|
||||
this._id = channel.id();
|
||||
}
|
||||
|
||||
get id() {
|
||||
return this._id;
|
||||
}
|
||||
send(text: string) {
|
||||
this.channel.writeAndFlush(new TextWebSocketFrame(text))
|
||||
}
|
||||
close() {
|
||||
this.channel.close();
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import { HttpRequestHandlerAdapter } from '../netty'
|
||||
import { AttributeKeys } from './constants'
|
||||
import { ServerOptions } from 'socket-io'
|
||||
|
||||
const DefaultHttpResponse = Java.type('io.netty.handler.codec.http.DefaultHttpResponse')
|
||||
const DefaultFullHttpResponse = Java.type('io.netty.handler.codec.http.DefaultFullHttpResponse')
|
||||
const HttpHeaders = Java.type('io.netty.handler.codec.http.HttpHeaders')
|
||||
const HttpVersion = Java.type('io.netty.handler.codec.http.HttpVersion')
|
||||
const HttpResponseStatus = Java.type('io.netty.handler.codec.http.HttpResponseStatus')
|
||||
const LastHttpContent = Java.type('io.netty.handler.codec.http.LastHttpContent')
|
||||
|
||||
const File = Java.type('java.io.File')
|
||||
const Runnable = Java.type('java.lang.Runnable')
|
||||
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)
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
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 allClients: { [key: string]: NettyClient };
|
||||
|
||||
constructor(pipeline: any, options: ServerOptions) {
|
||||
super()
|
||||
this.allClients = {};
|
||||
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 nettyClient = new NettyClient(this, ctx.channel())
|
||||
this.allClients[nettyClient.id] = nettyClient
|
||||
this.emit(ServerEvent.connect, nettyClient)
|
||||
})
|
||||
connectEvent.on(ServerEvent.message, (ctx, msg) => {
|
||||
this.emit(ServerEvent.message, this.allClients[ctx.channel().id()], msg.text())
|
||||
})
|
||||
connectEvent.on(ServerEvent.error, (ctx, cause) => {
|
||||
this.emit(ServerEvent.error, this.allClients[ctx.channel().id()], cause)
|
||||
})
|
||||
}
|
||||
close() {
|
||||
if (this.pipeline.names().contains(Keys.Detect)) {
|
||||
this.pipeline.remove(Keys.Detect)
|
||||
}
|
||||
Object.values(this.allClients).forEach(client => client.close())
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
NettyWebSocketServer,
|
||||
ServerEvent,
|
||||
NettyClient
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { EventEmitter } from 'events'
|
||||
import { ServerOptions } from '../socket-io';
|
||||
import { ServerEvent } from '../socket-io/constants'
|
||||
import { TextWebSocketFrameHandlerAdapter } from '../netty'
|
||||
|
||||
export class TextWebSocketFrameHandler extends TextWebSocketFrameHandlerAdapter {
|
||||
private event: EventEmitter;
|
||||
constructor(options: ServerOptions) {
|
||||
super()
|
||||
this.event = options.event;
|
||||
}
|
||||
userEventTriggered(ctx: any, evt: any) {
|
||||
if (evt == 'HANDSHAKE_COMPLETE') {
|
||||
this.event.emit(ServerEvent.connect, ctx)
|
||||
}
|
||||
}
|
||||
channelRead0(ctx: any, msg: any) {
|
||||
this.event.emit(ServerEvent.message, ctx, msg)
|
||||
}
|
||||
exceptionCaught(ctx: any, cause: Error) {
|
||||
this.event.emit(ServerEvent.error, ctx, cause)
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,39 @@
|
||||
import { EventEmitter } from 'events'
|
||||
import { SocketIO } from './interfaces';
|
||||
import { Namespace } from './namespace';
|
||||
import { Parser } from './parser';
|
||||
import { Socket } from './socket';
|
||||
import { Namespace } from './namespace'
|
||||
import { Parser } from './parser'
|
||||
import { Socket } from './socket'
|
||||
|
||||
export class Adapter extends EventEmitter implements SocketIO.Adapter {
|
||||
nsp: Namespace;
|
||||
rooms: Rooms;
|
||||
sids: { [id: string]: { [room: string]: boolean; }; };
|
||||
export type SocketId = string
|
||||
export type Room = string
|
||||
|
||||
export interface BroadcastFlags {
|
||||
volatile?: boolean
|
||||
compress?: boolean
|
||||
local?: boolean
|
||||
broadcast?: boolean
|
||||
binary?: boolean
|
||||
}
|
||||
|
||||
export interface BroadcastOptions {
|
||||
rooms: Set<Room>
|
||||
except?: Set<SocketId>
|
||||
flags?: BroadcastFlags
|
||||
}
|
||||
|
||||
export class Adapter extends EventEmitter implements Adapter {
|
||||
rooms: Map<Room, Set<SocketId>>
|
||||
sids: Map<SocketId, Set<Room>>
|
||||
private readonly encoder: Parser
|
||||
parser: Parser
|
||||
constructor(nsp: Namespace) {
|
||||
|
||||
constructor(readonly nsp: Namespace) {
|
||||
super()
|
||||
this.nsp = nsp;
|
||||
this.rooms = new Rooms();
|
||||
this.sids = {};
|
||||
this.parser = nsp.server.parser;
|
||||
}
|
||||
add(id: string, room: string, callback?: (err?: any) => void): void {
|
||||
return this.addAll(id, [room], callback);
|
||||
this.rooms = new Map()
|
||||
this.sids = new Map()
|
||||
this.parser = nsp.server._parser
|
||||
this.encoder = this.parser
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a socket to a list of room.
|
||||
*
|
||||
@@ -27,101 +42,123 @@ export class Adapter extends EventEmitter implements SocketIO.Adapter {
|
||||
* @param {Function} callback
|
||||
* @api public
|
||||
*/
|
||||
addAll(id: string, rooms: string | any[], fn: { (err?: any): void; bind?: any; }) {
|
||||
for (var i = 0; i < rooms.length; i++) {
|
||||
var room = rooms[i];
|
||||
this.sids[id] = this.sids[id] || {};
|
||||
this.sids[id][room] = true;
|
||||
this.rooms[room] = this.rooms[room] || new Room();
|
||||
this.rooms[room].add(id);
|
||||
}
|
||||
fn && fn.bind(null, null)
|
||||
};
|
||||
del(id: string, room: string, callback?: (err?: any) => void): void {
|
||||
if (this.sids[id]) delete this.sids[id][room];
|
||||
addAll(id: SocketId, rooms: Set<Room>): Promise<void> | void {
|
||||
for (const room of rooms) {
|
||||
if (!this.sids.has(id)) {
|
||||
this.sids.set(id, new Set())
|
||||
}
|
||||
this.sids.get(id).add(room)
|
||||
|
||||
if (this.rooms.hasOwnProperty(room)) {
|
||||
this.rooms[room].del(id);
|
||||
if (this.rooms[room].length === 0) delete this.rooms[room];
|
||||
if (!this.rooms.has(room)) {
|
||||
this.rooms.set(room, new Set())
|
||||
}
|
||||
this.rooms.get(room).add(id)
|
||||
}
|
||||
}
|
||||
del(id: string, room: string, callback?: (err?: any) => void): void {
|
||||
if (this.sids.has(id)) {
|
||||
this.sids.get(id).delete(room)
|
||||
}
|
||||
|
||||
if (this.rooms.has(room)) {
|
||||
this.rooms.get(room).delete(id)
|
||||
if (this.rooms.get(room).size === 0) this.rooms.delete(room)
|
||||
}
|
||||
callback && callback.bind(null, null)
|
||||
}
|
||||
delAll(id: string): void {
|
||||
var rooms = this.sids[id];
|
||||
if (rooms) {
|
||||
for (var room in rooms) {
|
||||
if (this.rooms.hasOwnProperty(room)) {
|
||||
this.rooms[room].del(id);
|
||||
if (this.rooms[room].length === 0) delete this.rooms[room];
|
||||
}
|
||||
if (!this.sids.has(id)) {
|
||||
return
|
||||
}
|
||||
|
||||
for (const room of this.sids.get(id)) {
|
||||
if (this.rooms.has(room)) {
|
||||
this.rooms.get(room).delete(id)
|
||||
if (this.rooms.get(room).size === 0) this.rooms.delete(room)
|
||||
}
|
||||
}
|
||||
delete this.sids[id];
|
||||
|
||||
this.sids.delete(id)
|
||||
}
|
||||
broadcast(packet: any, opts: { rooms?: string[]; except?: string[]; flags?: { [flag: string]: boolean; }; }): void {
|
||||
var rooms = opts.rooms || [];
|
||||
var except = opts.except || [];
|
||||
var flags = opts.flags || {};
|
||||
var packetOpts = {
|
||||
|
||||
/**
|
||||
* Broadcasts a packet.
|
||||
*
|
||||
* Options:
|
||||
* - `flags` {Object} flags for this packet
|
||||
* - `except` {Array} sids that should be excluded
|
||||
* - `rooms` {Array} list of rooms to broadcast to
|
||||
*
|
||||
* @param {Object} packet the packet object
|
||||
* @param {Object} opts the options
|
||||
* @public
|
||||
*/
|
||||
public broadcast(packet: any, opts: BroadcastOptions): void {
|
||||
const rooms = opts.rooms
|
||||
const except = opts.except || new Set()
|
||||
const flags = opts.flags || {}
|
||||
const packetOpts = {
|
||||
preEncoded: true,
|
||||
volatile: flags.volatile,
|
||||
compress: flags.compress
|
||||
};
|
||||
var ids = {};
|
||||
var self = this;
|
||||
var socket: Socket;
|
||||
}
|
||||
const ids = new Set()
|
||||
|
||||
packet.nsp = this.nsp.name;
|
||||
let encodedPackets = this.parser.encode(packet)
|
||||
if (rooms.length) {
|
||||
for (var i = 0; i < rooms.length; i++) {
|
||||
var room = self.rooms[rooms[i]];
|
||||
if (!room) continue;
|
||||
var sockets = room.sockets;
|
||||
for (var id in sockets) {
|
||||
if (sockets.hasOwnProperty(id)) {
|
||||
if (ids[id] || ~except.indexOf(id)) continue;
|
||||
socket = self.nsp.connected[id];
|
||||
if (socket) {
|
||||
socket.packet(encodedPackets as any, packetOpts);
|
||||
ids[id] = true;
|
||||
}
|
||||
packet.nsp = this.nsp.name
|
||||
const encodedPackets = this.encoder.encode(packet)
|
||||
|
||||
if (rooms.size) {
|
||||
for (const room of rooms) {
|
||||
if (!this.rooms.has(room)) continue
|
||||
|
||||
for (const id of this.rooms.get(room)) {
|
||||
if (ids.has(id) || except.has(id)) continue
|
||||
const socket = this.nsp.sockets.get(id)
|
||||
if (socket) {
|
||||
socket.packet(encodedPackets as any, packetOpts)
|
||||
ids.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (var id in self.sids) {
|
||||
if (self.sids.hasOwnProperty(id)) {
|
||||
if (~except.indexOf(id)) continue;
|
||||
socket = self.nsp.connected[id];
|
||||
if (socket) socket.packet(encodedPackets as any, packetOpts);
|
||||
}
|
||||
for (const [id] of this.sids) {
|
||||
if (except.has(id)) continue
|
||||
const socket = this.nsp.sockets.get(id)
|
||||
if (socket) socket.packet(encodedPackets as any, packetOpts)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Rooms implements SocketIO.Rooms {
|
||||
[room: string]: Room;
|
||||
}
|
||||
/**
|
||||
* Gets a list of sockets by sid.
|
||||
*
|
||||
* @param {Set<Room>} rooms the explicit set of rooms to check.
|
||||
*/
|
||||
public sockets(rooms: Set<Room>): Promise<Set<SocketId>> {
|
||||
const sids = new Set<SocketId>()
|
||||
if (rooms.size) {
|
||||
for (const room of rooms) {
|
||||
if (!this.rooms.has(room)) continue
|
||||
for (const id of this.rooms.get(room)) {
|
||||
if (this.nsp.sockets.has(id)) {
|
||||
sids.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const [id] of this.sids) {
|
||||
if (this.nsp.sockets.has(id)) sids.add(id)
|
||||
}
|
||||
}
|
||||
return Promise.resolve(sids)
|
||||
}
|
||||
|
||||
class Room implements SocketIO.Room {
|
||||
sockets: { [id: string]: boolean; };
|
||||
length: number;
|
||||
constructor() {
|
||||
this.sockets = {};
|
||||
this.length = 0;
|
||||
/**
|
||||
* Gets the list of rooms a given socket has joined.
|
||||
*
|
||||
* @param {SocketId} id the socket id
|
||||
*/
|
||||
public socketRooms(id: SocketId): Set<Room> | undefined {
|
||||
return this.sids.get(id)
|
||||
}
|
||||
add(id) {
|
||||
if (!this.sockets.hasOwnProperty(id)) {
|
||||
this.sockets[id] = true;
|
||||
this.length++;
|
||||
}
|
||||
}
|
||||
del(id) {
|
||||
if (this.sockets.hasOwnProperty(id)) {
|
||||
delete this.sockets[id];
|
||||
this.length--;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,107 +1,360 @@
|
||||
import { EventEmitter } from 'events'
|
||||
import { Parser } from './parser'
|
||||
import { Packet } from './packet';
|
||||
import { SocketIO } from './interfaces'
|
||||
import { Server, Socket } from './index';
|
||||
import { PacketTypes, SubPacketTypes } from './types';
|
||||
import { ServerEvent } from './constants';
|
||||
import { Packet } from './packet'
|
||||
import { Namespace, Server, Socket } from './index'
|
||||
import { PacketTypes, SubPacketTypes } from './types'
|
||||
import { ServerEvent } from './constants'
|
||||
import { SocketId } from './adapter'
|
||||
import { Transport } from '../transport'
|
||||
|
||||
const parser = new Parser();
|
||||
const parser = new Parser()
|
||||
|
||||
export class Client extends EventEmitter implements SocketIO.Client {
|
||||
id: string;
|
||||
server: Server;
|
||||
conn: SocketIO.EngineSocket;
|
||||
request: any;
|
||||
sockets: { [id: string]: Socket; };
|
||||
nsps: { [nsp: string]: SocketIO.Socket; };
|
||||
connectBuffer: any;
|
||||
export class Client extends EventEmitter {
|
||||
public readonly conn: Transport
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
readonly id: string
|
||||
private readonly server: Server
|
||||
// private readonly encoder: Encoder
|
||||
private readonly decoder: any
|
||||
private sockets: Map<SocketId, Socket>
|
||||
private nsps: Map<string, Socket>
|
||||
private connectTimeout: NodeJS.Timeout
|
||||
|
||||
constructor(server: Server, engine: SocketIO.EngineSocket) {
|
||||
super();
|
||||
this.server = server;
|
||||
this.conn = engine;
|
||||
this.id = this.conn.id + '';
|
||||
this.request = engine.request;
|
||||
this.sockets = {};
|
||||
this.nsps = {};
|
||||
private checkIntervalTimer: NodeJS.Timeout
|
||||
private upgradeTimeoutTimer: NodeJS.Timeout
|
||||
private pingTimeoutTimer: NodeJS.Timeout
|
||||
private pingIntervalTimer: NodeJS.Timeout
|
||||
|
||||
constructor(server: Server, conn) {
|
||||
super()
|
||||
this.server = server
|
||||
this.conn = conn
|
||||
// this.encoder = server.encoder
|
||||
this.decoder = server._parser
|
||||
this.id = this.conn.id + ''
|
||||
this.setup()
|
||||
// =============================
|
||||
this.sockets = new Map()
|
||||
this.nsps = new Map()
|
||||
// ================== engine.io
|
||||
this.onOpen()
|
||||
// ================== Transport
|
||||
this.conn.on(ServerEvent.disconnect, (reason) => {
|
||||
this.onclose(reason)
|
||||
})
|
||||
}
|
||||
connect(name, query) {
|
||||
if (this.server.nsps[name]) {
|
||||
// console.debug(`connecting to namespace ${name}`);
|
||||
return this.doConnect(name, query);
|
||||
}
|
||||
this.server.checkNamespace(name, query, (dynamicNsp) => {
|
||||
if (dynamicNsp) {
|
||||
// console.debug('dynamic namespace %s was created', dynamicNsp.name);
|
||||
this.doConnect(name, query);
|
||||
/**
|
||||
* @return the reference to the request that originated the Engine.IO connection
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
public get request(): any /**IncomingMessage */ {
|
||||
return this.conn.request
|
||||
}
|
||||
/**
|
||||
* Sets up event listeners.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private setup() {
|
||||
// @ts-ignore
|
||||
// this.decoder.on("decoded", this.ondecoded)
|
||||
this.conn.on("data", this.ondata.bind(this))
|
||||
this.conn.on("error", this.onerror.bind(this))
|
||||
this.conn.on("close", this.onclose.bind(this))
|
||||
console.debug(`setup client ${this.id}`)
|
||||
this.connectTimeout = setTimeout(() => {
|
||||
if (this.nsps.size === 0) {
|
||||
console.debug("no namespace joined yet, close the client")
|
||||
this.close()
|
||||
} else {
|
||||
// console.debug('creation of namespace %s was denied', name);
|
||||
this.packet({
|
||||
console.debug("the client has already joined a namespace, nothing to do")
|
||||
}
|
||||
}, this.server._connectTimeout)
|
||||
}
|
||||
/**
|
||||
* Connects a client to a namespace.
|
||||
*
|
||||
* @param {String} name - the namespace
|
||||
* @param {Object} auth - the auth parameters
|
||||
* @private
|
||||
*/
|
||||
private connect(name: string, auth: object = {}) {
|
||||
console.debug(`client ${this.id} connecting to namespace ${name} has: ${this.server._nsps.has(name)}`)
|
||||
if (this.server._nsps.has(name)) {
|
||||
return this.doConnect(name, auth)
|
||||
}
|
||||
|
||||
this.server._checkNamespace(name, auth, (dynamicNsp: Namespace) => {
|
||||
if (dynamicNsp) {
|
||||
console.debug(`dynamic namespace ${dynamicNsp.name} was created`)
|
||||
this.doConnect(name, auth)
|
||||
} else {
|
||||
console.debug(`creation of namespace ${name} was denied`)
|
||||
this._packet({
|
||||
type: PacketTypes.MESSAGE,
|
||||
sub_type: SubPacketTypes.ERROR,
|
||||
nsp: name,
|
||||
data: 'Invalid namespace'
|
||||
});
|
||||
data: {
|
||||
message: "Invalid namespace"
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
doConnect(name, query) {
|
||||
var nsp = this.server.of(name);
|
||||
if ('/' != name && !this.nsps['/']) {
|
||||
this.connectBuffer.push(name);
|
||||
return;
|
||||
doConnect(name, auth: object) {
|
||||
if (this.connectTimeout) {
|
||||
clearTimeout(this.connectTimeout)
|
||||
this.connectTimeout = null
|
||||
}
|
||||
var socket = nsp.add(this, query, () => {
|
||||
this.sockets[socket.id] = socket;
|
||||
this.nsps[nsp.name] = socket;
|
||||
const nsp = this.server.of(name)
|
||||
|
||||
if ('/' == nsp.name && this.connectBuffer.length > 0) {
|
||||
this.connectBuffer.forEach(this.connect, this);
|
||||
this.connectBuffer = [];
|
||||
}
|
||||
});
|
||||
nsp._add(this, auth, (socket: Socket) => {
|
||||
this.sockets.set(socket.id, socket)
|
||||
this.nsps.set(nsp.name, socket)
|
||||
})
|
||||
}
|
||||
packet(packet: Packet, opts: any = { preEncoded: false }) {
|
||||
this.conn.send(opts.preEncoded ? packet as unknown as string : parser.encode(packet))
|
||||
/**
|
||||
* Disconnects from all namespaces and closes transport.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_disconnect() {
|
||||
for (const socket of this.sockets.values()) {
|
||||
socket.disconnect()
|
||||
}
|
||||
this.sockets.clear()
|
||||
this.close()
|
||||
}
|
||||
/**
|
||||
* Removes a socket. Called by each `Socket`.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_remove(socket: Socket) {
|
||||
if (this.sockets.has(socket.id)) {
|
||||
this.sockets.delete(socket.id)
|
||||
this.nsps.delete(socket.nsp.name)
|
||||
} else {
|
||||
console.debug(`ignoring remove for ${socket.id}`,)
|
||||
}
|
||||
process.nextTick(() => {
|
||||
if (this.sockets.size == 0) {
|
||||
this.onclose('no live socket')
|
||||
}
|
||||
})
|
||||
}
|
||||
/**
|
||||
* Closes the underlying connection.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private close() {
|
||||
console.debug(`client ${this.id} close`)
|
||||
if ("open" == this.conn.readyState) {
|
||||
console.debug("forcing transport close")
|
||||
this.onclose("forced server close")
|
||||
this.conn.close()
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Writes a packet to the transport.
|
||||
*
|
||||
* @param {Object} packet object
|
||||
* @param {Object} opts
|
||||
* @private
|
||||
*/
|
||||
_packet(packet: Packet, opts = { preEncoded: false }) {
|
||||
// opts = opts || {}
|
||||
// const self = this
|
||||
|
||||
// // this writes to the actual connection
|
||||
// function writeToEngine(encodedPackets) {
|
||||
// if (opts.volatile && !self.conn.transport.writable) return
|
||||
// for (let i = 0; i < encodedPackets.length; i++) {
|
||||
// self.conn.write(encodedPackets[i], { compress: opts.compress })
|
||||
// }
|
||||
// }
|
||||
|
||||
// if ("open" == this.conn.readyState) {
|
||||
// debug("writing packet %j", packet)
|
||||
// if (!opts.preEncoded) {
|
||||
// // not broadcasting, need to encode
|
||||
// writeToEngine(this.encoder.encode(packet)) // encode, then write results to engine
|
||||
// } else {
|
||||
// // a broadcast pre-encodes a packet
|
||||
// writeToEngine(packet)
|
||||
// }
|
||||
// } else {
|
||||
// debug("ignoring packet write %j", packet)
|
||||
// }
|
||||
if ("open" == this.conn.readyState) {
|
||||
this.conn.send(opts.preEncoded ? packet as unknown as string : parser.encode(packet))
|
||||
} else {
|
||||
console.debug(`ignoring write packet ${JSON.stringify(packet)} to client ${this.id} is already close!`)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called with incoming transport data.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondata(data) {
|
||||
// try/catch is needed for protocol violations (GH-1880)
|
||||
try {
|
||||
this.decoder.add(data)
|
||||
} catch (e) {
|
||||
this.onerror(e)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called when parser fully decodes a packet.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondecoded(packet: Packet) {
|
||||
if (SubPacketTypes.CONNECT == packet.sub_type) {
|
||||
this.connect(packet.nsp, packet.data)
|
||||
} else {
|
||||
process.nextTick(() => {
|
||||
const socket = this.nsps.get(packet.nsp)
|
||||
if (socket) {
|
||||
socket._onpacket(packet)
|
||||
} else {
|
||||
console.debug(`client ${this.id} no socket for namespace ${packet.nsp}.`)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handles an error.
|
||||
*
|
||||
* @param {Object} err object
|
||||
* @private
|
||||
*/
|
||||
private onerror(err) {
|
||||
for (const socket of this.sockets.values()) {
|
||||
socket._onerror(err)
|
||||
}
|
||||
this.conn.close()
|
||||
}
|
||||
onclose(reason?: string) {
|
||||
// debug('client close with reason %s', reason);
|
||||
// ignore a potential subsequent `close` event
|
||||
this.destroy();
|
||||
// `nsps` and `sockets` are cleaned up seamlessly
|
||||
for (var id in this.sockets) {
|
||||
if (this.sockets.hasOwnProperty(id)) {
|
||||
this.sockets[id].onclose(reason);
|
||||
}
|
||||
this.conn.readyState = "closing"
|
||||
// ======= engine.io
|
||||
this.onClose(reason)
|
||||
// cleanup connectTimeout
|
||||
if (this.connectTimeout) {
|
||||
clearTimeout(this.connectTimeout)
|
||||
this.connectTimeout = null
|
||||
}
|
||||
this.sockets = {};
|
||||
console.debug(`client ${this.id} close with reason ${reason}`)
|
||||
// ignore a potential subsequent `close` event
|
||||
// `nsps` and `sockets` are cleaned up seamlessly
|
||||
for (const socket of this.sockets.values()) {
|
||||
socket._onclose(reason)
|
||||
}
|
||||
this.sockets.clear()
|
||||
// this.decoder.destroy(); // clean up decoder
|
||||
}
|
||||
disconnect() {
|
||||
if ('open' == this.conn.readyState) {
|
||||
// debug('forcing transport close');
|
||||
this.conn.close();
|
||||
this.onclose('forced server close');
|
||||
}
|
||||
}
|
||||
remove(socket: Socket) {
|
||||
if (this.sockets.hasOwnProperty(socket.id)) {
|
||||
var nsp = this.sockets[socket.id].nsp.name;
|
||||
delete this.sockets[socket.id];
|
||||
delete this.nsps[nsp];
|
||||
} else {
|
||||
// debug('ignoring remove for %s', socket.id);
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
// this.conn.removeListener('data', this.ondata);
|
||||
// this.conn.removeListener('error', this.onerror);
|
||||
// this.conn.removeListener('close', this.onclose);
|
||||
// this.decoder.removeListener('decoded', this.ondecoded);
|
||||
};
|
||||
}
|
||||
|
||||
//================== engine.io
|
||||
onOpen() {
|
||||
this.conn.readyState = "open"
|
||||
this._packet({
|
||||
type: PacketTypes.OPEN,
|
||||
data: {
|
||||
sid: this.id,
|
||||
upgrades: [],
|
||||
pingInterval: this.server.options.pingInterval,
|
||||
pingTimeout: this.server.options.pingTimeout
|
||||
}
|
||||
})
|
||||
this.schedulePing()
|
||||
}
|
||||
|
||||
onPacket(packet: Packet) {
|
||||
if ("open" === this.conn.readyState) {
|
||||
// export packet event
|
||||
// debug("packet")
|
||||
// this.emit("packet", packet)
|
||||
|
||||
// Reset ping timeout on any packet, incoming data is a good sign of
|
||||
// other side's liveness
|
||||
this.resetPingTimeout(this.server.options.pingInterval + this.server.options.pingTimeout * 2)
|
||||
switch (packet.type) {
|
||||
case PacketTypes.PING:
|
||||
this._packet({
|
||||
type: PacketTypes.PONG,
|
||||
data: packet.data
|
||||
})
|
||||
break
|
||||
case PacketTypes.PONG:
|
||||
this.schedulePing()
|
||||
break
|
||||
case PacketTypes.UPGRADE:
|
||||
break
|
||||
case PacketTypes.MESSAGE:
|
||||
this.ondecoded(packet)
|
||||
break
|
||||
case PacketTypes.CLOSE:
|
||||
this.onclose()
|
||||
break
|
||||
default:
|
||||
console.log(`client ${this.id} reciver unknow packet type: ${packet.type}`)
|
||||
}
|
||||
} else {
|
||||
console.debug(`packet received with closed client ${this.id}`)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon transport considered closed.
|
||||
* Possible reasons: `ping timeout`, `client error`, `parse error`,
|
||||
* `transport error`, `server close`, `transport close`
|
||||
*/
|
||||
onClose(reason, description?: string) {
|
||||
// if ("closed" !== this.conn.readyState) {
|
||||
clearTimeout(this.pingIntervalTimer)
|
||||
clearTimeout(this.pingTimeoutTimer)
|
||||
|
||||
clearInterval(this.checkIntervalTimer)
|
||||
this.checkIntervalTimer = null
|
||||
clearTimeout(this.upgradeTimeoutTimer)
|
||||
// this.emit("close", reason, description)
|
||||
// }
|
||||
}
|
||||
/**
|
||||
* Pings client every `this.pingInterval` and expects response
|
||||
* within `this.pingTimeout` or closes connection.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
schedulePing() {
|
||||
clearTimeout(this.pingIntervalTimer)
|
||||
this.pingIntervalTimer = setTimeout(() => {
|
||||
this.resetPingTimeout(this.server.options.pingTimeout)
|
||||
process.nextTick(() => this._packet({ type: PacketTypes.PING }))
|
||||
}, this.server.options.pingInterval)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets ping timeout.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
resetPingTimeout(timeout) {
|
||||
clearTimeout(this.pingTimeoutTimer)
|
||||
this.pingTimeoutTimer = setTimeout(() => {
|
||||
if (this.conn.readyState === "closed") return
|
||||
this.onclose("ping timeout")
|
||||
}, timeout)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,5 +4,6 @@ export enum ServerEvent {
|
||||
connection = 'connection',
|
||||
message = 'message',
|
||||
error = 'error',
|
||||
disconnect = 'disconnect'
|
||||
}
|
||||
disconnecting = 'disconnecting',
|
||||
disconnect = 'disconnect',
|
||||
}
|
||||
|
||||
@@ -3,221 +3,677 @@ import { EventEmitter } from 'events'
|
||||
import { ServerEvent } from './constants'
|
||||
import { Namespace } from './namespace'
|
||||
import { Client } from './client'
|
||||
import { SocketIO } from './interfaces'
|
||||
import { Parser } from './parser'
|
||||
import { PacketTypes, SubPacketTypes } from './types'
|
||||
import { Packet } from './packet'
|
||||
import { Socket } from './socket'
|
||||
import { Adapter } from './adapter'
|
||||
import { Transport } from '../transport'
|
||||
import { ParentNamespace } from './parent-namespace'
|
||||
|
||||
interface ServerOptions extends SocketIO.ServerOptions {
|
||||
interface EngineOptions {
|
||||
/**
|
||||
* how many ms without a pong packet to consider the connection closed
|
||||
* @default 5000
|
||||
*/
|
||||
pingTimeout: number
|
||||
/**
|
||||
* how many ms before sending a new ping packet
|
||||
* @default 25000
|
||||
*/
|
||||
pingInterval: number
|
||||
/**
|
||||
* how many ms before an uncompleted transport upgrade is cancelled
|
||||
* @default 10000
|
||||
*/
|
||||
upgradeTimeout: number
|
||||
/**
|
||||
* how many bytes or characters a message can be, before closing the session (to avoid DoS).
|
||||
* @default 1e5 (100 KB)
|
||||
*/
|
||||
maxHttpBufferSize: number
|
||||
/**
|
||||
* A function that receives a given handshake or upgrade request as its first parameter,
|
||||
* and can decide whether to continue or not. The second argument is a function that needs
|
||||
* to be called with the decided information: fn(err, success), where success is a boolean
|
||||
* value where false means that the request is rejected, and err is an error code.
|
||||
*/
|
||||
// allowRequest: (
|
||||
// req: http.IncomingMessage,
|
||||
// fn: (err: string | null | undefined, success: boolean) => void
|
||||
// ) => void
|
||||
/**
|
||||
* the low-level transports that are enabled
|
||||
* @default ["polling", "websocket"]
|
||||
*/
|
||||
// transports: Transport[]
|
||||
/**
|
||||
* whether to allow transport upgrades
|
||||
* @default true
|
||||
*/
|
||||
allowUpgrades: boolean
|
||||
/**
|
||||
* parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable.
|
||||
* @default false
|
||||
*/
|
||||
perMessageDeflate: boolean | object
|
||||
/**
|
||||
* parameters of the http compression for the polling transports (see zlib api docs). Set to false to disable.
|
||||
* @default true
|
||||
*/
|
||||
httpCompression: boolean | object
|
||||
/**
|
||||
* what WebSocket server implementation to use. Specified module must
|
||||
* conform to the ws interface (see ws module api docs). Default value is ws.
|
||||
* An alternative c++ addon is also available by installing uws module.
|
||||
*/
|
||||
wsEngine: string
|
||||
/**
|
||||
* an optional packet which will be concatenated to the handshake packet emitted by Engine.IO.
|
||||
*/
|
||||
initialPacket: any
|
||||
/**
|
||||
* configuration of the cookie that contains the client sid to send as part of handshake response headers. This cookie
|
||||
* might be used for sticky-session. Defaults to not sending any cookie.
|
||||
* @default false
|
||||
*/
|
||||
// cookie: CookieSerializeOptions | boolean
|
||||
/**
|
||||
* the options that will be forwarded to the cors module
|
||||
*/
|
||||
// cors: CorsOptions
|
||||
}
|
||||
|
||||
interface AttachOptions {
|
||||
/**
|
||||
* name of the path to capture
|
||||
* @default "/engine.io"
|
||||
*/
|
||||
path: string
|
||||
/**
|
||||
* destroy unhandled upgrade requests
|
||||
* @default true
|
||||
*/
|
||||
destroyUpgrade: boolean
|
||||
/**
|
||||
* milliseconds after which unhandled requests are ended
|
||||
* @default 1000
|
||||
*/
|
||||
destroyUpgradeTimeout: number
|
||||
}
|
||||
|
||||
interface EngineAttachOptions extends EngineOptions, AttachOptions { }
|
||||
|
||||
interface ServerOptions extends EngineAttachOptions {
|
||||
event?: EventEmitter
|
||||
root?: string
|
||||
/**
|
||||
* name of the path to capture
|
||||
* @default "/socket.io"
|
||||
*/
|
||||
path: string
|
||||
/**
|
||||
* whether to serve the client files
|
||||
* @default true
|
||||
*/
|
||||
serveClient: boolean
|
||||
/**
|
||||
* the adapter to use
|
||||
* @default the in-memory adapter (https://github.com/socketio/socket.io-adapter)
|
||||
*/
|
||||
adapter: any
|
||||
/**
|
||||
* the parser to use
|
||||
* @default the default parser (https://github.com/socketio/socket.io-parser)
|
||||
*/
|
||||
parser: any
|
||||
/**
|
||||
* how many ms before a client without namespace is closed
|
||||
* @default 45000
|
||||
*/
|
||||
connectTimeout: number
|
||||
}
|
||||
|
||||
interface WebSocketServer extends EventEmitter {
|
||||
close(): void
|
||||
}
|
||||
|
||||
class Server implements SocketIO.Server {
|
||||
class Server {
|
||||
public readonly sockets: Namespace
|
||||
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_parser: Parser
|
||||
private readonly encoder
|
||||
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_nsps: Map<string, Namespace>
|
||||
private parentNsps: Map<
|
||||
| string
|
||||
| RegExp
|
||||
| ((
|
||||
name: string,
|
||||
query: object,
|
||||
fn: (err: Error, success: boolean) => void
|
||||
) => void),
|
||||
ParentNamespace
|
||||
> = new Map();
|
||||
private _adapter: Adapter
|
||||
// private _serveClient: boolean;
|
||||
private eio
|
||||
private engine: { ws: any }
|
||||
private _path: string
|
||||
private clientPathRegex: RegExp
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_connectTimeout: number
|
||||
|
||||
options: Partial<ServerOptions>
|
||||
private websocketServer: WebSocketServer
|
||||
private allClients: { [key: string]: Client }
|
||||
private allClients: Map<string, Client>
|
||||
|
||||
engine: { ws: any }
|
||||
nsps: { [namespace: string]: Namespace }
|
||||
sockets: Namespace
|
||||
json: SocketIO.Server
|
||||
volatile: SocketIO.Server
|
||||
local: SocketIO.Server
|
||||
parser = new Parser();
|
||||
_adapter: Adapter
|
||||
options: ServerOptions
|
||||
|
||||
constructor(instance: any, options: ServerOptions) {
|
||||
constructor(instance: any, options: Partial<ServerOptions>) {
|
||||
if (!instance) { throw new Error('instance can\'t be undefiend!') }
|
||||
this.allClients = {}
|
||||
this.nsps = {}
|
||||
this.sockets = new Namespace('/', this)
|
||||
this.nsps['/'] = this.sockets
|
||||
if (instance.class.name.startsWith('io.netty.channel')) {
|
||||
let { NettyWebSocketServer } = require("../server")
|
||||
this.websocketServer = new NettyWebSocketServer(instance, Object.assign({
|
||||
event: new EventEmitter(),
|
||||
path: '/socket.io',
|
||||
root: root + '/wwwroot'
|
||||
}, options))
|
||||
} else {
|
||||
let { TomcatWebSocketServer } = require("../tomcat/server")
|
||||
this.websocketServer = new TomcatWebSocketServer(instance, options)
|
||||
}
|
||||
this.options = Object.assign({
|
||||
event: new EventEmitter(),
|
||||
path: '/socket.io',
|
||||
root: root + '/wwwroot',
|
||||
serveClient: false,
|
||||
connectTimeout: 45000,
|
||||
wsEngine: process.env.EIO_WS_ENGINE || "ws",
|
||||
pingTimeout: 5000,
|
||||
pingInterval: 25000,
|
||||
upgradeTimeout: 10000,
|
||||
maxHttpBufferSize: 1e6,
|
||||
transports: 'websocket',
|
||||
allowUpgrades: true,
|
||||
httpCompression: {
|
||||
threshold: 1024
|
||||
},
|
||||
cors: false
|
||||
}, options)
|
||||
this.initServerConfig()
|
||||
this.sockets = this.of('/')
|
||||
this.selectServerImpl(instance)
|
||||
this.initServer()
|
||||
}
|
||||
/**
|
||||
* Sets/gets whether client code is being served.
|
||||
*
|
||||
* @param {Boolean} v - whether to serve client code
|
||||
* @return {Server|Boolean} self when setting or value when getting
|
||||
* @public
|
||||
*/
|
||||
public serveClient(v: boolean): Server
|
||||
public serveClient(): boolean
|
||||
public serveClient(v?: boolean): Server | boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
/**
|
||||
* Executes the middleware for an incoming namespace not already created on the server.
|
||||
*
|
||||
* @param {String} name - name of incoming namespace
|
||||
* @param {Object} auth - the auth parameters
|
||||
* @param {Function} fn - callback
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_checkNamespace(
|
||||
name: string,
|
||||
auth: object,
|
||||
fn: (nsp: Namespace) => void
|
||||
) {
|
||||
// if (this.parentNsps.size === 0) return fn(false)
|
||||
|
||||
checkRequest(req: any, fn: (err: any, success: boolean) => void): void {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
serveClient(): boolean
|
||||
serveClient(v: boolean): SocketIO.Server
|
||||
serveClient(v?: any): boolean | SocketIO.Server {
|
||||
throw new Error("Method not implemented.")
|
||||
// const keysIterator = this.parentNsps.keys()
|
||||
|
||||
// const run = () => {
|
||||
// let nextFn = keysIterator.next()
|
||||
// if (nextFn.done) {
|
||||
// return fn(false)
|
||||
// }
|
||||
// nextFn.value(name, auth, (err, allow) => {
|
||||
// if (err || !allow) {
|
||||
// run()
|
||||
// } else {
|
||||
// fn(this.parentNsps.get(nextFn.value).createChild(name))
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
fn(undefined)
|
||||
}
|
||||
/**
|
||||
* Sets the client serving path.
|
||||
*
|
||||
* @param {String} v pathname
|
||||
* @return {Server|String} self when setting or value when getting
|
||||
* @public
|
||||
*/
|
||||
path(): string
|
||||
path(v: string): SocketIO.Server
|
||||
path(v?: any): string | SocketIO.Server {
|
||||
if (!arguments.length) return this.options.path
|
||||
this.options.path = v.replace(/\/$/, '')
|
||||
path(v: string): Server
|
||||
path(v?: any): string | Server {
|
||||
if (!arguments.length) return this._path
|
||||
|
||||
this._path = v.replace(/\/$/, "")
|
||||
|
||||
const escapedPath = this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")
|
||||
this.clientPathRegex = new RegExp(
|
||||
"^" +
|
||||
escapedPath +
|
||||
"/socket\\.io(\\.min|\\.msgpack\\.min)?\\.js(\\.map)?$"
|
||||
)
|
||||
return this
|
||||
}
|
||||
adapter(): Adapter
|
||||
adapter(v: any): SocketIO.Server
|
||||
adapter(v?: any): Adapter | SocketIO.Server {
|
||||
/**
|
||||
* Set the delay after which a client without namespace is closed
|
||||
* @param v
|
||||
* @public
|
||||
*/
|
||||
public connectTimeout(v: number): Server
|
||||
public connectTimeout(): number
|
||||
public connectTimeout(v?: number): Server | number {
|
||||
if (v === undefined) return this._connectTimeout
|
||||
this._connectTimeout = v
|
||||
return this
|
||||
}
|
||||
/**
|
||||
* Sets the adapter for rooms.
|
||||
*
|
||||
* @param {Adapter} v pathname
|
||||
* @return {Server|Adapter} self when setting or value when getting
|
||||
* @public
|
||||
*/
|
||||
public adapter(): any
|
||||
public adapter(v: any)
|
||||
public adapter(v?): Server | any {
|
||||
if (!arguments.length) return this._adapter
|
||||
this._adapter = v
|
||||
for (var i in this.nsps) {
|
||||
if (this.nsps.hasOwnProperty(i)) {
|
||||
this.nsps[i].initAdapter()
|
||||
}
|
||||
for (const nsp of this._nsps.values()) {
|
||||
nsp._initAdapter()
|
||||
}
|
||||
return this
|
||||
}
|
||||
origins(): string | string[]
|
||||
origins(v: string | string[]): SocketIO.Server
|
||||
origins(fn: (origin: string, callback: (error: string, success: boolean) => void) => void): SocketIO.Server
|
||||
origins(fn?: any): string | string[] | SocketIO.Server {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
attach(srv: any, opts?: SocketIO.ServerOptions): SocketIO.Server
|
||||
attach(port: number, opts?: SocketIO.ServerOptions): SocketIO.Server
|
||||
attach(port: any, opts?: any): SocketIO.Server {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
listen(srv: any, opts?: SocketIO.ServerOptions): SocketIO.Server
|
||||
listen(port: number, opts?: SocketIO.ServerOptions): SocketIO.Server
|
||||
listen(port: any, opts?: any): SocketIO.Server {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
bind(srv: any): SocketIO.Server {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
onconnection(socket: Client): SocketIO.Server {
|
||||
this.allClients[socket.id] = socket
|
||||
socket.packet({
|
||||
type: PacketTypes.OPEN,
|
||||
data: {
|
||||
sid: socket.id,
|
||||
upgrades: [],
|
||||
pingInterval: 25000,
|
||||
pingTimeout: 5000
|
||||
}
|
||||
})
|
||||
this.sockets.add(socket)
|
||||
// /**
|
||||
// * Attaches socket.io to a server or port.
|
||||
// *
|
||||
// * @param {http.Server|Number} srv - server or port
|
||||
// * @param {Object} opts - options passed to engine.io
|
||||
// * @return {Server} self
|
||||
// * @public
|
||||
// */
|
||||
// public listen(srv: http.Server, opts?: Partial<ServerOptions>): Server
|
||||
// public listen(srv: number, opts?: Partial<ServerOptions>): Server
|
||||
// public listen(srv: any, opts: Partial<ServerOptions> = {}): Server {
|
||||
// return this.attach(srv, opts)
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Attaches socket.io to a server or port.
|
||||
// *
|
||||
// * @param {http.Server|Number} srv - server or port
|
||||
// * @param {Object} opts - options passed to engine.io
|
||||
// * @return {Server} self
|
||||
// * @public
|
||||
// */
|
||||
// public attach(srv: http.Server, opts?: Partial<ServerOptions>): Server
|
||||
// public attach(port: number, opts?: Partial<ServerOptions>): Server
|
||||
// public attach(srv: any, opts: Partial<ServerOptions> = {}): Server {
|
||||
// if ("function" == typeof srv) {
|
||||
// const msg =
|
||||
// "You are trying to attach socket.io to an express " +
|
||||
// "request handler function. Please pass a http.Server instance."
|
||||
// throw new Error(msg)
|
||||
// }
|
||||
|
||||
// // handle a port as a string
|
||||
// if (Number(srv) == srv) {
|
||||
// srv = Number(srv)
|
||||
// }
|
||||
|
||||
// if ("number" == typeof srv) {
|
||||
// debug("creating http server and binding to %d", srv)
|
||||
// const port = srv
|
||||
// srv = http.createServer((req, res) => {
|
||||
// res.writeHead(404)
|
||||
// res.end()
|
||||
// })
|
||||
// srv.listen(port)
|
||||
// }
|
||||
|
||||
// // set engine.io path to `/socket.io`
|
||||
// opts.path = opts.path || this._path
|
||||
|
||||
// this.initEngine(srv, opts)
|
||||
|
||||
// return this
|
||||
// }
|
||||
// /**
|
||||
// * Initialize engine
|
||||
// *
|
||||
// * @param srv - the server to attach to
|
||||
// * @param opts - options passed to engine.io
|
||||
// * @private
|
||||
// */
|
||||
// private initEngine(srv: http.Server, opts: Partial<EngineAttachOptions>) {
|
||||
// // initialize engine
|
||||
// debug("creating engine.io instance with opts %j", opts)
|
||||
// this.eio = engine.attach(srv, opts)
|
||||
|
||||
// // attach static file serving
|
||||
// if (this._serveClient) this.attachServe(srv)
|
||||
|
||||
// // Export http server
|
||||
// this.httpServer = srv
|
||||
|
||||
// // bind to engine events
|
||||
// this.bind(this.eio)
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Attaches the static file serving.
|
||||
// *
|
||||
// * @param {Function|http.Server} srv http server
|
||||
// * @private
|
||||
// */
|
||||
// private attachServe(srv) {
|
||||
// debug("attaching client serving req handler")
|
||||
|
||||
// const evs = srv.listeners("request").slice(0)
|
||||
// srv.removeAllListeners("request")
|
||||
// srv.on("request", (req, res) => {
|
||||
// if (this.clientPathRegex.test(req.url)) {
|
||||
// this.serve(req, res)
|
||||
// } else {
|
||||
// for (let i = 0; i < evs.length; i++) {
|
||||
// evs[i].call(srv, req, res)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
// /**
|
||||
// * Handles a request serving of client source and map
|
||||
// *
|
||||
// * @param {http.IncomingMessage} req
|
||||
// * @param {http.ServerResponse} res
|
||||
// * @private
|
||||
// */
|
||||
// private serve(req: http.IncomingMessage, res: http.ServerResponse) {
|
||||
// const filename = req.url.replace(this._path, "")
|
||||
// const isMap = dotMapRegex.test(filename)
|
||||
// const type = isMap ? "map" : "source"
|
||||
|
||||
// // Per the standard, ETags must be quoted:
|
||||
// // https://tools.ietf.org/html/rfc7232#section-2.3
|
||||
// const expectedEtag = '"' + clientVersion + '"'
|
||||
|
||||
// const etag = req.headers["if-none-match"]
|
||||
// if (etag) {
|
||||
// if (expectedEtag == etag) {
|
||||
// debug("serve client %s 304", type)
|
||||
// res.writeHead(304)
|
||||
// res.end()
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
|
||||
// debug("serve client %s", type)
|
||||
|
||||
// res.setHeader("Cache-Control", "public, max-age=0")
|
||||
// res.setHeader(
|
||||
// "Content-Type",
|
||||
// "application/" + (isMap ? "json" : "javascript")
|
||||
// )
|
||||
// res.setHeader("ETag", expectedEtag)
|
||||
|
||||
// if (!isMap) {
|
||||
// res.setHeader("X-SourceMap", filename.substring(1) + ".map")
|
||||
// }
|
||||
// Server.sendFile(filename, req, res)
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * @param filename
|
||||
// * @param req
|
||||
// * @param res
|
||||
// * @private
|
||||
// */
|
||||
// private static sendFile(
|
||||
// filename: string,
|
||||
// req: http.IncomingMessage,
|
||||
// res: http.ServerResponse
|
||||
// ) {
|
||||
// const readStream = createReadStream(
|
||||
// path.join(__dirname, "../client-dist/", filename)
|
||||
// )
|
||||
// const encoding = accepts(req).encodings(["br", "gzip", "deflate"])
|
||||
|
||||
// const onError = err => {
|
||||
// if (err) {
|
||||
// res.end()
|
||||
// }
|
||||
// }
|
||||
|
||||
// switch (encoding) {
|
||||
// case "br":
|
||||
// res.writeHead(200, { "content-encoding": "br" })
|
||||
// readStream.pipe(createBrotliCompress()).pipe(res)
|
||||
// pipeline(readStream, createBrotliCompress(), res, onError)
|
||||
// break
|
||||
// case "gzip":
|
||||
// res.writeHead(200, { "content-encoding": "gzip" })
|
||||
// pipeline(readStream, createGzip(), res, onError)
|
||||
// break
|
||||
// case "deflate":
|
||||
// res.writeHead(200, { "content-encoding": "deflate" })
|
||||
// pipeline(readStream, createDeflate(), res, onError)
|
||||
// break
|
||||
// default:
|
||||
// res.writeHead(200)
|
||||
// pipeline(readStream, res, onError)
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Binds socket.io to an engine.io instance.
|
||||
// *
|
||||
// * @param {engine.Server} engine engine.io (or compatible) server
|
||||
// * @return {Server} self
|
||||
// * @public
|
||||
// */
|
||||
// public bind(engine): Server {
|
||||
// this.engine = engine
|
||||
// this.engine.on("connection", this.onconnection.bind(this))
|
||||
// return this
|
||||
// }
|
||||
/**
|
||||
* Called with each incoming transport connection.
|
||||
*
|
||||
* @param {engine.Socket} conn
|
||||
* @return {Server} self
|
||||
* @private
|
||||
*/
|
||||
private onconnection(conn): Server {
|
||||
console.debug(`incoming connection with id ${conn.id}`)
|
||||
let client = new Client(this, conn)
|
||||
this.allClients.set(conn.id, client)
|
||||
return this
|
||||
}
|
||||
of(nsp: string): Namespace {
|
||||
if (!this.nsps[nsp]) {
|
||||
this.nsps[nsp] = new Namespace(nsp, this)
|
||||
// of(nsp: string): Namespace {
|
||||
// if (!this._nsps.has(nsp)) {
|
||||
// console.debug(`create Namespace ${nsp}`)
|
||||
// this._nsps.set(nsp, new Namespace(this, nsp))
|
||||
// }
|
||||
// return this._nsps.get(nsp)
|
||||
// }
|
||||
/**
|
||||
* Looks up a namespace.
|
||||
*
|
||||
* @param {String|RegExp|Function} name nsp name
|
||||
* @param {Function} [fn] optional, nsp `connection` ev handler
|
||||
* @public
|
||||
*/
|
||||
public of(
|
||||
name:
|
||||
| string
|
||||
| RegExp
|
||||
| ((
|
||||
name: string,
|
||||
query: object,
|
||||
fn: (err: Error, success: boolean) => void
|
||||
) => void),
|
||||
fn?: (socket: Socket) => void
|
||||
) {
|
||||
if (typeof name === "function" || name instanceof RegExp) {
|
||||
const parentNsp = new ParentNamespace(this)
|
||||
console.debug(`initializing parent namespace ${parentNsp.name}`)
|
||||
if (typeof name === "function") {
|
||||
this.parentNsps.set(name, parentNsp)
|
||||
} else {
|
||||
this.parentNsps.set(
|
||||
(nsp, conn, next) => next(null, (name as RegExp).test(nsp)),
|
||||
parentNsp
|
||||
)
|
||||
}
|
||||
if (fn) {
|
||||
// @ts-ignore
|
||||
parentNsp.on("connect", fn)
|
||||
}
|
||||
return parentNsp
|
||||
}
|
||||
return this.nsps[nsp]
|
||||
if (String(name)[0] !== "/") name = "/" + name
|
||||
let nsp = this._nsps.get(name)
|
||||
if (!nsp) {
|
||||
console.debug(`initializing namespace ${name}`)
|
||||
nsp = new Namespace(this, name)
|
||||
this._nsps.set(name, nsp)
|
||||
}
|
||||
if (fn) nsp.on("connect", fn)
|
||||
return nsp
|
||||
}
|
||||
close(fn?: () => void): void {
|
||||
for (let socket in this.sockets.sockets) {
|
||||
this.sockets.sockets[socket].onclose()
|
||||
this.clients.length
|
||||
for (const client of this.allClients.values()) {
|
||||
client._disconnect()
|
||||
}
|
||||
|
||||
// this.engine.close()
|
||||
this.websocketServer.close()
|
||||
|
||||
// if (this.httpServer) {
|
||||
// this.httpServer.close(fn)
|
||||
// } else {
|
||||
fn && fn()
|
||||
// }
|
||||
}
|
||||
on(event: "connection", listener: (socket: SocketIO.Socket) => void): SocketIO.Namespace
|
||||
on(event: "connect", listener: (socket: SocketIO.Socket) => void): SocketIO.Namespace
|
||||
on(event: string, listener: Function): SocketIO.Namespace
|
||||
on(event: any, listener: any): SocketIO.Namespace {
|
||||
on(event: "connection", listener: (socket: Socket) => void): Namespace
|
||||
on(event: "connect", listener: (socket: Socket) => void): Namespace
|
||||
on(event: string, listener: Function): Namespace
|
||||
on(event: any, listener: any): Namespace {
|
||||
return this.sockets.on(event, listener)
|
||||
}
|
||||
to(room: string): SocketIO.Namespace {
|
||||
to(room: string): Namespace {
|
||||
return this.sockets.to(room)
|
||||
}
|
||||
in(room: string): SocketIO.Namespace {
|
||||
in(room: string): Namespace {
|
||||
return this.sockets.in(room)
|
||||
}
|
||||
use(fn: (socket: SocketIO.Socket, fn: (err?: any) => void) => void): SocketIO.Namespace {
|
||||
use(fn: (socket: Socket, fn: (err?: any) => void) => void): Namespace {
|
||||
return this.sockets.use(fn)
|
||||
}
|
||||
emit(event: string, ...args: any[]): SocketIO.Namespace {
|
||||
emit(event: string, ...args: any[]): Namespace {
|
||||
// @ts-ignore
|
||||
return this.sockets.emit(event, ...args)
|
||||
}
|
||||
send(...args: any[]): SocketIO.Namespace {
|
||||
send(...args: any[]): Namespace {
|
||||
return this.sockets.send(...args)
|
||||
}
|
||||
write(...args: any[]): SocketIO.Namespace {
|
||||
write(...args: any[]): Namespace {
|
||||
return this.sockets.write(...args)
|
||||
}
|
||||
clients(...args: any[]): SocketIO.Namespace {
|
||||
clients(...args: any[]): Namespace {
|
||||
return this.sockets.clients(args[0])
|
||||
}
|
||||
compress(...args: any[]): SocketIO.Namespace {
|
||||
compress(...args: any[]): Namespace {
|
||||
return this.sockets.compress(args[0])
|
||||
}
|
||||
// ===============================
|
||||
checkNamespace(name, query, fn) {
|
||||
fn(false)
|
||||
};
|
||||
|
||||
private initServerConfig() {
|
||||
this.allClients = new Map()
|
||||
this._nsps = new Map()
|
||||
this.connectTimeout(this.options.connectTimeout || 45000)
|
||||
this._parser = this.options.parser || new Parser()
|
||||
this.adapter(this.options.adapter || Adapter)
|
||||
}
|
||||
private selectServerImpl(instance: any) {
|
||||
let WebSocketServerImpl = undefined
|
||||
if (instance.class.name.startsWith('io.netty.channel')) {
|
||||
WebSocketServerImpl = require("../netty").NettyWebSocketServer
|
||||
} else {
|
||||
WebSocketServerImpl = require("../tomcat").TomcatWebSocketServer
|
||||
}
|
||||
this.websocketServer = new WebSocketServerImpl(instance, this.options)
|
||||
}
|
||||
private initServer() {
|
||||
this.websocketServer.on(ServerEvent.connect, (socket: SocketIO.EngineSocket) => {
|
||||
let client = new Client(this, socket)
|
||||
this.onconnection(client)
|
||||
this.websocketServer.on(ServerEvent.connect, (transport: Transport) => {
|
||||
this.onconnection(transport)
|
||||
})
|
||||
this.websocketServer.on(ServerEvent.message, (socket: SocketIO.EngineSocket, text) => {
|
||||
this.processPacket(this.parser.decode(text), this.allClients[socket.id])
|
||||
})
|
||||
this.websocketServer.on(ServerEvent.disconnect, (socket: SocketIO.EngineSocket, reason) => {
|
||||
this.allClients[socket.id].onclose(reason)
|
||||
delete this.allClients[socket.id]
|
||||
})
|
||||
this.websocketServer.on(ServerEvent.error, (socket: SocketIO.EngineSocket, cause) => {
|
||||
if (socket.listeners(ServerEvent.error).length) {
|
||||
socket.emit(ServerEvent.error, cause)
|
||||
this.websocketServer.on(ServerEvent.message, (transport: Transport, text) => {
|
||||
if (this.allClients.has(transport.id)) {
|
||||
let client = this.allClients.get(transport.id)
|
||||
client.onPacket(this._parser.decode(text))
|
||||
} else {
|
||||
console.error(`client ${socket.id} cause error: ${cause}`)
|
||||
console.error(`unknow transport ${transport.id} reciver message ${text}`)
|
||||
}
|
||||
})
|
||||
this.websocketServer.on(ServerEvent.disconnect, (transport: Transport, reason) => {
|
||||
if (this.allClients.has(transport.id)) {
|
||||
this.allClients.get(transport.id).onclose(reason)
|
||||
this.allClients.delete(transport.id)
|
||||
} else {
|
||||
console.error(`unknow transport ${transport?.id} disconnect cause ${reason}`)
|
||||
}
|
||||
})
|
||||
this.websocketServer.on(ServerEvent.error, (transport: Transport, cause) => {
|
||||
if (this.allClients.has(transport?.id)) {
|
||||
let client = this.allClients.get(transport?.id)
|
||||
if (client.listeners(ServerEvent.error).length) {
|
||||
client.emit(ServerEvent.error, cause)
|
||||
} else {
|
||||
console.error(`client ${client.id} cause error: ${cause}`)
|
||||
console.ex(cause)
|
||||
}
|
||||
} else {
|
||||
console.error(`unknow transport ${transport?.id} cause error: ${cause}`)
|
||||
console.ex(cause)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private processPacket(packet: Packet, client: Client) {
|
||||
switch (packet.type) {
|
||||
case PacketTypes.PING:
|
||||
client.packet({
|
||||
type: PacketTypes.PONG,
|
||||
data: packet.data
|
||||
})
|
||||
break
|
||||
case PacketTypes.UPGRADE:
|
||||
break
|
||||
case PacketTypes.MESSAGE:
|
||||
this.processSubPacket(packet, client)
|
||||
break
|
||||
case PacketTypes.CLOSE:
|
||||
client.onclose()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private processSubPacket(packet: Packet, client: Client) {
|
||||
let namespace = this.nsps[packet.nsp]
|
||||
if (!namespace) {
|
||||
client.packet({
|
||||
type: PacketTypes.MESSAGE,
|
||||
sub_type: SubPacketTypes.ERROR,
|
||||
data: 'not support dynamic namespace: ' + packet.nsp
|
||||
})
|
||||
client.disconnect()
|
||||
return
|
||||
}
|
||||
namespace.process(packet, client)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Expose main namespace (/).
|
||||
*/
|
||||
|
||||
const emitterMethods = Object.keys(EventEmitter.prototype).filter(function (
|
||||
key
|
||||
) {
|
||||
return typeof EventEmitter.prototype[key] === "function"
|
||||
})
|
||||
|
||||
emitterMethods.forEach(function (fn) {
|
||||
Server.prototype[fn] = function () {
|
||||
return this.sockets[fn].apply(this.sockets, arguments)
|
||||
}
|
||||
})
|
||||
|
||||
export {
|
||||
Server,
|
||||
Socket,
|
||||
Client,
|
||||
Namespace,
|
||||
ServerOptions
|
||||
}
|
||||
|
||||
@@ -1,844 +0,0 @@
|
||||
export declare namespace SocketIO {
|
||||
interface Server {
|
||||
engine: { ws: any };
|
||||
|
||||
/**
|
||||
* A dictionary of all the namespaces currently on this Server
|
||||
*/
|
||||
nsps: { [namespace: string]: Namespace };
|
||||
|
||||
/**
|
||||
* The default '/' Namespace
|
||||
*/
|
||||
sockets: Namespace;
|
||||
|
||||
/**
|
||||
* Sets the 'json' flag when emitting an event
|
||||
*/
|
||||
json: Server;
|
||||
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event data may be lost if the clients are not ready to receive messages
|
||||
*/
|
||||
volatile: Server;
|
||||
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node
|
||||
*/
|
||||
local: Server;
|
||||
|
||||
/**
|
||||
* Server request verification function, that checks for allowed origins
|
||||
* @param req The http.IncomingMessage request
|
||||
* @param fn The callback to be called. It should take one parameter, err,
|
||||
* which will be null if there was no problem, and one parameter, success,
|
||||
* of type boolean
|
||||
*/
|
||||
checkRequest(req: any, fn: (err: any, success: boolean) => void): void;
|
||||
|
||||
/**
|
||||
* Gets whether we're serving the client.js file or not
|
||||
* @default true
|
||||
*/
|
||||
serveClient(): boolean;
|
||||
|
||||
/**
|
||||
* Sets whether we're serving the client.js file or not
|
||||
* @param v True if we want to serve the file, false otherwise
|
||||
* @default true
|
||||
* @return This Server
|
||||
*/
|
||||
serveClient(v: boolean): Server;
|
||||
|
||||
/**
|
||||
* Gets the client serving path
|
||||
* @default '/socket.io'
|
||||
*/
|
||||
path(): string;
|
||||
|
||||
/**
|
||||
* Sets the client serving path
|
||||
* @param v The path to serve the client file on
|
||||
* @default '/socket.io'
|
||||
* @return This Server
|
||||
*/
|
||||
path(v: string): Server;
|
||||
|
||||
/**
|
||||
* Gets the adapter that we're going to use for handling rooms
|
||||
* @default typeof Adapter
|
||||
*/
|
||||
adapter(): any;
|
||||
|
||||
/**
|
||||
* Sets the adapter (class) that we're going to use for handling rooms
|
||||
* @param v The class for the adapter to create
|
||||
* @default typeof Adapter
|
||||
* @return This Server
|
||||
*/
|
||||
adapter(v: any): Server;
|
||||
|
||||
/**
|
||||
* Gets the allowed origins for requests
|
||||
* @default "*:*"
|
||||
*/
|
||||
origins(): string | string[];
|
||||
|
||||
/**
|
||||
* Sets the allowed origins for requests
|
||||
* @param v The allowed origins, in host:port form
|
||||
* @default "*:*"
|
||||
* return This Server
|
||||
*/
|
||||
origins(v: string | string[]): Server;
|
||||
|
||||
/**
|
||||
* Provides a function taking two arguments origin:String
|
||||
* and callback(error, success), where success is a boolean
|
||||
* value indicating whether origin is allowed or not. If
|
||||
* success is set to false, error must be provided as a string
|
||||
* value that will be appended to the server response, e.g. “Origin not allowed”.
|
||||
* @param fn The function that will be called to check the origin
|
||||
* return This Server
|
||||
*/
|
||||
origins(fn: (origin: string, callback: (error: string | null, success: boolean) => void) => void): Server;
|
||||
|
||||
/**
|
||||
* Attaches socket.io to a server
|
||||
* @param srv The http.Server that we want to attach to
|
||||
* @param opts An optional parameters object
|
||||
* @return This Server
|
||||
*/
|
||||
attach(srv: any, opts?: ServerOptions): Server;
|
||||
|
||||
/**
|
||||
* Attaches socket.io to a port
|
||||
* @param port The port that we want to attach to
|
||||
* @param opts An optional parameters object
|
||||
* @return This Server
|
||||
*/
|
||||
attach(port: number, opts?: ServerOptions): Server;
|
||||
|
||||
/**
|
||||
* @see attach( srv, opts )
|
||||
*/
|
||||
listen(srv: any, opts?: ServerOptions): Server;
|
||||
|
||||
/**
|
||||
* @see attach( port, opts )
|
||||
*/
|
||||
listen(port: number, opts?: ServerOptions): Server;
|
||||
|
||||
/**
|
||||
* Binds socket.io to an engine.io instance
|
||||
* @param src The Engine.io (or compatible) server to bind to
|
||||
* @return This Server
|
||||
*/
|
||||
bind(srv: any): Server;
|
||||
|
||||
/**
|
||||
* Called with each incoming connection
|
||||
* @param socket The Engine.io Socket
|
||||
* @return This Server
|
||||
*/
|
||||
onconnection(socket: any): Server;
|
||||
|
||||
/**
|
||||
* Looks up/creates a Namespace
|
||||
* @param nsp The name of the NameSpace to look up/create. Should start
|
||||
* with a '/'
|
||||
* @return The Namespace
|
||||
*/
|
||||
of(nsp: string | RegExp | Function): Namespace;
|
||||
|
||||
/**
|
||||
* Closes the server connection
|
||||
*/
|
||||
close(fn?: () => void): void;
|
||||
|
||||
/**
|
||||
* The event fired when we get a new connection
|
||||
* @param event The event being fired: 'connection'
|
||||
* @param listener A listener that should take one parameter of type Socket
|
||||
* @return The default '/' Namespace
|
||||
*/
|
||||
on(event: 'connection', listener: (socket: Socket) => void): Namespace;
|
||||
|
||||
/**
|
||||
* @see on( 'connection', listener )
|
||||
*/
|
||||
on(event: 'connect', listener: (socket: Socket) => void): Namespace;
|
||||
|
||||
/**
|
||||
* Base 'on' method to add a listener for an event
|
||||
* @param event The event that we want to add a listener for
|
||||
* @param listener The callback to call when we get the event. The parameters
|
||||
* for the callback depend on the event
|
||||
* @return The default '/' Namespace
|
||||
*/
|
||||
on(event: string, listener: Function): Namespace;
|
||||
|
||||
/**
|
||||
* Targets a room when emitting to the default '/' Namespace
|
||||
* @param room The name of the room that we're targeting
|
||||
* @return The default '/' Namespace
|
||||
*/
|
||||
to(room: string): Namespace;
|
||||
|
||||
/**
|
||||
* @see to( room )
|
||||
*/
|
||||
in(room: string): Namespace;
|
||||
|
||||
/**
|
||||
* Registers a middleware function, which is a function that gets executed
|
||||
* for every incoming Socket, on the default '/' Namespace
|
||||
* @param fn The function to call when we get a new incoming socket. It should
|
||||
* take one parameter of type Socket, and one callback function to call to
|
||||
* execute the next middleware function. The callback can take one optional
|
||||
* parameter, err, if there was an error. Errors passed to middleware callbacks
|
||||
* are sent as special 'error' packets to clients
|
||||
* @return The default '/' Namespace
|
||||
*/
|
||||
use(fn: (socket: Socket, fn: (err?: any) => void) => void): Namespace;
|
||||
|
||||
/**
|
||||
* Emits an event to the default Namespace
|
||||
* @param event The event that we want to emit
|
||||
* @param args Any number of optional arguments to pass with the event. If the
|
||||
* last argument is a function, it will be called as an ack. The ack should
|
||||
* take whatever data was sent with the packet
|
||||
* @return The default '/' Namespace
|
||||
*/
|
||||
emit(event: string, ...args: any[]): Namespace;
|
||||
|
||||
/**
|
||||
* Sends a 'message' event
|
||||
* @see emit( event, ...args )
|
||||
* @return The default '/' Namespace
|
||||
*/
|
||||
send(...args: any[]): Namespace;
|
||||
|
||||
/**
|
||||
* @see send( ...args )
|
||||
*/
|
||||
write(...args: any[]): Namespace;
|
||||
|
||||
/**
|
||||
* Gets a list of clients
|
||||
* @return The default '/' Namespace
|
||||
*/
|
||||
clients(...args: any[]): Namespace;
|
||||
|
||||
/**
|
||||
* Sets the compress flag
|
||||
* @return The default '/' Namespace
|
||||
*/
|
||||
compress(...args: any[]): Namespace;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options to pass to our server when creating it
|
||||
*/
|
||||
interface ServerOptions {
|
||||
|
||||
/**
|
||||
* The path to server the client file to
|
||||
* @default '/socket.io'
|
||||
*/
|
||||
path?: string;
|
||||
|
||||
/**
|
||||
* Should we serve the client file?
|
||||
* @default true
|
||||
*/
|
||||
serveClient?: boolean;
|
||||
|
||||
/**
|
||||
* The adapter to use for handling rooms. NOTE: this should be a class,
|
||||
* not an object
|
||||
* @default typeof Adapter
|
||||
*/
|
||||
adapter?: Adapter;
|
||||
|
||||
/**
|
||||
* Accepted origins
|
||||
* @default '*:*'
|
||||
*/
|
||||
origins?: string | string[];
|
||||
|
||||
/**
|
||||
* How many milliseconds without a pong packed to consider the connection closed (engine.io)
|
||||
* @default 60000
|
||||
*/
|
||||
pingTimeout?: number;
|
||||
|
||||
/**
|
||||
* How many milliseconds before sending a new ping packet (keep-alive) (engine.io)
|
||||
* @default 25000
|
||||
*/
|
||||
pingInterval?: number;
|
||||
|
||||
/**
|
||||
* How many bytes or characters a message can be when polling, before closing the session
|
||||
* (to avoid Dos) (engine.io)
|
||||
* @default 10E7
|
||||
*/
|
||||
maxHttpBufferSize?: number;
|
||||
|
||||
/**
|
||||
* A function that receives a given handshake or upgrade request as its first parameter,
|
||||
* and can decide whether to continue or not. The second argument is a function that needs
|
||||
* to be called with the decided information: fn( err, success ), where success is a boolean
|
||||
* value where false means that the request is rejected, and err is an error code (engine.io)
|
||||
* @default null
|
||||
*/
|
||||
allowRequest?: (request: any, callback: (err: number, success: boolean) => void) => void;
|
||||
|
||||
/**
|
||||
* Transports to allow connections to (engine.io)
|
||||
* @default ['polling','websocket']
|
||||
*/
|
||||
transports?: string[];
|
||||
|
||||
/**
|
||||
* Whether to allow transport upgrades (engine.io)
|
||||
* @default true
|
||||
*/
|
||||
allowUpgrades?: boolean;
|
||||
|
||||
/**
|
||||
* parameters of the WebSocket permessage-deflate extension (see ws module).
|
||||
* Set to false to disable (engine.io)
|
||||
* @default true
|
||||
*/
|
||||
perMessageDeflate?: Object | boolean;
|
||||
|
||||
/**
|
||||
* Parameters of the http compression for the polling transports (see zlib).
|
||||
* Set to false to disable, or set an object with parameter "threshold:number"
|
||||
* to only compress data if the byte size is above this value (1024) (engine.io)
|
||||
* @default true|1024
|
||||
*/
|
||||
httpCompression?: Object | boolean;
|
||||
|
||||
/**
|
||||
* Name of the HTTP cookie that contains the client sid to send as part of
|
||||
* handshake response headers. Set to false to not send one (engine.io)
|
||||
* @default "io"
|
||||
*/
|
||||
cookie?: string | boolean;
|
||||
|
||||
/**
|
||||
* Whether to let engine.io handle the OPTIONS requests.
|
||||
* You can also pass a custom function to handle the requests
|
||||
* @default true
|
||||
*/
|
||||
handlePreflightRequest?: ((req: any, res: any) => void) | boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Namespace, sandboxed environments for sockets, each connection
|
||||
* to a Namespace requires a new Socket
|
||||
*/
|
||||
interface Namespace extends NodeJS.EventEmitter {
|
||||
|
||||
/**
|
||||
* The name of the NameSpace
|
||||
*/
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* The controller Server for this Namespace
|
||||
*/
|
||||
server: Server;
|
||||
|
||||
/**
|
||||
* A dictionary of all the Sockets connected to this Namespace, where
|
||||
* the Socket ID is the key
|
||||
*/
|
||||
sockets: { [id: string]: Socket };
|
||||
|
||||
/**
|
||||
* A dictionary of all the Sockets connected to this Namespace, where
|
||||
* the Socket ID is the key
|
||||
*/
|
||||
connected: { [id: string]: Socket };
|
||||
|
||||
/**
|
||||
* The Adapter that we're using to handle dealing with rooms etc
|
||||
*/
|
||||
adapter: Adapter;
|
||||
|
||||
/**
|
||||
* Sets the 'json' flag when emitting an event
|
||||
*/
|
||||
json: Namespace;
|
||||
|
||||
/**
|
||||
* Registers a middleware function, which is a function that gets executed
|
||||
* for every incoming Socket
|
||||
* @param fn The function to call when we get a new incoming socket. It should
|
||||
* take one parameter of type Socket, and one callback function to call to
|
||||
* execute the next middleware function. The callback can take one optional
|
||||
* parameter, err, if there was an error. Errors passed to middleware callbacks
|
||||
* are sent as special 'error' packets to clients
|
||||
* @return This Namespace
|
||||
*/
|
||||
use(fn: (socket: Socket, fn: (err?: any) => void) => void): Namespace;
|
||||
|
||||
/**
|
||||
* Targets a room when emitting
|
||||
* @param room The name of the room that we're targeting
|
||||
* @return This Namespace
|
||||
*/
|
||||
to(room: string): Namespace;
|
||||
|
||||
/**
|
||||
* @see to( room )
|
||||
*/
|
||||
in(room: string): Namespace;
|
||||
|
||||
/**
|
||||
* Sends a 'message' event
|
||||
* @see emit( event, ...args )
|
||||
* @return This Namespace
|
||||
*/
|
||||
send(...args: any[]): Namespace;
|
||||
|
||||
/**
|
||||
* @see send( ...args )
|
||||
*/
|
||||
write(...args: any[]): Namespace;
|
||||
|
||||
/**
|
||||
* The event fired when we get a new connection
|
||||
* @param event The event being fired: 'connection'
|
||||
* @param listener A listener that should take one parameter of type Socket
|
||||
* @return This Namespace
|
||||
*/
|
||||
on(event: 'connection', listener: (socket: Socket) => void): this;
|
||||
|
||||
/**
|
||||
* @see on( 'connection', listener )
|
||||
*/
|
||||
on(event: 'connect', listener: (socket: Socket) => void): this;
|
||||
|
||||
/**
|
||||
* Base 'on' method to add a listener for an event
|
||||
* @param event The event that we want to add a listener for
|
||||
* @param listener The callback to call when we get the event. The parameters
|
||||
* for the callback depend on the event
|
||||
* @ This Namespace
|
||||
*/
|
||||
on(event: string, listener: Function): this;
|
||||
|
||||
/**
|
||||
* Gets a list of clients.
|
||||
* @return This Namespace
|
||||
*/
|
||||
clients(fn: Function): Namespace;
|
||||
|
||||
/**
|
||||
* Sets the compress flag.
|
||||
* @param compress If `true`, compresses the sending data
|
||||
* @return This Namespace
|
||||
*/
|
||||
compress(compress: boolean): Namespace;
|
||||
}
|
||||
|
||||
interface Packet extends Array<any> {
|
||||
/**
|
||||
* Event name
|
||||
*/
|
||||
[0]: string;
|
||||
/**
|
||||
* Packet data
|
||||
*/
|
||||
[1]: any;
|
||||
/**
|
||||
* Ack function
|
||||
*/
|
||||
[2]: (...args: any[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The socket, which handles our connection for a namespace. NOTE: while
|
||||
* we technically extend NodeJS.EventEmitter, we're not putting it here
|
||||
* as we have a problem with the emit() event (as it's overridden with a
|
||||
* different return)
|
||||
*/
|
||||
interface Socket extends NodeJS.EventEmitter {
|
||||
|
||||
/**
|
||||
* The namespace that this socket is for
|
||||
*/
|
||||
nsp: Namespace;
|
||||
|
||||
/**
|
||||
* The Server that our namespace is in
|
||||
*/
|
||||
server: Server;
|
||||
|
||||
/**
|
||||
* The Adapter that we use to handle our rooms
|
||||
*/
|
||||
adapter: Adapter;
|
||||
|
||||
/**
|
||||
* The unique ID for this Socket. Regenerated at every connection. This is
|
||||
* also the name of the room that the Socket automatically joins on connection
|
||||
*/
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* The http.IncomingMessage request sent with the connection. Useful
|
||||
* for recovering headers etc
|
||||
*/
|
||||
request: any;
|
||||
|
||||
/**
|
||||
* The Client associated with this Socket
|
||||
*/
|
||||
client: Client;
|
||||
|
||||
/**
|
||||
* The underlying Engine.io Socket instance
|
||||
*/
|
||||
conn: EngineSocket;
|
||||
|
||||
/**
|
||||
* The list of rooms that this Socket is currently in, where
|
||||
* the ID the the room ID
|
||||
*/
|
||||
rooms: { [id: string]: string };
|
||||
|
||||
/**
|
||||
* Is the Socket currently connected?
|
||||
*/
|
||||
connected: boolean;
|
||||
|
||||
/**
|
||||
* Is the Socket currently disconnected?
|
||||
*/
|
||||
disconnected: boolean;
|
||||
|
||||
/**
|
||||
* The object used when negociating the handshake
|
||||
*/
|
||||
handshake: Handshake;
|
||||
/**
|
||||
* Sets the 'json' flag when emitting an event
|
||||
*/
|
||||
json: Socket;
|
||||
|
||||
/**
|
||||
* Sets the 'volatile' flag when emitting an event. Volatile messages are
|
||||
* messages that can be dropped because of network issues and the like. Use
|
||||
* for high-volume/real-time messages where you don't need to receive *all*
|
||||
* of them
|
||||
*/
|
||||
volatile: Socket;
|
||||
|
||||
/**
|
||||
* Sets the 'broadcast' flag when emitting an event. Broadcasting an event
|
||||
* will send it to all the other sockets in the namespace except for yourself
|
||||
*/
|
||||
broadcast: Socket;
|
||||
|
||||
/**
|
||||
* Targets a room when broadcasting
|
||||
* @param room The name of the room that we're targeting
|
||||
* @return This Socket
|
||||
*/
|
||||
to(room: string): Socket;
|
||||
|
||||
/**
|
||||
* @see to( room )
|
||||
*/
|
||||
in(room: string): Socket;
|
||||
|
||||
/**
|
||||
* Registers a middleware, which is a function that gets executed for every incoming Packet and receives as parameter the packet and a function to optionally defer execution to the next registered middleware.
|
||||
*
|
||||
* Errors passed to middleware callbacks are sent as special error packets to clients.
|
||||
*/
|
||||
use(fn: (packet: Packet, next: (err?: any) => void) => void): Socket;
|
||||
|
||||
/**
|
||||
* Sends a 'message' event
|
||||
* @see emit( event, ...args )
|
||||
*/
|
||||
send(...args: any[]): Socket;
|
||||
|
||||
/**
|
||||
* @see send( ...args )
|
||||
*/
|
||||
write(...args: any[]): Socket;
|
||||
|
||||
/**
|
||||
* Joins a room. You can join multiple rooms, and by default, on connection,
|
||||
* you join a room with the same name as your ID
|
||||
* @param name The name of the room that we want to join
|
||||
* @param fn An optional callback to call when we've joined the room. It should
|
||||
* take an optional parameter, err, of a possible error
|
||||
* @return This Socket
|
||||
*/
|
||||
join(name: string | string[], fn?: (err?: any) => void): Socket;
|
||||
|
||||
/**
|
||||
* Leaves a room
|
||||
* @param name The name of the room to leave
|
||||
* @param fn An optional callback to call when we've left the room. It should
|
||||
* take on optional parameter, err, of a possible error
|
||||
*/
|
||||
leave(name: string, fn?: Function): Socket;
|
||||
|
||||
/**
|
||||
* Leaves all the rooms that we've joined
|
||||
*/
|
||||
leaveAll(): void;
|
||||
|
||||
/**
|
||||
* Disconnects this Socket
|
||||
* @param close If true, also closes the underlying connection
|
||||
* @return This Socket
|
||||
*/
|
||||
disconnect(close?: boolean): Socket;
|
||||
|
||||
/**
|
||||
* Returns all the callbacks for a particular event
|
||||
* @param event The event that we're looking for the callbacks of
|
||||
* @return An array of callback Functions, or an empty array if we don't have any
|
||||
*/
|
||||
listeners(event: string): Function[];
|
||||
|
||||
/**
|
||||
* Sets the compress flag
|
||||
* @param compress If `true`, compresses the sending data
|
||||
* @return This Socket
|
||||
*/
|
||||
compress(compress: boolean): Socket;
|
||||
|
||||
/**
|
||||
* Emits the error
|
||||
* @param err Error message=
|
||||
*/
|
||||
error(err: any): void;
|
||||
}
|
||||
|
||||
interface Handshake {
|
||||
/**
|
||||
* The headers passed along with the request. e.g. 'host',
|
||||
* 'connection', 'accept', 'referer', 'cookie'
|
||||
*/
|
||||
headers: any;
|
||||
|
||||
/**
|
||||
* The current time, as a string
|
||||
*/
|
||||
time: string;
|
||||
|
||||
/**
|
||||
* The remote address of the connection request
|
||||
*/
|
||||
address: string;
|
||||
|
||||
/**
|
||||
* Is this a cross-domain request?
|
||||
*/
|
||||
xdomain: boolean;
|
||||
|
||||
/**
|
||||
* Is this a secure request?
|
||||
*/
|
||||
secure: boolean;
|
||||
|
||||
/**
|
||||
* The timestamp for when this was issued
|
||||
*/
|
||||
issued: number;
|
||||
|
||||
/**
|
||||
* The request url
|
||||
*/
|
||||
url: string;
|
||||
|
||||
/**
|
||||
* Any query string parameters in the request url
|
||||
*/
|
||||
query: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* The interface describing a room
|
||||
*/
|
||||
interface Room {
|
||||
sockets: { [id: string]: boolean };
|
||||
length: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The interface describing a dictionary of rooms
|
||||
* Where room is the name of the room
|
||||
*/
|
||||
|
||||
interface Rooms {
|
||||
[room: string]: Room;
|
||||
}
|
||||
|
||||
/**
|
||||
* The interface used when dealing with rooms etc
|
||||
*/
|
||||
interface Adapter extends NodeJS.EventEmitter {
|
||||
|
||||
/**
|
||||
* The namespace that this adapter is for
|
||||
*/
|
||||
nsp: Namespace;
|
||||
|
||||
/**
|
||||
* A dictionary of all the rooms that we have in this namespace
|
||||
*/
|
||||
rooms: Rooms;
|
||||
|
||||
/**
|
||||
* A dictionary of all the socket ids that we're dealing with, and all
|
||||
* the rooms that the socket is currently in
|
||||
*/
|
||||
sids: { [id: string]: { [room: string]: boolean } };
|
||||
|
||||
/**
|
||||
* Adds a socket to a room. If the room doesn't exist, it's created
|
||||
* @param id The ID of the socket to add
|
||||
* @param room The name of the room to add the socket to
|
||||
* @param callback An optional callback to call when the socket has been
|
||||
* added. It should take an optional parameter, error, if there was a problem
|
||||
*/
|
||||
add(id: string, room: string, callback?: (err?: any) => void): void;
|
||||
|
||||
/**
|
||||
* Removes a socket from a room. If there are no more sockets in the room,
|
||||
* the room is deleted
|
||||
* @param id The ID of the socket that we're removing
|
||||
* @param room The name of the room to remove the socket from
|
||||
* @param callback An optional callback to call when the socket has been
|
||||
* removed. It should take on optional parameter, error, if there was a problem
|
||||
*/
|
||||
del(id: string, room: string, callback?: (err?: any) => void): void;
|
||||
|
||||
/**
|
||||
* Adds a socket to a list of room.
|
||||
*
|
||||
* @param {String} socket id
|
||||
* @param {String} rooms
|
||||
* @param {Function} callback
|
||||
* @api public
|
||||
*/
|
||||
addAll(id: string, rooms: string | any[], fn: { (err?: any): void; bind?: any; });
|
||||
|
||||
/**
|
||||
* Removes a socket from all the rooms that it's joined
|
||||
* @param id The ID of the socket that we're removing
|
||||
*/
|
||||
delAll(id: string): void;
|
||||
|
||||
/**
|
||||
* Broadcasts a packet
|
||||
* @param packet The packet to broadcast
|
||||
* @param opts Any options to send along:
|
||||
* - rooms: An optional list of rooms to broadcast to. If empty, the packet is broadcast to all sockets
|
||||
* - except: A list of Socket IDs to exclude
|
||||
* - flags: Any flags that we want to send along ('json', 'volatile', 'broadcast')
|
||||
*/
|
||||
broadcast(packet: any, opts: { rooms?: string[]; except?: string[]; flags?: { [flag: string]: boolean } }): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The client behind each socket (can have multiple sockets)
|
||||
*/
|
||||
interface Client {
|
||||
/**
|
||||
* The Server that this client belongs to
|
||||
*/
|
||||
server: Server;
|
||||
|
||||
/**
|
||||
* The underlying Engine.io Socket instance
|
||||
*/
|
||||
conn: EngineSocket;
|
||||
|
||||
/**
|
||||
* The ID for this client. Regenerated at every connection
|
||||
*/
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* The http.IncomingMessage request sent with the connection. Useful
|
||||
* for recovering headers etc
|
||||
*/
|
||||
request: any;
|
||||
|
||||
/**
|
||||
* The dictionary of sockets currently connect via this client (i.e. to different
|
||||
* namespaces) where the Socket ID is the key
|
||||
*/
|
||||
sockets: { [id: string]: Socket };
|
||||
|
||||
/**
|
||||
* A dictionary of all the namespaces for this client, with the Socket that
|
||||
* deals with that namespace
|
||||
*/
|
||||
nsps: { [nsp: string]: Socket };
|
||||
}
|
||||
|
||||
/**
|
||||
* A reference to the underlying engine.io Socket connection.
|
||||
*/
|
||||
interface EngineSocket extends NodeJS.EventEmitter {
|
||||
/**
|
||||
* The ID for this socket - matches Client.id
|
||||
*/
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* The Engine.io Server for this socket
|
||||
*/
|
||||
server: any;
|
||||
|
||||
/**
|
||||
* The ready state for the client. Either 'opening', 'open', 'closing', or 'closed'
|
||||
*/
|
||||
readyState: string;
|
||||
|
||||
/**
|
||||
* The remote IP for this connection
|
||||
*/
|
||||
remoteAddress: string;
|
||||
|
||||
/**
|
||||
* whether the transport has been upgraded
|
||||
*/
|
||||
upgraded: boolean;
|
||||
|
||||
/**
|
||||
* (http.IncomingMessage): request that originated the Socket
|
||||
*/
|
||||
request: any;
|
||||
|
||||
/**
|
||||
* (Transport): transport reference
|
||||
*/
|
||||
transport: any;
|
||||
|
||||
/**
|
||||
* send
|
||||
*/
|
||||
send(text: string);
|
||||
|
||||
/**
|
||||
* close
|
||||
*/
|
||||
close();
|
||||
}
|
||||
}
|
||||
@@ -1,138 +1,242 @@
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
import { Client } from './client'
|
||||
import { SocketIO } from './interfaces';
|
||||
import { ServerEvent } from './constants';
|
||||
import { Socket } from './socket';
|
||||
import { Adapter } from './adapter';
|
||||
import { ServerEvent } from './constants'
|
||||
import { RESERVED_EVENTS, Socket } from './socket'
|
||||
import { Adapter, Room, SocketId } from './adapter'
|
||||
import { Server } from './index'
|
||||
import { Packet } from './packet';
|
||||
import { PacketTypes, SubPacketTypes } from './types';
|
||||
import { Packet } from './packet'
|
||||
import { PacketTypes, SubPacketTypes } from './types'
|
||||
|
||||
export class Namespace extends EventEmitter implements SocketIO.Namespace {
|
||||
name: string;
|
||||
server: Server;
|
||||
sockets: { [id: string]: Socket; };
|
||||
connected: { [id: string]: Socket; };
|
||||
adapter: SocketIO.Adapter;
|
||||
json: SocketIO.Namespace;
|
||||
export interface ExtendedError extends Error {
|
||||
data?: any
|
||||
}
|
||||
|
||||
fns: any[];
|
||||
ids: number;
|
||||
rooms: string[];
|
||||
flags: { [key: string]: boolean };
|
||||
export class Namespace extends EventEmitter {
|
||||
public readonly name: string
|
||||
public readonly sockets: Map<SocketId, Socket>
|
||||
|
||||
private events = ['connect', 'connection', 'newListener']
|
||||
public adapter: Adapter
|
||||
|
||||
constructor(name: string, server: Server) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.server = server;
|
||||
this.sockets = {};
|
||||
this.connected = {};
|
||||
this.fns = [];
|
||||
this.ids = 0;
|
||||
this.rooms = [];
|
||||
this.flags = {};
|
||||
this.adapter = new Adapter(this);
|
||||
/** @private */
|
||||
readonly server: Server
|
||||
json: Namespace
|
||||
|
||||
/** @private */
|
||||
_fns: Array<
|
||||
(socket: Socket, next: (err: ExtendedError) => void) => void
|
||||
> = [];
|
||||
|
||||
/** @private */
|
||||
_rooms: Set<Room>
|
||||
|
||||
/** @private */
|
||||
_flags: any = {}
|
||||
|
||||
/** @private */
|
||||
_ids: number = 0
|
||||
|
||||
constructor(server: Server, name: string) {
|
||||
super()
|
||||
this.server = server
|
||||
this.name = name + ''
|
||||
this._initAdapter()
|
||||
// =======================
|
||||
this.sockets = new Map()
|
||||
this._rooms = new Set()
|
||||
}
|
||||
initAdapter() {
|
||||
_initAdapter() {
|
||||
// @ts-ignore
|
||||
this.adapter = new (this.server.adapter())()
|
||||
this.adapter = new (this.server.adapter())(this)
|
||||
}
|
||||
add(client: Client, query?: any, callback?: () => void) {
|
||||
// client.conn.request.url();
|
||||
let socket = new Socket(this, client, {});
|
||||
this.sockets[client.id] = socket;
|
||||
client.nsps[this.name] = socket;
|
||||
this.onconnection(socket);
|
||||
return socket;
|
||||
/**
|
||||
* Sets up namespace middleware.
|
||||
*
|
||||
* @return {Namespace} self
|
||||
* @public
|
||||
*/
|
||||
public use(
|
||||
fn: (socket: Socket, next: (err?: ExtendedError) => void) => void
|
||||
): Namespace {
|
||||
this._fns.push(fn)
|
||||
return this
|
||||
}
|
||||
del(client: Client) {
|
||||
let socket = this.sockets[client.id];
|
||||
socket.disconnect();
|
||||
delete this.sockets[client.id];
|
||||
/**
|
||||
* Executes the middleware for an incoming client.
|
||||
*
|
||||
* @param {Socket} socket - the socket that will get added
|
||||
* @param {Function} fn - last fn call in the middleware
|
||||
* @private
|
||||
*/
|
||||
private run(socket: Socket, fn: (err: ExtendedError) => void) {
|
||||
const fns = this._fns.slice(0)
|
||||
if (!fns.length) return fn(null)
|
||||
|
||||
function run(i) {
|
||||
fns[i](socket, function (err) {
|
||||
// upon error, short-circuit
|
||||
if (err) return fn(err)
|
||||
|
||||
// if no middleware left, summon callback
|
||||
if (!fns[i + 1]) return fn(null)
|
||||
|
||||
// go on to next
|
||||
run(i + 1)
|
||||
})
|
||||
}
|
||||
|
||||
run(0)
|
||||
}
|
||||
use(fn: (socket: SocketIO.Socket, fn: (err?: any) => void) => void): SocketIO.Namespace {
|
||||
throw new Error("Method not implemented.");
|
||||
to(name: string): Namespace {
|
||||
this._rooms.add(name)
|
||||
return this
|
||||
}
|
||||
to(room: string): SocketIO.Namespace {
|
||||
if (!~this.rooms.indexOf(room)) this.rooms.push(room);
|
||||
return this;
|
||||
in(name: string): Namespace {
|
||||
return this.to(name)
|
||||
}
|
||||
in(room: string): SocketIO.Namespace {
|
||||
return this.to(room);
|
||||
_add(client: Client, query?: any, fn?: (socket: Socket) => void) {
|
||||
const socket = new Socket(this, client, query || {})
|
||||
console.debug(`client ${client.id} adding socket ${socket.id} to nsp ${this.name}`)
|
||||
this.run(socket, err => {
|
||||
process.nextTick(() => {
|
||||
if ("open" == client.conn.readyState) {
|
||||
if (err)
|
||||
return socket._error({
|
||||
message: err.message,
|
||||
data: err.data
|
||||
})
|
||||
|
||||
// track socket
|
||||
this.sockets.set(socket.id, socket)
|
||||
|
||||
// it's paramount that the internal `onconnect` logic
|
||||
// fires before user-set events to prevent state order
|
||||
// violations (such as a disconnection before the connection
|
||||
// logic is complete)
|
||||
socket._onconnect()
|
||||
// !!! at java multi thread need direct callback socket
|
||||
if (fn) fn(socket)
|
||||
|
||||
// fire user-set events
|
||||
super.emit(ServerEvent.connect, socket)
|
||||
super.emit(ServerEvent.connection, socket)
|
||||
} else {
|
||||
console.debug(`next called after client ${client.id} was closed - ignoring socket`)
|
||||
}
|
||||
})
|
||||
})
|
||||
return socket
|
||||
}
|
||||
send(...args: any[]): SocketIO.Namespace {
|
||||
super.emit('message', ...args)
|
||||
return this;
|
||||
}
|
||||
write(...args: any[]): SocketIO.Namespace {
|
||||
return this.send(...args);
|
||||
/**
|
||||
* Removes a client. Called by each `Socket`.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_remove(socket: Socket): void {
|
||||
if (this.sockets.has(socket.id)) {
|
||||
console.debug(`namespace ${this.name} remove socket ${socket.id}`)
|
||||
this.sockets.delete(socket.id)
|
||||
} else {
|
||||
console.debug(`namespace ${this.name} ignoring remove for ${socket.id}`)
|
||||
}
|
||||
}
|
||||
emit(event: string, ...args: any[]): boolean {
|
||||
if (~this.events.indexOf(event)) {
|
||||
super.emit(event, ...args);
|
||||
// @ts-ignore
|
||||
return this;
|
||||
if (RESERVED_EVENTS.has(event)) {
|
||||
throw new Error(`"${event}" is a reserved event name`)
|
||||
}
|
||||
// set up packet object
|
||||
var packet = {
|
||||
type: PacketTypes.MESSAGE,
|
||||
sub_type: (this.flags.binary !== undefined ? this.flags.binary : this.hasBin(args)) ? SubPacketTypes.BINARY_EVENT : SubPacketTypes.EVENT,
|
||||
sub_type: (this._flags.binary !== undefined ? this._flags.binary : this.hasBin(args)) ? SubPacketTypes.BINARY_EVENT : SubPacketTypes.EVENT,
|
||||
name: event,
|
||||
data: args
|
||||
}
|
||||
|
||||
if ('function' == typeof args[args.length - 1]) {
|
||||
throw new Error('Callbacks are not supported when broadcasting');
|
||||
throw new Error('Callbacks are not supported when broadcasting')
|
||||
}
|
||||
|
||||
var rooms = this.rooms.slice(0);
|
||||
var flags = Object.assign({}, this.flags);
|
||||
var rooms = new Set(this._rooms)
|
||||
var flags = Object.assign({}, this._flags)
|
||||
|
||||
// reset flags
|
||||
this.rooms = [];
|
||||
this.flags = {};
|
||||
this._rooms.clear()
|
||||
this._flags = {}
|
||||
|
||||
this.adapter.broadcast(packet, {
|
||||
rooms: rooms,
|
||||
rooms: new Set(rooms),
|
||||
flags: flags
|
||||
});
|
||||
})
|
||||
// @ts-ignore
|
||||
return this;
|
||||
return this
|
||||
}
|
||||
send(...args: any[]): Namespace {
|
||||
this.emit('message', ...args)
|
||||
return this
|
||||
}
|
||||
write(...args: any[]): Namespace {
|
||||
return this.send(...args)
|
||||
}
|
||||
/**
|
||||
* Gets a list of clients.
|
||||
*
|
||||
* @return {Namespace} self
|
||||
* @public
|
||||
*/
|
||||
public allSockets(): Promise<Set<SocketId>> {
|
||||
if (!this.adapter) {
|
||||
throw new Error("No adapter for this namespace, are you trying to get the list of clients of a dynamic namespace?")
|
||||
}
|
||||
const rooms = new Set(this._rooms)
|
||||
this._rooms.clear()
|
||||
return this.adapter.sockets(rooms)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the compress flag.
|
||||
*
|
||||
* @param {Boolean} compress - if `true`, compresses the sending data
|
||||
* @return {Namespace} self
|
||||
* @public
|
||||
*/
|
||||
public compress(compress: boolean): Namespace {
|
||||
this._flags.compress = compress
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
|
||||
* receive messages (because of network slowness or other issues, or because they’re connected through long polling
|
||||
* and is in the middle of a request-response cycle).
|
||||
*
|
||||
* @return {Namespace} self
|
||||
* @public
|
||||
*/
|
||||
public get volatile(): Namespace {
|
||||
this._flags.volatile = true
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
|
||||
*
|
||||
* @return {Namespace} self
|
||||
* @public
|
||||
*/
|
||||
public get local(): Namespace {
|
||||
this._flags.local = true
|
||||
return this
|
||||
}
|
||||
|
||||
hasBin(args: any[]) {
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
clients(fn: Function): SocketIO.Namespace {
|
||||
clients(fn: (sockets: Socket[]) => Namespace): Namespace {
|
||||
return fn(Object.values(this.sockets))
|
||||
}
|
||||
compress(compress: boolean): SocketIO.Namespace {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
process(packet: Packet, client: Client) {
|
||||
switch (packet.sub_type) {
|
||||
case SubPacketTypes.CONNECT:
|
||||
this.add(client);
|
||||
break;
|
||||
default:
|
||||
this.sockets[client.id].onpacket(packet);
|
||||
break;
|
||||
}
|
||||
}
|
||||
remove(socket: Socket) {
|
||||
if (this.sockets.hasOwnProperty(socket.id)) {
|
||||
delete this.sockets[socket.id];
|
||||
} else {
|
||||
// debug('ignoring remove for %s', socket.id);
|
||||
}
|
||||
}
|
||||
private onconnection(socket: any) {
|
||||
let client = socket as Socket;
|
||||
this.sockets[client.id] = client;
|
||||
client.onconnect()
|
||||
this.emit(ServerEvent.connect, socket);
|
||||
this.emit(ServerEvent.connection, socket);
|
||||
close() {
|
||||
this.removeAllListeners(ServerEvent.connect)
|
||||
this.removeAllListeners(ServerEvent.connection)
|
||||
Object.values(this.sockets).forEach(socket => socket.disconnect(false))
|
||||
}
|
||||
}
|
||||
|
||||
40
packages/websocket/src/socket-io/parent-namespace.ts
Normal file
40
packages/websocket/src/socket-io/parent-namespace.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Namespace } from "./namespace"
|
||||
|
||||
export class ParentNamespace extends Namespace {
|
||||
private static count: number = 0;
|
||||
private children: Set<Namespace> = new Set();
|
||||
|
||||
constructor(server) {
|
||||
super(server, "/_" + ParentNamespace.count++)
|
||||
}
|
||||
|
||||
_initAdapter() { }
|
||||
|
||||
public emit(...args: any[]): boolean {
|
||||
this.children.forEach(nsp => {
|
||||
nsp._rooms = this._rooms
|
||||
nsp._flags = this._flags
|
||||
nsp.emit.apply(nsp, args as any)
|
||||
})
|
||||
this._rooms.clear()
|
||||
this._flags = {}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
createChild(name) {
|
||||
const namespace = new Namespace(this.server, name)
|
||||
namespace._fns = this._fns.slice(0)
|
||||
this.listeners("connect").forEach(listener =>
|
||||
// @ts-ignore
|
||||
namespace.on("connect", listener)
|
||||
)
|
||||
this.listeners("connection").forEach(listener =>
|
||||
// @ts-ignore
|
||||
namespace.on("connection", listener)
|
||||
)
|
||||
this.children.add(namespace)
|
||||
this.server._nsps.set(name, namespace)
|
||||
return namespace
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,31 @@
|
||||
import { Packet } from "./packet";
|
||||
import { PacketTypes, SubPacketTypes } from "./types";
|
||||
import { EventEmitter } from 'events'
|
||||
import { Packet } from "./packet"
|
||||
import { PacketTypes, SubPacketTypes } from "./types"
|
||||
|
||||
export class Parser {
|
||||
export class Parser extends EventEmitter {
|
||||
encode(packet: Packet): string {
|
||||
let origin = JSON.stringify(packet)
|
||||
// first is type
|
||||
let str = '' + packet.type;
|
||||
let str = '' + packet.type
|
||||
if (packet.type == PacketTypes.PONG) {
|
||||
if (packet.data) { str += packet.data };
|
||||
return str;
|
||||
return str
|
||||
}
|
||||
if (packet.sub_type != undefined) {
|
||||
str += packet.sub_type;
|
||||
str += packet.sub_type
|
||||
}
|
||||
// attachments if we have them
|
||||
if ([SubPacketTypes.BINARY_EVENT, SubPacketTypes.BINARY_ACK].includes(packet.sub_type)) {
|
||||
str += packet.attachments + '-';
|
||||
str += packet.attachments + '-'
|
||||
}
|
||||
// if we have a namespace other than `/`
|
||||
// we append it followed by a comma `,`
|
||||
if (packet.nsp && '/' !== packet.nsp) {
|
||||
str += packet.nsp + ',';
|
||||
str += packet.nsp + ','
|
||||
}
|
||||
// immediately followed by the id
|
||||
if (null != packet.id) {
|
||||
str += packet.id;
|
||||
str += packet.id
|
||||
}
|
||||
if (packet.sub_type == SubPacketTypes.EVENT) {
|
||||
if (packet.name == undefined) { throw new Error(`SubPacketTypes.EVENT name can't be empty!`) }
|
||||
@@ -32,25 +33,25 @@ export class Parser {
|
||||
}
|
||||
// json data
|
||||
if (null != packet.data) {
|
||||
let payload = this.tryStringify(packet.data);
|
||||
let payload = this.tryStringify(packet.data)
|
||||
if (payload !== false) {
|
||||
str += payload;
|
||||
str += payload
|
||||
} else {
|
||||
return '4"encode error"'
|
||||
}
|
||||
}
|
||||
console.trace(`encoded ${origin} as ${str}`);
|
||||
return str;
|
||||
console.trace(`encoded ${origin} as ${str}`)
|
||||
return str
|
||||
}
|
||||
tryStringify(str: any) {
|
||||
try {
|
||||
return JSON.stringify(str);
|
||||
return JSON.stringify(str)
|
||||
} catch (e) {
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
}
|
||||
decode(str: string): Packet {
|
||||
let i = 0;
|
||||
let i = 0
|
||||
// ignore parse binary
|
||||
// if ((frame.getByte(0) == 'b' && frame.getByte(1) == '4')
|
||||
// || frame.getByte(0) == 4 || frame.getByte(0) == 1) {
|
||||
@@ -59,69 +60,69 @@ export class Parser {
|
||||
// look up type
|
||||
let p: Packet = {
|
||||
type: Number(str.charAt(i))
|
||||
};
|
||||
}
|
||||
if (null == PacketTypes[p.type]) {
|
||||
return this.error('unknown packet type ' + p.type);
|
||||
return this.error('unknown packet type ' + p.type)
|
||||
}
|
||||
// if str empty return
|
||||
if (str.length == i + 1) {
|
||||
return p;
|
||||
return p
|
||||
}
|
||||
// if is ping packet read data and return
|
||||
if (PacketTypes.PING == p.type) {
|
||||
p.data = str.substr(++i);
|
||||
return p;
|
||||
p.data = str.substr(++i)
|
||||
return p
|
||||
}
|
||||
// look up sub type
|
||||
p.sub_type = Number(str.charAt(++i));
|
||||
p.sub_type = Number(str.charAt(++i))
|
||||
if (null == PacketTypes[p.sub_type]) {
|
||||
return this.error('unknown sub packet type ' + p.type);
|
||||
return this.error('unknown sub packet type ' + p.type)
|
||||
}
|
||||
// look up attachments if type binary
|
||||
if ([SubPacketTypes.BINARY_ACK, SubPacketTypes.BINARY_EVENT].includes(p.sub_type)) {
|
||||
let buf = '';
|
||||
let buf = ''
|
||||
while (str.charAt(++i) !== '-') {
|
||||
buf += str.charAt(i);
|
||||
if (i == str.length) break;
|
||||
buf += str.charAt(i)
|
||||
if (i == str.length) break
|
||||
}
|
||||
if (buf != `${Number(buf)}` || str.charAt(i) !== '-') {
|
||||
return this.error('Illegal attachments');
|
||||
return this.error('Illegal attachments')
|
||||
}
|
||||
p.attachments = Number(buf);
|
||||
p.attachments = Number(buf)
|
||||
}
|
||||
|
||||
// look up namespace (if any)
|
||||
if ('/' === str.charAt(i + 1)) {
|
||||
p.nsp = '';
|
||||
p.nsp = ''
|
||||
while (++i) {
|
||||
let c = str.charAt(i);
|
||||
if (',' === c) break;
|
||||
p.nsp += c;
|
||||
if (i === str.length) break;
|
||||
let c = str.charAt(i)
|
||||
if (',' === c) break
|
||||
p.nsp += c
|
||||
if (i === str.length) break
|
||||
}
|
||||
} else {
|
||||
p.nsp = '/';
|
||||
p.nsp = '/'
|
||||
}
|
||||
|
||||
// handle namespace query
|
||||
if (p.nsp.indexOf('?') !== -1) {
|
||||
p.nsp = p.nsp.split('?')[0];
|
||||
p.nsp = p.nsp.split('?')[0]
|
||||
}
|
||||
|
||||
// look up id
|
||||
let next = str.charAt(i + 1);
|
||||
let next = str.charAt(i + 1)
|
||||
if ('' !== next && !isNaN(Number(next))) {
|
||||
let id = ''
|
||||
while (++i) {
|
||||
let c = str.charAt(i);
|
||||
let c = str.charAt(i)
|
||||
if (null == c || isNaN(Number(c))) {
|
||||
--i;
|
||||
break;
|
||||
--i
|
||||
break
|
||||
}
|
||||
id += str.charAt(i);
|
||||
if (i === str.length) break;
|
||||
id += str.charAt(i)
|
||||
if (i === str.length) break
|
||||
}
|
||||
p.id = Number(id);
|
||||
p.id = Number(id)
|
||||
}
|
||||
|
||||
// ignore binary packet
|
||||
@@ -131,25 +132,25 @@ export class Parser {
|
||||
|
||||
// look up json data
|
||||
if (str.charAt(++i)) {
|
||||
let payload = this.tryParse(str.substr(i));
|
||||
let isPayloadValid = payload !== false && (p.sub_type == SubPacketTypes.ERROR || Array.isArray(payload));
|
||||
let payload = this.tryParse(str.substr(i))
|
||||
let isPayloadValid = payload !== false && (p.sub_type == SubPacketTypes.ERROR || Array.isArray(payload))
|
||||
if (isPayloadValid) {
|
||||
p.name = payload[0];
|
||||
p.data = payload.slice(1);
|
||||
p.name = payload[0]
|
||||
p.data = payload.slice(1)
|
||||
} else {
|
||||
return this.error('invalid payload ' + str.substr(i));
|
||||
return this.error('invalid payload ' + str.substr(i))
|
||||
}
|
||||
}
|
||||
|
||||
console.trace(`decoded ${str} as ${JSON.stringify(p)}`);
|
||||
return p;
|
||||
console.trace(`decoded ${str} as ${JSON.stringify(p)}`)
|
||||
return p
|
||||
}
|
||||
|
||||
tryParse(str: string) {
|
||||
try {
|
||||
return JSON.parse(str);
|
||||
return JSON.parse(str)
|
||||
} catch (e) {
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,6 +159,6 @@ export class Parser {
|
||||
type: PacketTypes.MESSAGE,
|
||||
sub_type: SubPacketTypes.ERROR,
|
||||
data: 'parser error: ' + error
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,166 +1,110 @@
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
import { SocketIO } from "./interfaces"
|
||||
import { Packet } from './packet'
|
||||
import { PacketTypes, SubPacketTypes } from './types'
|
||||
import { Client } from './client'
|
||||
import { Namespace } from './namespace'
|
||||
import * as querystring from 'querystring'
|
||||
import { ServerEvent } from './constants'
|
||||
import { Adapter, BroadcastFlags, Room, SocketId } from './adapter'
|
||||
import { Server } from 'index'
|
||||
|
||||
export class Socket extends EventEmitter implements SocketIO.Socket {
|
||||
export const RESERVED_EVENTS = new Set([
|
||||
"connect",
|
||||
"connect_error",
|
||||
"disconnect",
|
||||
"disconnecting",
|
||||
// EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
|
||||
"newListener",
|
||||
"removeListener"
|
||||
])
|
||||
|
||||
/**
|
||||
* The handshake details
|
||||
*/
|
||||
export interface Handshake {
|
||||
/**
|
||||
* The headers sent as part of the handshake
|
||||
*/
|
||||
headers: object
|
||||
|
||||
/**
|
||||
* The date of creation (as string)
|
||||
*/
|
||||
time: string
|
||||
|
||||
/**
|
||||
* The ip of the client
|
||||
*/
|
||||
address: string
|
||||
|
||||
/**
|
||||
* Whether the connection is cross-domain
|
||||
*/
|
||||
xdomain: boolean
|
||||
|
||||
/**
|
||||
* Whether the connection is secure
|
||||
*/
|
||||
secure: boolean
|
||||
|
||||
/**
|
||||
* The date of creation (as unix timestamp)
|
||||
*/
|
||||
issued: number
|
||||
|
||||
/**
|
||||
* The request URL string
|
||||
*/
|
||||
url: string
|
||||
|
||||
/**
|
||||
* The query object
|
||||
*/
|
||||
query: any
|
||||
|
||||
/**
|
||||
* The auth object
|
||||
*/
|
||||
auth: any
|
||||
}
|
||||
export class Socket extends EventEmitter {
|
||||
nsp: Namespace
|
||||
server: SocketIO.Server
|
||||
adapter: SocketIO.Adapter
|
||||
id: string
|
||||
request: any
|
||||
|
||||
public readonly id: SocketId
|
||||
public readonly handshake: Handshake
|
||||
|
||||
public connected: boolean
|
||||
public disconnected: boolean
|
||||
|
||||
private readonly server: Server
|
||||
private readonly adapter: Adapter
|
||||
|
||||
client: Client
|
||||
conn: SocketIO.EngineSocket
|
||||
rooms: { [id: string]: string }
|
||||
acks: { [id: string]: Function }
|
||||
connected: boolean
|
||||
disconnected: boolean
|
||||
handshake: SocketIO.Handshake
|
||||
private acks: Map<number, () => void>
|
||||
|
||||
fns: any[]
|
||||
flags: { [key: string]: boolean }
|
||||
_rooms: string[]
|
||||
private flags: BroadcastFlags = {};
|
||||
private _rooms: Set<Room> = new Set();
|
||||
private _anyListeners: Array<(...args: any[]) => void>
|
||||
|
||||
private events = [
|
||||
'error',
|
||||
'connect',
|
||||
'disconnect',
|
||||
'disconnecting',
|
||||
'newListener',
|
||||
'removeListener'
|
||||
]
|
||||
|
||||
constructor(nsp: Namespace, client: Client, query = {}) {
|
||||
constructor(nsp: Namespace, client: Client, auth = {}) {
|
||||
super()
|
||||
this.nsp = nsp
|
||||
this.server = nsp.server
|
||||
this.adapter = this.nsp.adapter
|
||||
this.id = nsp.name !== '/' ? nsp.name + '#' + client.id : client.id
|
||||
this.client = client
|
||||
this.request = client.request
|
||||
this.conn = client.conn
|
||||
this.rooms = {}
|
||||
this.acks = {}
|
||||
this.acks = new Map()
|
||||
this.connected = true
|
||||
this.disconnected = false
|
||||
this.handshake = this.buildHandshake(query)
|
||||
this.handshake = this.buildHandshake(auth)
|
||||
|
||||
this.fns = []
|
||||
this.flags = {}
|
||||
this._rooms = []
|
||||
}
|
||||
|
||||
get json() {
|
||||
this.flags.json = true
|
||||
return this
|
||||
}
|
||||
|
||||
get volatile() {
|
||||
this.flags.volatile = true
|
||||
return this
|
||||
}
|
||||
get broadcast() {
|
||||
this.flags.broadcast = true
|
||||
return this
|
||||
}
|
||||
get local() {
|
||||
this.flags.local = true
|
||||
return this
|
||||
}
|
||||
|
||||
to(room: string): SocketIO.Socket {
|
||||
if (!~this._rooms.indexOf(room)) this._rooms.push(room)
|
||||
return this
|
||||
}
|
||||
in(room: string): SocketIO.Socket {
|
||||
return this.to(room)
|
||||
}
|
||||
use(fn: (packet: SocketIO.Packet, next: (err?: any) => void) => void): SocketIO.Socket {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
send(...args: any[]): SocketIO.Socket {
|
||||
this.emit("message", ...args)
|
||||
return this
|
||||
}
|
||||
write(...args: any[]): SocketIO.Socket {
|
||||
return this.send(...args)
|
||||
}
|
||||
join(rooms: string | string[], fn?: (err?: any) => void): SocketIO.Socket {
|
||||
if (!Array.isArray(rooms)) {
|
||||
rooms = [rooms]
|
||||
}
|
||||
rooms = rooms.filter((room) => {
|
||||
return !this.rooms.hasOwnProperty(room)
|
||||
})
|
||||
if (!rooms.length) {
|
||||
fn && fn(null)
|
||||
return this
|
||||
}
|
||||
this.adapter.addAll(this.id, rooms, (err) => {
|
||||
if (err) return fn && fn(err);
|
||||
// debug('joined room %s', rooms);
|
||||
(rooms as Array<string>).forEach((room) => {
|
||||
this.rooms[room] = room
|
||||
})
|
||||
fn && fn(null)
|
||||
})
|
||||
return this
|
||||
}
|
||||
leave(name: string, fn?: Function): SocketIO.Socket {
|
||||
delete this.rooms[name]
|
||||
fn && fn(null)
|
||||
return this
|
||||
}
|
||||
leaveAll(): void {
|
||||
this.adapter.delAll(this.id)
|
||||
this.rooms = {}
|
||||
}
|
||||
disconnect(close?: boolean): SocketIO.Socket {
|
||||
if (!this.connected) return this
|
||||
if (close) {
|
||||
this.client.disconnect()
|
||||
} else {
|
||||
this.packet({ type: PacketTypes.MESSAGE, sub_type: SubPacketTypes.DISCONNECT })
|
||||
this.onclose('server namespace disconnect')
|
||||
}
|
||||
return this
|
||||
}
|
||||
compress(compress: boolean): SocketIO.Socket {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
error(err: any): void {
|
||||
this.packet({ type: PacketTypes.MESSAGE, sub_type: SubPacketTypes.ERROR, data: err })
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
buildHandshake(query): SocketIO.Handshake {
|
||||
let requestUri = this.request.uri()
|
||||
let headers = {}
|
||||
let nativeHeaders = this.request.headers()
|
||||
nativeHeaders.forEach(function (header) {
|
||||
headers[header.getKey()] = header.getValue()
|
||||
})
|
||||
return {
|
||||
headers: headers,
|
||||
time: (new Date) + '',
|
||||
address: this.conn.remoteAddress + '',
|
||||
xdomain: !!headers['origin'],
|
||||
secure: false,
|
||||
issued: +(new Date),
|
||||
url: requestUri,
|
||||
query: Object.assign(query, querystring.parse(requestUri.indexOf('?') != -1 ? requestUri.split('?')[1] : ''))
|
||||
}
|
||||
this._rooms = new Set()
|
||||
}
|
||||
emit(event: string, ...args: any[]): boolean {
|
||||
if (~this.events.indexOf(event)) {
|
||||
super.emit(event, ...args)
|
||||
// @ts-ignore
|
||||
return this
|
||||
}
|
||||
|
||||
let packet: Packet = {
|
||||
type: PacketTypes.MESSAGE,
|
||||
sub_type: (this.flags.binary !== undefined ? this.flags.binary : this.hasBin(args)) ? SubPacketTypes.BINARY_EVENT : SubPacketTypes.EVENT,
|
||||
@@ -169,25 +113,26 @@ export class Socket extends EventEmitter implements SocketIO.Socket {
|
||||
}
|
||||
|
||||
// access last argument to see if it's an ACK callback
|
||||
if (typeof args[args.length - 1] === 'function') {
|
||||
if (this._rooms.length || this.flags.broadcast) {
|
||||
throw new Error('Callbacks are not supported when broadcasting')
|
||||
if (typeof args[args.length - 1] === "function") {
|
||||
if (this._rooms.size || this.flags.broadcast) {
|
||||
throw new Error("Callbacks are not supported when broadcasting")
|
||||
}
|
||||
// debug('emitting packet with ack id %d', this.nsp.ids);
|
||||
this.acks[this.nsp.ids] = args.pop()
|
||||
packet.id = this.nsp.ids++
|
||||
|
||||
// console.debug("emitting packet with ack id %d", this.nsp._ids)
|
||||
this.acks.set(this.nsp._ids, args.pop())
|
||||
packet.id = this.nsp._ids++
|
||||
}
|
||||
|
||||
let rooms = this._rooms.slice(0)
|
||||
let flags = Object.assign({}, this.flags)
|
||||
const rooms = new Set(this._rooms)
|
||||
const flags = Object.assign({}, this.flags)
|
||||
|
||||
// reset flags
|
||||
this._rooms = []
|
||||
this._rooms.clear()
|
||||
this.flags = {}
|
||||
|
||||
if (rooms.length || flags.broadcast) {
|
||||
if (rooms.size || flags.broadcast) {
|
||||
this.adapter.broadcast(packet, {
|
||||
except: [this.id],
|
||||
except: new Set([this.id]),
|
||||
rooms: rooms,
|
||||
flags: flags
|
||||
})
|
||||
@@ -195,47 +140,69 @@ export class Socket extends EventEmitter implements SocketIO.Socket {
|
||||
// dispatch packet
|
||||
this.packet(packet, flags)
|
||||
}
|
||||
// @ts-ignore
|
||||
return true
|
||||
}
|
||||
to(name: Room): Socket {
|
||||
this._rooms.add(name)
|
||||
return this
|
||||
}
|
||||
packet(packet: Packet, opts: any = { preEncoded: false }) {
|
||||
if (!opts.preEncoded) {
|
||||
packet.nsp = this.nsp.name
|
||||
opts.compress = false !== opts.compress
|
||||
}
|
||||
try {
|
||||
this.client.packet(packet, opts)
|
||||
} catch (error) {
|
||||
this.onerror(error)
|
||||
}
|
||||
in(room: string): Socket {
|
||||
return this.to(room)
|
||||
}
|
||||
onconnect() {
|
||||
this.nsp.connected[this.id] = this
|
||||
this.client.sockets[this.id] = this
|
||||
use(fn: (packet: Packet, next: (err?: any) => void) => void): Socket {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
send(...args: any[]): Socket {
|
||||
this.emit("message", ...args)
|
||||
return this
|
||||
}
|
||||
write(...args: any[]): Socket {
|
||||
return this.send(...args)
|
||||
}
|
||||
public join(rooms: Room | Array<Room>): Promise<void> | void {
|
||||
console.debug(`join room ${rooms}`)
|
||||
|
||||
return this.adapter.addAll(
|
||||
this.id,
|
||||
new Set(Array.isArray(rooms) ? rooms : [rooms])
|
||||
)
|
||||
}
|
||||
/**
|
||||
* Leaves a room.
|
||||
*
|
||||
* @param {String} room
|
||||
* @return a Promise or nothing, depending on the adapter
|
||||
* @public
|
||||
*/
|
||||
public leave(room: string): Promise<void> | void {
|
||||
console.debug(`leave room ${room}`)
|
||||
|
||||
return this.adapter.del(this.id, room)
|
||||
}
|
||||
|
||||
/**
|
||||
* Leave all rooms.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private leaveAll(): void {
|
||||
this.adapter.delAll(this.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by `Namespace` upon successful
|
||||
* middleware execution (ie: authorization).
|
||||
* Socket is added to namespace array before
|
||||
* call to join, so adapters can access it.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_onconnect(): void {
|
||||
console.debug(`socket ${this.id} connected - writing packet`)
|
||||
this.join(this.id)
|
||||
// let skip = this.nsp.name === '/' && this.nsp.fns.length === 0;
|
||||
// if (skip) {
|
||||
// debug('packet already sent in initial handshake');
|
||||
// } else {
|
||||
this.packet({
|
||||
type: PacketTypes.MESSAGE,
|
||||
sub_type: SubPacketTypes.CONNECT
|
||||
})
|
||||
// }
|
||||
this.packet({ type: PacketTypes.MESSAGE, sub_type: SubPacketTypes.CONNECT, data: { sid: this.id } })
|
||||
}
|
||||
onclose(reason?: string) {
|
||||
if (!this.connected) return this
|
||||
// debug('closing socket - reason %s', reason);
|
||||
this.emit('disconnecting', reason)
|
||||
this.leaveAll()
|
||||
this.nsp.remove(this)
|
||||
this.client.remove(this)
|
||||
this.connected = false
|
||||
this.disconnected = true
|
||||
delete this.nsp.connected[this.id]
|
||||
this.emit('disconnect', reason)
|
||||
}
|
||||
onpacket(packet: Packet) {
|
||||
_onpacket(packet: Packet) {
|
||||
switch (packet.sub_type) {
|
||||
// 2
|
||||
case SubPacketTypes.EVENT:
|
||||
@@ -259,23 +226,12 @@ export class Socket extends EventEmitter implements SocketIO.Socket {
|
||||
break
|
||||
// 4
|
||||
case SubPacketTypes.ERROR:
|
||||
this.onerror(new Error(packet.data))
|
||||
this._onerror(new Error(packet.data))
|
||||
}
|
||||
}
|
||||
onerror(err: Error) {
|
||||
if (this.listeners('error').length) {
|
||||
this.emit('error', err)
|
||||
} else {
|
||||
console.error('Missing error handler on `socket`.')
|
||||
console.error(err.stack)
|
||||
}
|
||||
}
|
||||
ondisconnect() {
|
||||
this.onclose('client namespace disconnect')
|
||||
}
|
||||
onevent(packet: Packet) {
|
||||
if (null != packet.id) {
|
||||
// debug('attaching ack callback to event');
|
||||
console.trace(`attaching ack ${packet.id} callback to client ${this.id} event`)
|
||||
this.dispatch(packet, this.ack(packet.id))
|
||||
} else {
|
||||
this.dispatch(packet)
|
||||
@@ -295,17 +251,238 @@ export class Socket extends EventEmitter implements SocketIO.Socket {
|
||||
}
|
||||
}
|
||||
onack(packet: Packet) {
|
||||
let ack = this.acks[packet.id]
|
||||
let ack = this.acks.get(packet.id)
|
||||
if ('function' == typeof ack) {
|
||||
// debug('calling ack %s with %j', packet.id, packet.data);
|
||||
console.trace(`calling ack ${packet.id} on socket ${this.id} with ${packet.data}`)
|
||||
ack.apply(this, packet.data)
|
||||
delete this.acks[packet.id]
|
||||
this.acks.delete(packet.id)
|
||||
} else {
|
||||
// debug('bad ack %s', packet.id);
|
||||
console.trace(`bad ack ${packet.id} on socket ${this.id}`)
|
||||
}
|
||||
}
|
||||
dispatch(packet: Packet, ack?: Function) {
|
||||
if (ack) { this.acks[packet.id] = ack }
|
||||
/**
|
||||
* Called upon client disconnect packet.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondisconnect(): void {
|
||||
console.debug(`socket ${this.id} got disconnect packet`)
|
||||
this._onclose("client namespace disconnect")
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a client error.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_onerror(err): void {
|
||||
if (this.listeners("error").length) {
|
||||
super.emit("error", err)
|
||||
} else {
|
||||
console.error(`Missing error handler on 'socket(${this.id})'.`)
|
||||
console.error(err.stack)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called upon closing. Called by `Client`.
|
||||
*
|
||||
* @param {String} reason
|
||||
* @throw {Error} optional error object
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_onclose(reason: string) {
|
||||
if (!this.connected) return this
|
||||
console.debug(`closing socket ${this.id} - reason: ${reason} connected: ${this.connected}`)
|
||||
super.emit(ServerEvent.disconnecting, reason)
|
||||
this.leaveAll()
|
||||
this.nsp._remove(this)
|
||||
this.client._remove(this)
|
||||
this.connected = false
|
||||
this.disconnected = true
|
||||
super.emit(ServerEvent.disconnect, reason)
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces an `error` packet.
|
||||
*
|
||||
* @param {Object} err - error object
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_error(err) {
|
||||
this.packet({ type: PacketTypes.MESSAGE, sub_type: SubPacketTypes.ERROR, data: err })
|
||||
}
|
||||
disconnect(close?: boolean): Socket {
|
||||
if (!this.connected) return this
|
||||
if (close) {
|
||||
this.client._disconnect()
|
||||
} else {
|
||||
this.packet({ type: PacketTypes.MESSAGE, sub_type: SubPacketTypes.DISCONNECT })
|
||||
this._onclose('server namespace disconnect')
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
compress(compress: boolean): Socket {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
|
||||
* receive messages (because of network slowness or other issues, or because they’re connected through long polling
|
||||
* and is in the middle of a request-response cycle).
|
||||
*
|
||||
* @return {Socket} self
|
||||
* @public
|
||||
*/
|
||||
public get volatile(): Socket {
|
||||
this.flags.volatile = true
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the
|
||||
* sender.
|
||||
*
|
||||
* @return {Socket} self
|
||||
* @public
|
||||
*/
|
||||
public get broadcast(): Socket {
|
||||
this.flags.broadcast = true
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
|
||||
*
|
||||
* @return {Socket} self
|
||||
* @public
|
||||
*/
|
||||
public get local(): Socket {
|
||||
this.flags.local = true
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* A reference to the request that originated the underlying Engine.IO Socket.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
public get request(): any {
|
||||
return this.client.request
|
||||
}
|
||||
|
||||
/**
|
||||
* A reference to the underlying Client transport connection (Engine.IO Socket object).
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
public get conn() {
|
||||
return this.client.conn
|
||||
}
|
||||
|
||||
/**
|
||||
* @public
|
||||
*/
|
||||
public get rooms(): Set<Room> {
|
||||
return this.adapter.socketRooms(this.id) || new Set()
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* @param listener
|
||||
* @public
|
||||
*/
|
||||
public onAny(listener: (...args: any[]) => void): Socket {
|
||||
this._anyListeners = this._anyListeners || []
|
||||
this._anyListeners.push(listener)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* @param listener
|
||||
* @public
|
||||
*/
|
||||
public prependAny(listener: (...args: any[]) => void): Socket {
|
||||
this._anyListeners = this._anyListeners || []
|
||||
this._anyListeners.unshift(listener)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @param listener
|
||||
* @public
|
||||
*/
|
||||
public offAny(listener?: (...args: any[]) => void): Socket {
|
||||
if (!this._anyListeners) {
|
||||
return this
|
||||
}
|
||||
if (listener) {
|
||||
const listeners = this._anyListeners
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
if (listener === listeners[i]) {
|
||||
listeners.splice(i, 1)
|
||||
return this
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this._anyListeners = []
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
public listenersAny() {
|
||||
return this._anyListeners || []
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
buildHandshake(auth): Handshake {
|
||||
let requestUri = this.request.uri()
|
||||
let headers = {}
|
||||
let nativeHeaders = this.request.headers()
|
||||
nativeHeaders.forEach(function (header) {
|
||||
headers[header.getKey()] = header.getValue()
|
||||
})
|
||||
return {
|
||||
headers: headers,
|
||||
time: new Date() + '',
|
||||
address: this.conn.remoteAddress + '',
|
||||
xdomain: !!headers['origin'],
|
||||
secure: false,
|
||||
issued: +new Date(),
|
||||
url: requestUri,
|
||||
query: querystring.parse(requestUri.indexOf('?') != -1 ? requestUri.split('?')[1] : ''),
|
||||
auth
|
||||
}
|
||||
}
|
||||
packet(packet: Packet, opts: any = { preEncoded: false }) {
|
||||
if (!opts.preEncoded) {
|
||||
packet.nsp = this.nsp.name
|
||||
opts.compress = false !== opts.compress
|
||||
}
|
||||
try {
|
||||
this.client._packet(packet, opts)
|
||||
} catch (error) {
|
||||
this._onerror(error)
|
||||
}
|
||||
}
|
||||
dispatch(packet: Packet, ack?: () => void) {
|
||||
if (ack) { this.acks.set(packet.id, ack) }
|
||||
super.emit(packet.name, ...packet.data, ack)
|
||||
}
|
||||
private hasBin(obj: any) {
|
||||
|
||||
@@ -1,45 +1,22 @@
|
||||
import { EventEmitter } from 'events'
|
||||
import { SocketIO } from '../socket-io/interfaces'
|
||||
import { Transport } from '../transport'
|
||||
|
||||
export class TomcatClient extends EventEmitter implements SocketIO.EngineSocket {
|
||||
private _id: string
|
||||
export class TomcatClient extends Transport {
|
||||
private session: javax.websocket.Session
|
||||
|
||||
server: any
|
||||
readyState: string
|
||||
remoteAddress: string
|
||||
upgraded: boolean
|
||||
request: any
|
||||
transport: any
|
||||
|
||||
constructor(server: any, session: javax.websocket.Session) {
|
||||
super()
|
||||
this.server = server
|
||||
this.readyState = 'open'
|
||||
super(server)
|
||||
this.remoteAddress = session + ''
|
||||
this.upgraded = true
|
||||
this.request = {
|
||||
uri: () => `${session.getRequestURI()}`,
|
||||
headers: () => []
|
||||
}
|
||||
this.transport = null
|
||||
|
||||
this._id = session.getId() + ''
|
||||
this.session = session
|
||||
this._id = session.getId()
|
||||
}
|
||||
|
||||
get id() {
|
||||
return this._id
|
||||
doSend(text: string) {
|
||||
Java.synchronized(() => this.session.getBasicRemote().sendText(text), this.session)()
|
||||
}
|
||||
send(text: string) {
|
||||
if (this.readyState == 'open') {
|
||||
Java.synchronized(() => this.session.getBasicRemote().sendText(text), this.session)()
|
||||
}
|
||||
}
|
||||
close() {
|
||||
if (this.readyState == 'open') {
|
||||
this.readyState = 'close'
|
||||
this.session.close()
|
||||
}
|
||||
doClose() {
|
||||
this.session.close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { EventEmitter } from 'events'
|
||||
|
||||
import { ServerOptions } from '../socket-io'
|
||||
import { ServerEvent } from '../socket-io/constants'
|
||||
import { SocketIO } from '../socket-io/interfaces'
|
||||
import { ProxyBeanName } from './constants'
|
||||
import { TomcatClient } from './client'
|
||||
|
||||
@@ -15,28 +14,45 @@ type TomcatWebSocketSession = javax.websocket.Session
|
||||
class TomcatWebSocketServer extends EventEmitter {
|
||||
private beanFactory: any
|
||||
private executor: any
|
||||
private allClients: { [key: string]: SocketIO.EngineSocket }
|
||||
private clients: Map<string, any>
|
||||
|
||||
constructor(beanFactory: any, options: ServerOptions) {
|
||||
super()
|
||||
this.allClients = {}
|
||||
this.clients = new Map()
|
||||
this.beanFactory = beanFactory
|
||||
this.initThreadPool()
|
||||
try { this.beanFactory.destroySingleton(ProxyBeanName) } catch (error) { }
|
||||
let NashornWebSocketServerProxy = Java.extend(WebSocketServerProxy, {
|
||||
onOpen: (session: TomcatWebSocketSession) => {
|
||||
let cid = `${session?.getId()}`
|
||||
let tomcatClient = new TomcatClient(this, session)
|
||||
this.allClients[session.getId()] = tomcatClient
|
||||
this.clients.set(cid, tomcatClient)
|
||||
this.emit(ServerEvent.connect, tomcatClient)
|
||||
},
|
||||
onMessage: (session: TomcatWebSocketSession, message: string) => {
|
||||
this.executor.execute(() => this.emit(ServerEvent.message, this.allClients[session.getId()], message))
|
||||
let cid = `${session?.getId()}`
|
||||
if (this.clients.has(cid)) {
|
||||
this.executor.execute(() => this.emit(ServerEvent.message, this.clients.get(cid), message))
|
||||
} else {
|
||||
console.error(`unknow client ${session} reciver message ${message}`)
|
||||
}
|
||||
},
|
||||
onClose: (session: TomcatWebSocketSession, reason: any) => {
|
||||
this.emit(ServerEvent.disconnect, this.allClients[session.getId()], reason)
|
||||
let cid = `${session?.getId()}`
|
||||
if (this.clients.has(cid)) {
|
||||
this.emit(ServerEvent.disconnect, this.clients.get(cid), reason)
|
||||
} else {
|
||||
console.error(`unknow client ${session} disconnect cause ${reason}`)
|
||||
}
|
||||
},
|
||||
onError: (session: TomcatWebSocketSession, error: Error) => {
|
||||
this.emit(ServerEvent.error, this.allClients[session.getId()], error)
|
||||
let cid = `${session?.getId()}`
|
||||
if (this.clients.has(cid)) {
|
||||
this.emit(ServerEvent.error, this.clients.get(cid), error)
|
||||
} else {
|
||||
console.error(`unknow client ${session} cause error ${error}`)
|
||||
console.ex(error)
|
||||
}
|
||||
},
|
||||
})
|
||||
this.beanFactory.registerSingleton(ProxyBeanName, new NashornWebSocketServerProxy())
|
||||
@@ -52,7 +68,7 @@ class TomcatWebSocketServer extends EventEmitter {
|
||||
this.executor.initialize()
|
||||
}
|
||||
close() {
|
||||
Object.values(this.allClients).forEach(client => client.close())
|
||||
this.clients.forEach(client => client.close())
|
||||
this.beanFactory.destroySingleton(ProxyBeanName)
|
||||
this.executor.shutdown()
|
||||
}
|
||||
35
packages/websocket/src/transport.ts
Normal file
35
packages/websocket/src/transport.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
export abstract class Transport extends EventEmitter {
|
||||
protected _id: string
|
||||
|
||||
server: any
|
||||
readyState: 'opening' | 'open' | 'closing' | 'closed'
|
||||
remoteAddress: string
|
||||
upgraded: boolean
|
||||
request: any
|
||||
|
||||
constructor(server: any) {
|
||||
super()
|
||||
this.server = server
|
||||
this.readyState = 'open'
|
||||
this.upgraded = true
|
||||
}
|
||||
get id() {
|
||||
return this._id
|
||||
}
|
||||
send(text: string) {
|
||||
if (this.readyState == 'open') {
|
||||
this.doSend(text)
|
||||
} else {
|
||||
console.debug(`send message ${text} to close client ${this._id}`)
|
||||
}
|
||||
}
|
||||
close() {
|
||||
if ("closed" === this.readyState || "closing" === this.readyState) { return }
|
||||
this.doClose()
|
||||
this.readyState = 'closed'
|
||||
}
|
||||
abstract doSend(text: string)
|
||||
abstract doClose()
|
||||
}
|
||||
Reference in New Issue
Block a user