Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
17af1fd49b | ||
| b5423cd26c | |||
| aca864500f | |||
| f86e1a8c94 | |||
| a76f9e8b50 | |||
| 6dcc56b0e5 | |||
| 6f8ea8290b | |||
| 1f574695a1 | |||
| 090c0b2668 | |||
| db8f2d9bc2 | |||
| e02f673c82 | |||
| 47c85f70eb | |||
| da9e2063ca |
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"useWorkspaces": true,
|
"useWorkspaces": true,
|
||||||
"npmClient": "yarn",
|
"npmClient": "yarn",
|
||||||
"packages": [
|
"packages": [
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/amqp",
|
"name": "@ccms/amqp",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript amqp package",
|
"description": "MiaoScript amqp package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,17 +19,17 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.10.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.10.1",
|
||||||
"@javatypes/amqp-client": "^0.0.3",
|
"@javatypes/amqp-client": "^0.0.3",
|
||||||
"@javatypes/spring-amqp": "^0.0.3",
|
"@javatypes/spring-amqp": "^0.0.3",
|
||||||
"@javatypes/spring-rabbit": "^0.0.3",
|
"@javatypes/spring-rabbit": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/api",
|
"name": "@ccms/api",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,16 +19,16 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8",
|
"@ccms/container": "^0.10.1",
|
||||||
"@ccms/ployfill": "^0.9.8",
|
"@ccms/ployfill": "^0.10.1",
|
||||||
"base64-js": "^1.3.1",
|
"base64-js": "^1.5.1",
|
||||||
"source-map-builder": "^0.0.7"
|
"source-map-builder": "^0.0.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/base64-js": "^1.3.0",
|
"@types/base64-js": "^1.3.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import i18n from '@ccms/i18n'
|
import i18n from '@ccms/i18n'
|
||||||
import { injectable } from "@ccms/container"
|
import { injectable } from "@ccms/container"
|
||||||
import { plugin } from './interfaces'
|
import { plugin } from './plugin'
|
||||||
|
|
||||||
export namespace command {
|
export namespace command {
|
||||||
@injectable()
|
@injectable()
|
||||||
|
|||||||
@@ -133,6 +133,7 @@ export class MiaoScriptConsole implements Console {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
stack(ex: Error, color: boolean = true): string[] {
|
stack(ex: Error, color: boolean = true): string[] {
|
||||||
|
if (!ex) return []
|
||||||
let stack = ex.getStackTrace()
|
let stack = ex.getStackTrace()
|
||||||
let cache = [(color ? '§c' : '') + ex]
|
let cache = [(color ? '§c' : '') + ex]
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
|
|||||||
@@ -1,4 +1,14 @@
|
|||||||
export namespace constants {
|
export namespace constants {
|
||||||
|
export namespace ServiceIdentifier {
|
||||||
|
/**
|
||||||
|
* Runtime Server NettyPipeline
|
||||||
|
*/
|
||||||
|
export const NettyPipeline = Symbol("NettyPipeline")
|
||||||
|
/**
|
||||||
|
* Runtime Server RootLogger
|
||||||
|
*/
|
||||||
|
export const RootLogger = Symbol("RootLogger")
|
||||||
|
}
|
||||||
export namespace Reflect {
|
export namespace Reflect {
|
||||||
export const Method = {
|
export const Method = {
|
||||||
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
|
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
import "@ccms/nashorn"
|
import "@ccms/nashorn"
|
||||||
|
|
||||||
|
export * from './web'
|
||||||
|
export * from './amqp'
|
||||||
export * from './chat'
|
export * from './chat'
|
||||||
export * from './task'
|
export * from './task'
|
||||||
export * from './event'
|
export * from './event'
|
||||||
export * from './proxy'
|
export * from './proxy'
|
||||||
|
export * from './plugin'
|
||||||
|
export * from './server'
|
||||||
export * from './console'
|
export * from './console'
|
||||||
export * from './channel'
|
export * from './channel'
|
||||||
export * from './command'
|
export * from './command'
|
||||||
|
export * from './database'
|
||||||
export * from './constants'
|
export * from './constants'
|
||||||
export * from './interfaces'
|
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
export * from './web'
|
|
||||||
export * from './amqp'
|
|
||||||
export * from './plugin'
|
|
||||||
export * from './server'
|
|
||||||
export * from './database'
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
export interface NativePluginManager {
|
|
||||||
load(name: string): boolean;
|
|
||||||
unload(name: string): boolean;
|
|
||||||
reload(name: string): boolean;
|
|
||||||
delete(name: string): boolean;
|
|
||||||
}
|
|
||||||
@@ -78,7 +78,7 @@ export namespace plugin {
|
|||||||
scan(target: any): PluginLoadMetadata[]
|
scan(target: any): PluginLoadMetadata[]
|
||||||
/**
|
/**
|
||||||
* 读取插件 返回插件加载元信息
|
* 读取插件 返回插件加载元信息
|
||||||
* @param target
|
* @param target
|
||||||
*/
|
*/
|
||||||
read(target: any): PluginLoadMetadata
|
read(target: any): PluginLoadMetadata
|
||||||
/**
|
/**
|
||||||
@@ -162,6 +162,14 @@ export namespace plugin {
|
|||||||
* 插件作者 不填默认为 Unknow
|
* 插件作者 不填默认为 Unknow
|
||||||
*/
|
*/
|
||||||
author?: string | string[]
|
author?: string | string[]
|
||||||
|
/**
|
||||||
|
* 脚本依赖
|
||||||
|
*/
|
||||||
|
depends?: string[]
|
||||||
|
/**
|
||||||
|
* 插件依赖
|
||||||
|
*/
|
||||||
|
nativeDepends?: string[]
|
||||||
/**
|
/**
|
||||||
* 插件源文件 必须指定为 __filename
|
* 插件源文件 必须指定为 __filename
|
||||||
*/
|
*/
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { provideSingleton, Autowired } from '@ccms/container'
|
import { provideSingleton, Autowired, optional } from '@ccms/container'
|
||||||
import { channel } from './channel'
|
import { channel } from './channel'
|
||||||
|
|
||||||
export namespace proxy {
|
export namespace proxy {
|
||||||
@@ -44,7 +44,7 @@ export namespace proxy {
|
|||||||
* Get a list of players connected on a certain server, or on ALL the servers.
|
* Get a list of players connected on a certain server, or on ALL the servers.
|
||||||
* @param server count server
|
* @param server count server
|
||||||
* Response:
|
* Response:
|
||||||
* String server = in.readUTF(); // The name of the server you got the player list of, as given in args.
|
* String server = in.readUTF(); // The name of the server you got the player list of, as given in args.
|
||||||
* String[] playerList = in.readUTF().split(", ");
|
* String[] playerList = in.readUTF().split(", ");
|
||||||
*/
|
*/
|
||||||
playerList(server: string | "ALL") {
|
playerList(server: string | "ALL") {
|
||||||
@@ -98,7 +98,7 @@ export namespace proxy {
|
|||||||
return this.forward("ALL", channel, data)
|
return this.forward("ALL", channel, data)
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||||
* Remember, the sending and receiving server(s) need to have a player online.
|
* Remember, the sending and receiving server(s) need to have a player online.
|
||||||
* @param server reciver
|
* @param server reciver
|
||||||
* @param channel channelName
|
* @param channel channelName
|
||||||
@@ -112,7 +112,7 @@ export namespace proxy {
|
|||||||
return this.finalSend()
|
return this.finalSend()
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||||
* Remember, the sending and receiving server(s) need to have a player online.
|
* Remember, the sending and receiving server(s) need to have a player online.
|
||||||
* @param server reciver
|
* @param server reciver
|
||||||
* @param channel channelName
|
* @param channel channelName
|
||||||
@@ -147,6 +147,7 @@ export namespace proxy {
|
|||||||
}
|
}
|
||||||
@provideSingleton(BungeeCord)
|
@provideSingleton(BungeeCord)
|
||||||
export class BungeeCord {
|
export class BungeeCord {
|
||||||
|
@optional()
|
||||||
@Autowired()
|
@Autowired()
|
||||||
private channel: channel.Channel
|
private channel: channel.Channel
|
||||||
/**
|
/**
|
||||||
@@ -157,4 +158,4 @@ export namespace proxy {
|
|||||||
return new bungeecord.SubChannelBuilder(this.channel, player)
|
return new bungeecord.SubChannelBuilder(this.channel, player)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
import { injectable, inject } from '@ccms/container'
|
import { injectable, Autowired, ContainerInstance, Container, postConstruct } from '@ccms/container'
|
||||||
|
|
||||||
import { NativePluginManager } from './native_plugin'
|
import { constants } from './constants'
|
||||||
import { constants } from '../../constants'
|
|
||||||
|
|
||||||
export { NativePluginManager } from './native_plugin'
|
|
||||||
|
|
||||||
export namespace server {
|
export namespace server {
|
||||||
/**
|
/**
|
||||||
@@ -19,6 +16,24 @@ export namespace server {
|
|||||||
* Runtime Server Instance
|
* Runtime Server Instance
|
||||||
*/
|
*/
|
||||||
export const ServerInstance = Symbol("ServerInstance")
|
export const ServerInstance = Symbol("ServerInstance")
|
||||||
|
@injectable()
|
||||||
|
export abstract class NativePluginManager {
|
||||||
|
has(name: string): boolean {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
load(name: string): boolean {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
unload(name: string): boolean {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
reload(name: string): boolean {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
delete(name: string): boolean {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* MiaoScript Server
|
* MiaoScript Server
|
||||||
*/
|
*/
|
||||||
@@ -48,9 +63,6 @@ export namespace server {
|
|||||||
getPluginsFolder(): string {
|
getPluginsFolder(): string {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
getNativePluginManager(): NativePluginManager {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getDedicatedServer?(): any {
|
getDedicatedServer?(): any {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
@@ -63,8 +75,9 @@ export namespace server {
|
|||||||
}
|
}
|
||||||
@injectable()
|
@injectable()
|
||||||
export class ServerChecker {
|
export class ServerChecker {
|
||||||
@inject(ServerType)
|
@Autowired(ServerType)
|
||||||
private serverType: string
|
private serverType: string
|
||||||
|
|
||||||
check(servers: string[]) {
|
check(servers: string[]) {
|
||||||
// Not set servers -> allow
|
// Not set servers -> allow
|
||||||
if (!servers || !servers.length) return true
|
if (!servers || !servers.length) return true
|
||||||
@@ -80,14 +93,17 @@ export namespace server {
|
|||||||
}
|
}
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class ReflectServer extends server.Server {
|
export abstract class ReflectServer extends server.Server {
|
||||||
|
@Autowired(ContainerInstance)
|
||||||
|
private container: Container
|
||||||
|
|
||||||
protected pipeline: any
|
protected pipeline: any
|
||||||
protected rootLogger: any
|
protected rootLogger: any
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super()
|
super()
|
||||||
this.reflect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
protected reflect() {
|
protected reflect() {
|
||||||
try {
|
try {
|
||||||
let consoleServer = this.getDedicatedServer()
|
let consoleServer = this.getDedicatedServer()
|
||||||
@@ -107,7 +123,11 @@ export namespace server {
|
|||||||
if (connection.class.name.indexOf('ServerConnection') !== -1
|
if (connection.class.name.indexOf('ServerConnection') !== -1
|
||||||
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
|
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
|
||||||
connection = undefined
|
connection = undefined
|
||||||
} catch (error) { }
|
} catch (error) {
|
||||||
|
if (global.debug) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||||
for (const field of constants.Reflect.Field.listeningChannels) {
|
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||||
@@ -115,16 +135,30 @@ export namespace server {
|
|||||||
promise = reflect.on(connection).get(field).get().get(0)
|
promise = reflect.on(connection).get(field).get().get(0)
|
||||||
if (promise.class.name.indexOf('Promise') !== -1) { break }
|
if (promise.class.name.indexOf('Promise') !== -1) { break }
|
||||||
promise = undefined
|
promise = undefined
|
||||||
} catch (error) { }
|
} catch (error) {
|
||||||
|
if (global.debug) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||||
|
this.container.bind(constants.ServiceIdentifier.NettyPipeline).toConstantValue(this.pipeline)
|
||||||
}
|
}
|
||||||
protected reflectRootLogger(consoleServer: any) {
|
protected reflectRootLogger(consoleServer: any) {
|
||||||
try {
|
try {
|
||||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
try { this.rootLogger = reflect.on(consoleServer).get(0).get().parent } catch (error) { }
|
if (global.debug) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
this.rootLogger = reflect.on(consoleServer).get(0).get().parent
|
||||||
|
} catch (error) {
|
||||||
|
if (global.debug) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
|
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
|
||||||
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
||||||
@@ -135,6 +169,7 @@ export namespace server {
|
|||||||
this.rootLogger = this.rootLogger.parent
|
this.rootLogger = this.rootLogger.parent
|
||||||
}
|
}
|
||||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
||||||
|
this.container.bind(constants.ServiceIdentifier.RootLogger).toConstantValue(this.rootLogger)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,34 +1,66 @@
|
|||||||
import { plugin } from './index'
|
import { plugin } from './index'
|
||||||
import { injectable } from '@ccms/container'
|
import { injectable } from '@ccms/container'
|
||||||
|
|
||||||
|
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||||
|
|
||||||
export namespace task {
|
export namespace task {
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class TaskManager {
|
export abstract class TaskManager {
|
||||||
protected cacheTasks = new Map<string, task.Task[]>()
|
protected taskId: java.util.concurrent.atomic.AtomicInteger
|
||||||
|
protected cacheTasks = new Map<number, task.Task>()
|
||||||
|
protected pluginCacheTasks = new Map<string, Map<number, task.Task>>()
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.taskId = new AtomicInteger(0)
|
||||||
|
process.on('task.finish', (task: task.Task) => {
|
||||||
|
let taskId = task.getTaskId()
|
||||||
|
this.cacheTasks.delete(taskId)
|
||||||
|
let ownerName = task.getOwner()?.description.name
|
||||||
|
if (ownerName && this.pluginCacheTasks.has(ownerName)) {
|
||||||
|
this.pluginCacheTasks.get(ownerName).delete(taskId)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
||||||
if (!this.cacheTasks.has(plugin.description.name)) {
|
if (!this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
this.cacheTasks.set(plugin.description.name, [])
|
this.pluginCacheTasks.set(plugin.description.name, new Map())
|
||||||
}
|
}
|
||||||
this.cacheTasks.get(plugin.description.name).push(task)
|
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
|
||||||
return task
|
return task
|
||||||
}
|
}
|
||||||
|
|
||||||
protected pluginDisable(plugin: plugin.Plugin) {
|
protected pluginDisable(plugin: plugin.Plugin) {
|
||||||
if (this.cacheTasks.has(plugin.description.name)) {
|
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
this.cacheTasks.get(plugin.description.name).forEach(task => task.cancel())
|
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => {
|
||||||
this.cacheTasks.delete(plugin.description.name)
|
task.cancel()
|
||||||
|
})
|
||||||
|
this.pluginCacheTasks.delete(plugin.description.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获得自增的任务ID
|
||||||
|
*/
|
||||||
|
protected nextId() {
|
||||||
|
return this.taskId.incrementAndGet()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建任务
|
* 创建任务
|
||||||
* @param func 任务内容
|
* @param func 任务内容
|
||||||
*/
|
*/
|
||||||
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
||||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
||||||
let task = this.create0(func)
|
let task = this.create0(plugin, func, this.nextId())
|
||||||
|
this.cacheTasks.set(task.getTaskId(), task)
|
||||||
if (plugin) { return this.pluginCreate(plugin, task) }
|
if (plugin) { return this.pluginCreate(plugin, task) }
|
||||||
return task
|
return task
|
||||||
}
|
}
|
||||||
|
cancel(taskId: number) {
|
||||||
|
if (!this.cacheTasks.has(taskId)) { throw new Error(`Task ${taskId} not found!`) }
|
||||||
|
this.cacheTasks.get(taskId).cancel()
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 在主线程执行代码
|
* 在主线程执行代码
|
||||||
* @param func 执行内容
|
* @param func 执行内容
|
||||||
@@ -41,22 +73,33 @@ export namespace task {
|
|||||||
if (plugin) { return this.pluginDisable(plugin) }
|
if (plugin) { return this.pluginDisable(plugin) }
|
||||||
this.disable0()
|
this.disable0()
|
||||||
}
|
}
|
||||||
protected abstract create0(func: Function): task.Task
|
protected abstract create0(owner: plugin.Plugin, func: Function, id: number): task.Task
|
||||||
protected abstract disable0()
|
protected abstract disable0()
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 任务抽象
|
* 任务抽象
|
||||||
*/
|
*/
|
||||||
export abstract class Task {
|
export abstract class Task implements Cancelable {
|
||||||
protected plugin: any
|
|
||||||
protected func: Function
|
protected func: Function
|
||||||
protected isAsync: boolean = false;
|
protected isAsync: boolean = false;
|
||||||
protected laterTime: number = 0;
|
protected laterTime: number = 0;
|
||||||
protected interval: number = 0;
|
protected interval: number = 0;
|
||||||
|
protected owner: plugin.Plugin
|
||||||
|
protected taskId: number
|
||||||
|
protected innerTask: any
|
||||||
|
|
||||||
constructor(plugin: any, func: Function) {
|
constructor(owner: plugin.Plugin, func: Function, id: number) {
|
||||||
this.plugin = plugin
|
this.owner = owner
|
||||||
this.func = func
|
this.func = func
|
||||||
|
this.taskId = id
|
||||||
|
}
|
||||||
|
|
||||||
|
getOwner() {
|
||||||
|
return this.owner
|
||||||
|
}
|
||||||
|
|
||||||
|
getTaskId() {
|
||||||
|
return this.taskId
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -90,12 +133,15 @@ export namespace task {
|
|||||||
* 取消任务
|
* 取消任务
|
||||||
*/
|
*/
|
||||||
cancel(): boolean {
|
cancel(): boolean {
|
||||||
throw new Error("Method not implemented.")
|
let result = this.cancel0()
|
||||||
|
process.emit('task.finish', this)
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
protected run(...args: any[]): void {
|
protected run(...args: any[]): void {
|
||||||
try {
|
try {
|
||||||
this.func(...args)
|
this.func(...args)
|
||||||
|
!this.interval && process.emit('task.finish', this)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console('§4插件执行任务时发生错误', ex)
|
console.console('§4插件执行任务时发生错误', ex)
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
@@ -107,16 +153,21 @@ export namespace task {
|
|||||||
* @param args 任务参数
|
* @param args 任务参数
|
||||||
*/
|
*/
|
||||||
submit(...args: any[]): Cancelable {
|
submit(...args: any[]): Cancelable {
|
||||||
let cancelable = this.submit0(...args)
|
this.innerTask = this.submit0(...args)
|
||||||
this.cancel = cancelable.cancel
|
return this
|
||||||
return cancelable
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 提交任务
|
* 提交任务
|
||||||
* @param args 任务参数
|
* @param args 任务参数
|
||||||
*/
|
*/
|
||||||
protected abstract submit0(...args: any[]): Cancelable
|
protected abstract submit0(...args: any[]): any
|
||||||
|
/**
|
||||||
|
* 取消任务
|
||||||
|
*/
|
||||||
|
protected cancel0(): boolean {
|
||||||
|
return this.innerTask?.cancel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 返可取消的对象
|
* 返可取消的对象
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bukkit",
|
"name": "@ccms/bukkit",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript bukkit package",
|
"description": "MiaoScript bukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/spigot-api": "^0.0.3",
|
"@javatypes/spigot-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.10.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,17 +7,14 @@ const Callable = Java.type('java.util.concurrent.Callable')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class BukkitTaskManager extends task.TaskManager {
|
export class BukkitTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
private pluginInstance: any
|
return new BukkitTask(owner, func, id)
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
|
||||||
return new BukkitTask(this.pluginInstance, func)
|
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
return Bukkit.getScheduler().callSyncMethod(base.getInstance(), new Callable({ call: () => func() })).get()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
Bukkit.getScheduler().cancelTasks(this.pluginInstance)
|
Bukkit.getScheduler().cancelTasks(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,9 +23,9 @@ export class BukkitTask extends task.Task {
|
|||||||
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
||||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
return run[funcName](base.getInstance(), this.laterTime, this.interval)
|
||||||
} else {
|
} else {
|
||||||
return run[funcName](this.plugin, this.laterTime)
|
return run[funcName](base.getInstance(), this.laterTime)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bungee",
|
"name": "@ccms/bungee",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript bungee package",
|
"description": "MiaoScript bungee package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/bungee-api": "^0.0.3",
|
"@javatypes/bungee-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.10.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,17 +6,14 @@ let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class BungeeTaskManager extends task.TaskManager {
|
export class BungeeTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
private pluginInstance: any
|
return new BungeeTask(owner, func, id)
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
|
||||||
return new BungeeTask(this.pluginInstance, func)
|
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func()
|
return func()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
this.pluginInstance.getProxy().getScheduler().cancel(this.pluginInstance)
|
base.getInstance().getProxy().getScheduler().cancel(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,12 +21,12 @@ export class BungeeTask extends task.Task {
|
|||||||
submit0(...args: any[]): task.Cancelable {
|
submit0(...args: any[]): task.Cancelable {
|
||||||
let run = new Runnable({ run: () => this.run(...args) })
|
let run = new Runnable({ run: () => this.run(...args) })
|
||||||
if (this.isAsync) {
|
if (this.isAsync) {
|
||||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
return base.getInstance().getProxy().getScheduler().runAsync(base.getInstance(), run)
|
||||||
}
|
}
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
||||||
} else {
|
} else {
|
||||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "@ccms/client",
|
"name": "@ccms/client",
|
||||||
"version": "0.9.4",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript client package",
|
"description": "MiaoScript client package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,10 +22,10 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"minecraft-protocol": "^1.16.0"
|
"minecraft-protocol": "^1.19.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/common",
|
"name": "@ccms/common",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,11 +19,11 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.10.1",
|
||||||
"@javatypes/jdk": "^0.0.3",
|
"@javatypes/jdk": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
/// <reference types="@javatypes/jdk" />
|
/// <reference types="@javatypes/jdk" />
|
||||||
|
|
||||||
|
const JavaClass = Java.type('java.lang.Class')
|
||||||
|
const JavaObject = Java.type('java.lang.Object')
|
||||||
|
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
|
||||||
|
const fieldCache = new Map<string, java.lang.reflect.Field>()
|
||||||
|
const methodCache = new Map<string, java.lang.reflect.Method>()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 反射工具类
|
* 反射工具类
|
||||||
* Created by MiaoWoo on 2017/2/9 0009.
|
* Created by MiaoWoo on 2017/2/9 0009.
|
||||||
*/
|
*/
|
||||||
const JavaClass = Java.type('java.lang.Class')
|
|
||||||
const JavaObject = Java.type('java.lang.Object')
|
|
||||||
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
|
|
||||||
const methodCache = []
|
|
||||||
|
|
||||||
class Reflect {
|
class Reflect {
|
||||||
private obj: java.lang.Object
|
private obj: java.lang.Object
|
||||||
private class: java.lang.Class<any>
|
private class: java.lang.Class<any>
|
||||||
@@ -34,15 +35,26 @@ class Reflect {
|
|||||||
return Java.from(declaredMethods(this.class))
|
return Java.from(declaredMethods(this.class))
|
||||||
}
|
}
|
||||||
|
|
||||||
field(name: string | java.lang.String): Reflect {
|
field(nameOrIndex: string | java.lang.String | number, declared = false): java.lang.reflect.Field {
|
||||||
try {
|
if (nameOrIndex == undefined || nameOrIndex == null) throw new Error(`reflect field name can't be ${nameOrIndex} from ${this.class.getName()}!`)
|
||||||
// Try getting a public field
|
let key = this.class.getName() + ':' + nameOrIndex + ':' + declared
|
||||||
let field = this.class.getField(name)
|
if (fieldCache.has(key)) {
|
||||||
return on(field.get(this.obj))
|
return fieldCache.get(key)
|
||||||
} catch (ex) {
|
|
||||||
// Try again, getting a non-public field
|
|
||||||
return on(accessible(declaredField(this.class, name)).get(this.obj))
|
|
||||||
}
|
}
|
||||||
|
let field = null
|
||||||
|
if (typeof nameOrIndex == "number") {
|
||||||
|
field = this.fields(declared)[nameOrIndex]
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
// Try getting a public field
|
||||||
|
field = this.class.getField(nameOrIndex)
|
||||||
|
} catch (ex) {
|
||||||
|
// Try again, getting a non-public field
|
||||||
|
field = declaredField(this.class, nameOrIndex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!field) throw new Error(`can't reflect field ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${this.class.getName()}!`)
|
||||||
|
return accessible(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
fields(declared = false): java.lang.reflect.Field[] {
|
fields(declared = false): java.lang.reflect.Field[] {
|
||||||
@@ -50,7 +62,7 @@ class Reflect {
|
|||||||
}
|
}
|
||||||
|
|
||||||
values(declared = false) {
|
values(declared = false) {
|
||||||
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.field(field.getName()).get() }, {}) as any
|
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.get(field.getName()).get() }, {}) as any
|
||||||
}
|
}
|
||||||
|
|
||||||
call(...args: any[]): Reflect {
|
call(...args: any[]): Reflect {
|
||||||
@@ -64,17 +76,12 @@ class Reflect {
|
|||||||
get(index: number, declared?: boolean): Reflect
|
get(index: number, declared?: boolean): Reflect
|
||||||
get(prop: string): Reflect
|
get(prop: string): Reflect
|
||||||
get(param?: string | number, declared: boolean = true): Reflect | any {
|
get(param?: string | number, declared: boolean = true): Reflect | any {
|
||||||
if (param == undefined || param == null) return this.obj
|
if (arguments.length === 0) return this.obj
|
||||||
if (typeof param == "number") {
|
return on(this.field(param, declared).get(this.obj))
|
||||||
return on(accessible(this.fields(declared)[param]).get(this.obj))
|
|
||||||
}
|
|
||||||
if (typeof param == "string") {
|
|
||||||
return this.field(param)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
set(name: any, value: any): Reflect {
|
set(param: string | number, value: any, declared: boolean = true): Reflect {
|
||||||
accessible(declaredField(this.class, name)).set(this.obj, value)
|
this.field(param, declared).set(this.obj, value)
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,64 +143,43 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
|||||||
return field
|
return field
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethod(clazz: java.lang.Class<any>, name: string, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
function declaredMethod(clazz: java.lang.Class<any>, nameOrIndex: string | number, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
||||||
let key = clazz.getName() + '.' + name + ':' + (clazzs || []).join(':')
|
let key = clazz.getName() + '.' + nameOrIndex + ':' + (clazzs || []).map(c => c.getName()).join(':')
|
||||||
if (!methodCache[key]) {
|
if (methodCache.has(key)) { return methodCache.get(key) }
|
||||||
|
if (typeof nameOrIndex === "number") {
|
||||||
|
methodCache.set(key, declaredMethods(clazz)[nameOrIndex])
|
||||||
|
} else {
|
||||||
try {
|
try {
|
||||||
// @ts-ignore
|
methodCache.set(key, clazz.getMethod(nameOrIndex, clazzs as any))
|
||||||
methodCache[key] = clazz.getMethod(name, clazzs)
|
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
try {
|
try {
|
||||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs as any)
|
methodCache.set(key, clazz.getDeclaredMethod(nameOrIndex, clazzs as any))
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
for (const m of Java.from(declaredMethods(clazz))) {
|
for (const m of Java.from(declaredMethods(clazz))) {
|
||||||
if (m.getName() == name) {
|
if (m.getName() == nameOrIndex) {
|
||||||
methodCache[key] = m
|
methodCache.set(key, m)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return methodCache[key]
|
if (!methodCache.has(key)) throw new Error(`can't reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${clazz.getName()}!`)
|
||||||
|
return methodCache.get(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethods(clazz: java.lang.Class<any>) {
|
function declaredMethods(clazz: java.lang.Class<any>) {
|
||||||
return clazz.getDeclaredMethods()
|
return clazz.getDeclaredMethods()
|
||||||
}
|
}
|
||||||
|
|
||||||
let classMethodsCache: any[] = []
|
|
||||||
|
|
||||||
function mapToObject(javaObj) {
|
function mapToObject(javaObj) {
|
||||||
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||||
let target = {}
|
let target = Proxy.newProxy(javaObj, {
|
||||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t))
|
apply: (target, name, args) => { return args ? javaObj[name](args) : javaObj[name]() }
|
||||||
|
})
|
||||||
return target
|
return target
|
||||||
}
|
}
|
||||||
|
|
||||||
function getJavaObjectMethods(javaObj) {
|
|
||||||
let className = javaObj.class.name
|
|
||||||
if (!classMethodsCache[className]) {
|
|
||||||
let names: any[] = []
|
|
||||||
let methods = javaObj.class.methods
|
|
||||||
for (let i in methods) {
|
|
||||||
names.push(methods[i].name)
|
|
||||||
}
|
|
||||||
classMethodsCache[className] = names
|
|
||||||
}
|
|
||||||
return classMethodsCache[className]
|
|
||||||
}
|
|
||||||
|
|
||||||
function mapMethod(target, source, name) {
|
|
||||||
target[name] = function __SimpleDynamicMethod__(...args) {
|
|
||||||
if (args.length > 0) {
|
|
||||||
return source[name](args)
|
|
||||||
} else {
|
|
||||||
return source[name]()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function on(obj) {
|
function on(obj) {
|
||||||
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
||||||
return new Reflect(obj)
|
return new Reflect(obj)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/compile",
|
"name": "@ccms/compile",
|
||||||
"version": "0.9.4",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript compile package",
|
"description": "MiaoScript compile package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,6 +21,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/container",
|
"name": "@ccms/container",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript container package",
|
"description": "MiaoScript container package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,10 +19,10 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.10.1",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"inversify": "^5.0.1",
|
"inversify": "^5.0.1",
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export const Autowired = (className?: any) => {
|
|||||||
return inject(className)(target, propertyKey, index)
|
return inject(className)(target, propertyKey, index)
|
||||||
}
|
}
|
||||||
let type = Reflect.getMetadata('design:type', target, propertyKey)
|
let type = Reflect.getMetadata('design:type', target, propertyKey)
|
||||||
if (type && type !== Object && Java.isJavaObject(type)) {
|
if (type && type !== Object && !Java.isJavaObject(type)) {
|
||||||
inject(type)(target, propertyKey, index)
|
inject(type)(target, propertyKey, index)
|
||||||
named(className || propertyKey)(target, propertyKey, index)
|
named(className || propertyKey)(target, propertyKey, index)
|
||||||
} else if (container.isBound(ioc.Autowired)) {
|
} else if (container.isBound(ioc.Autowired)) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/core",
|
"name": "@ccms/core",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,11 +21,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.10.1"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -99,6 +99,7 @@ function initialize() {
|
|||||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
||||||
container.bind(server.ServerType).toConstantValue(type)
|
container.bind(server.ServerType).toConstantValue(type)
|
||||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
||||||
|
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
|
||||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
||||||
require(`${global.scope}/${type}`).default(container)
|
require(`${global.scope}/${type}`).default(container)
|
||||||
require(`${global.scope}/plugin`)
|
require(`${global.scope}/plugin`)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/database",
|
"name": "@ccms/database",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript database package",
|
"description": "MiaoScript database package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,10 +22,10 @@
|
|||||||
"@javatypes/spring-jdbc": "^0.0.3",
|
"@javatypes/spring-jdbc": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.10.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/i18n",
|
"name": "@ccms/i18n",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript i18n package",
|
"description": "MiaoScript i18n package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,11 +19,11 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.10.1",
|
||||||
"@types/js-yaml": "^3.12.5",
|
"@types/js-yaml": "^3.12.5",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"js-yaml": "^3.14.0"
|
"js-yaml": "^3.14.0"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/keyvalue",
|
"name": "@ccms/keyvalue",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript keyvalue package",
|
"description": "MiaoScript keyvalue package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,18 +19,18 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.10.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.10.1",
|
||||||
"@javatypes/amqp-client": "^0.0.3",
|
"@javatypes/amqp-client": "^0.0.3",
|
||||||
"@javatypes/spring-amqp": "^0.0.3",
|
"@javatypes/spring-amqp": "^0.0.3",
|
||||||
"@javatypes/spring-rabbit": "^0.0.3",
|
"@javatypes/spring-rabbit": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/nashorn",
|
"name": "@ccms/nashorn",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,6 +22,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,8 +81,18 @@ declare global {
|
|||||||
i18n(name: string, ...params: any[]): void
|
i18n(name: string, ...params: any[]): void
|
||||||
}
|
}
|
||||||
interface ProxyConstructor {
|
interface ProxyConstructor {
|
||||||
newProxy<T extends object>(target: T, handler: ProxyHandler<T>): T
|
newProxy<T extends object>(target: T, handler: ProxyHandle<T>): T
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export interface ProxyHandle<T = any> extends ProxyHandler<any> {
|
||||||
|
setPrototypeOf?(target: T, v: any): any
|
||||||
|
// get: (target: any, name: string) => any
|
||||||
|
// set: (target: any, name: string, value: any) => boolean
|
||||||
|
// construct: (target: any, ...args: any[]) => any
|
||||||
|
// has: (target: any, name: string) => boolean
|
||||||
|
// ownKeys: (target: any) => string[]
|
||||||
|
values?: (target: T) => any[]
|
||||||
|
// call: (target: any, name: string, ...args: any[]) => any
|
||||||
|
// deleteProperty: (target: any, name: string) => boolean
|
||||||
|
}
|
||||||
export { }
|
export { }
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/nodejs",
|
"name": "@ccms/nodejs",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript nodejs package",
|
"description": "MiaoScript nodejs package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,10 +19,10 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.10.1",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/nukkit",
|
"name": "@ccms/nukkit",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript nukkit package",
|
"description": "MiaoScript nukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/nukkit-api": "^0.0.3",
|
"@javatypes/nukkit-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.10.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,25 @@
|
|||||||
import { MiaoScriptConsole } from '@ccms/api'
|
import { MiaoScriptConsole } from '@ccms/api'
|
||||||
|
|
||||||
let Nukkit = base.getInstance().getServer();
|
let Nukkit = base.getInstance().getServer()
|
||||||
|
let LogLevel = Java.type('cn.nukkit.utils.LogLevel')
|
||||||
let CommandSender = Java.type('cn.nukkit.command.CommandSender')
|
let CommandSender = Java.type('cn.nukkit.command.CommandSender')
|
||||||
|
|
||||||
export class NukkitConsole extends MiaoScriptConsole {
|
export class NukkitConsole extends MiaoScriptConsole {
|
||||||
sender(sender, ...args) {
|
sender(sender, ...args) {
|
||||||
if (!(sender instanceof CommandSender)) {
|
if (!(sender instanceof CommandSender)) {
|
||||||
this.error(`First parameter ${sender} not instanceof cn.nukkit.command.CommandSender can't send message!`)
|
this.error(`First parameter ${sender} not instanceof cn.nukkit.command.CommandSender can't send message!`)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
||||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||||
} else {
|
} else {
|
||||||
sender.sendMessage(this.prefix + args.join(' '));
|
sender.sendMessage(this.prefix + args.join(' '))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console(...args: string[]): void {
|
console(...args: string[]): void {
|
||||||
this.sender(Nukkit.getConsoleSender(), args.join(' '));
|
this.sender(Nukkit.getConsoleSender(), args.join(' '))
|
||||||
|
}
|
||||||
|
error(...args: any[]) {
|
||||||
|
this.logger.log(LogLevel.ERROR, this.name + args.join(' '))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,17 +5,14 @@ const NukkitRunnable = Java.type('cn.nukkit.scheduler.NukkitRunnable')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class NukkitTaskManager extends task.TaskManager {
|
export class NukkitTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
private pluginInstance: any
|
return new NukkitTask(owner, func, id)
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
|
||||||
return new NukkitTask(this.pluginInstance, func)
|
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func()
|
return func()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
base.getInstance().getServer().getScheduler().cancelTask(this.pluginInstance)
|
base.getInstance().getServer().getScheduler().cancelTask(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,9 +21,9 @@ export class NukkitTask extends task.Task {
|
|||||||
let run = new NukkitRunnable({ run: () => this.run(...args) })
|
let run = new NukkitRunnable({ run: () => this.run(...args) })
|
||||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
return run[funcName](base.getInstance(), this.laterTime, this.interval)
|
||||||
} else {
|
} else {
|
||||||
return run[funcName](this.plugin, this.laterTime)
|
return run[funcName](base.getInstance(), this.laterTime)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/ployfill",
|
"name": "@ccms/ployfill",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript ployfill package",
|
"description": "MiaoScript ployfill package",
|
||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
@@ -14,14 +14,14 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/i18n": "^0.9.8",
|
"@ccms/i18n": "^0.10.1",
|
||||||
"@ccms/nodejs": "^0.9.8",
|
"@ccms/nodejs": "^0.10.1",
|
||||||
"core-js": "^3.6.5"
|
"core-js": "^3.7.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.10.1",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,19 @@ class Process extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
platform = Packages.java.lang.System.getProperty("os.name")
|
platform = Packages.java.lang.System.getProperty("os.name")
|
||||||
|
on(event: string | symbol, listener: (...args: any[]) => void) {
|
||||||
|
return super.on(event, (...args) => {
|
||||||
|
try {
|
||||||
|
listener(...args)
|
||||||
|
} catch (error) {
|
||||||
|
try {
|
||||||
|
super.emit('error', error)
|
||||||
|
} catch (error) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
nextTick(func: Function) {
|
nextTick(func: Function) {
|
||||||
microTaskPool.execute(func)
|
microTaskPool.execute(func)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,9 @@
|
|||||||
|
import { ProxyHandle } from '@ccms/nashorn'
|
||||||
|
|
||||||
// Nashorn JSAdapter See https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-JSAdapterconstructor
|
// Nashorn JSAdapter See https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-JSAdapterconstructor
|
||||||
let createProxy = eval(`
|
let createProxy = eval(`
|
||||||
function(handle){ return new JSAdapter(handle) }
|
function(handle){ return new JSAdapter(handle) }
|
||||||
`)
|
`)
|
||||||
export interface ProxyHandle extends ProxyHandler<any> {
|
|
||||||
// get: (target: any, name: string) => any
|
|
||||||
// set: (target: any, name: string, value: any) => boolean
|
|
||||||
// construct: (target: any, ...args: any[]) => any
|
|
||||||
// has: (target: any, name: string) => boolean
|
|
||||||
// ownKeys: (target: any) => string[]
|
|
||||||
values: (target: any) => any[];
|
|
||||||
// call: (target: any, name: string, ...args: any[]) => any
|
|
||||||
// deleteProperty: (target: any, name: string) => boolean
|
|
||||||
}
|
|
||||||
export class Proxy {
|
export class Proxy {
|
||||||
static newProxy(target: any, handle: Partial<ProxyHandle>): any {
|
static newProxy(target: any, handle: Partial<ProxyHandle>): any {
|
||||||
return new Proxy(target, handle)
|
return new Proxy(target, handle)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/plugin",
|
"name": "@ccms/plugin",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,13 +22,13 @@
|
|||||||
"@types/js-yaml": "^3.12.5",
|
"@types/js-yaml": "^3.12.5",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8",
|
"@ccms/container": "^0.10.1",
|
||||||
"@ccms/i18n": "^0.9.8",
|
"@ccms/i18n": "^0.10.1",
|
||||||
"js-yaml": "^3.14.0"
|
"js-yaml": "^3.14.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { command, plugin, server } from '@ccms/api'
|
import { command, plugin, server } from '@ccms/api'
|
||||||
import { provideSingleton, inject, Autowired } from '@ccms/container'
|
import { provideSingleton, Autowired } from '@ccms/container'
|
||||||
import { getPluginCommandMetadata, getPluginTabCompleterMetadata } from './utils'
|
import { getPluginCommandMetadata, getPluginTabCompleterMetadata } from './utils'
|
||||||
|
|
||||||
@provideSingleton(PluginCommandManager)
|
@provideSingleton(PluginCommandManager)
|
||||||
@@ -35,8 +35,6 @@ export class PluginCommandManager {
|
|||||||
|
|
||||||
private unregistryCommand(pluginInstance: plugin.Plugin) {
|
private unregistryCommand(pluginInstance: plugin.Plugin) {
|
||||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||||
cmds.forEach(cmd => {
|
cmds.forEach(cmd => this.CommandManager.off(pluginInstance, cmd.name))
|
||||||
this.CommandManager.off(pluginInstance, cmd.name)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ export class PluginConfigManager {
|
|||||||
saveConfig(plugin: plugin.Plugin) {
|
saveConfig(plugin: plugin.Plugin) {
|
||||||
let configs = getPluginConfigMetadata(plugin)
|
let configs = getPluginConfigMetadata(plugin)
|
||||||
for (let [_, config] of configs) {
|
for (let [_, config] of configs) {
|
||||||
this.saveConfig0(plugin, config)
|
config.autosave && this.saveConfig0(plugin, config)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,7 +102,6 @@ export class PluginConfigManager {
|
|||||||
|
|
||||||
private saveConfig0(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata) {
|
private saveConfig0(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata) {
|
||||||
try {
|
try {
|
||||||
if (metadata.readonly) { console.debug(`[${plugin.description.name}] Skip Save Config ${metadata.variable} Because it's readonly!`) }
|
|
||||||
metadata.file = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, metadata.filename)
|
metadata.file = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, metadata.filename)
|
||||||
let result = this.getConfigLoader(metadata.format).dump(plugin[metadata.variable])
|
let result = this.getConfigLoader(metadata.format).dump(plugin[metadata.variable])
|
||||||
base.save(metadata.file, result)
|
base.save(metadata.file, result)
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ export function config(metadata: interfaces.ConfigMetadata = {}) {
|
|||||||
metadata.variable = key
|
metadata.variable = key
|
||||||
metadata.version = metadata.version ?? 1
|
metadata.version = metadata.version ?? 1
|
||||||
metadata.format = metadata.format ?? 'yml'
|
metadata.format = metadata.format ?? 'yml'
|
||||||
|
metadata.autosave = metadata.autosave ?? false
|
||||||
metadata.filename = metadata.filename ?? metadata.name + '.' + metadata.format
|
metadata.filename = metadata.filename ?? metadata.name + '.' + metadata.format
|
||||||
let previousMetadata = getPluginConfigMetadata(target)
|
let previousMetadata = getPluginConfigMetadata(target)
|
||||||
previousMetadata.set(metadata.name, metadata)
|
previousMetadata.set(metadata.name, metadata)
|
||||||
|
|||||||
@@ -72,9 +72,9 @@ export namespace interfaces {
|
|||||||
*/
|
*/
|
||||||
format?: string
|
format?: string
|
||||||
/**
|
/**
|
||||||
* 是否为只读(关闭时将不会自动保存)
|
* 自动保存 默认为 false
|
||||||
*/
|
*/
|
||||||
readonly?: boolean
|
autosave?: boolean
|
||||||
/**
|
/**
|
||||||
* 配置文件名称
|
* 配置文件名称
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import i18n from '@ccms/i18n'
|
import i18n from '@ccms/i18n'
|
||||||
import { plugin, server, event } from '@ccms/api'
|
import { plugin, server } from '@ccms/api'
|
||||||
import { inject, provideSingleton, Container, ContainerInstance, Autowired } from '@ccms/container'
|
import { provideSingleton, Container, ContainerInstance, Autowired } from '@ccms/container'
|
||||||
|
|
||||||
import './config'
|
import './config'
|
||||||
import { interfaces } from './interfaces'
|
import { interfaces } from './interfaces'
|
||||||
@@ -13,15 +13,17 @@ const Thread = Java.type('java.lang.Thread')
|
|||||||
|
|
||||||
@provideSingleton(plugin.PluginManager)
|
@provideSingleton(plugin.PluginManager)
|
||||||
export class PluginManagerImpl implements plugin.PluginManager {
|
export class PluginManagerImpl implements plugin.PluginManager {
|
||||||
@inject(ContainerInstance)
|
@Autowired(ContainerInstance)
|
||||||
private container: Container
|
private container: Container
|
||||||
@inject(plugin.PluginInstance)
|
@Autowired(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
@inject(server.ServerType)
|
@Autowired(server.ServerType)
|
||||||
private serverType: string
|
private serverType: string
|
||||||
|
|
||||||
@Autowired()
|
@Autowired()
|
||||||
private serverChecker: server.ServerChecker
|
private serverChecker: server.ServerChecker
|
||||||
|
@Autowired()
|
||||||
|
private nativePluginManager: server.NativePluginManager
|
||||||
|
|
||||||
@Autowired()
|
@Autowired()
|
||||||
private taskManager: PluginTaskManager
|
private taskManager: PluginTaskManager
|
||||||
@@ -224,15 +226,28 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
try {
|
try {
|
||||||
this.buildPlugin(metadata)
|
this.buildPlugin(metadata)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.console(error)
|
console.console(`§4无法加载插件 §b${metadata.name} §4构建插件失败!`)
|
||||||
|
console.ex(error)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private checkDepends(depends: string | string[]) {
|
||||||
|
if (!depends) return true
|
||||||
|
for (const depend of depends) { if (!this.metadataMap.has(depend)) return false }
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
private checkNativeDepends(depends: string | string[]) {
|
||||||
|
if (!depends) return true
|
||||||
|
for (const depend of depends) { if (!this.nativePluginManager.has(depend)) return false }
|
||||||
|
return true
|
||||||
|
}
|
||||||
private buildPlugin(metadata: plugin.PluginMetadata) {
|
private buildPlugin(metadata: plugin.PluginMetadata) {
|
||||||
if (!this.loaderMap.has(metadata.type)) { throw new Error(`§4无法加载插件 §c${metadata.name} §4请检查 §c${metadata.type} §4加载器是否正常启用!`) }
|
|
||||||
if (this.instanceMap.has(metadata.name)) { throw new Error(`Plugin ${metadata.name} is already load from ${metadata.source}...`) }
|
if (this.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.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 pluginInstance = this.loaderMap.get(metadata.type).build(metadata)
|
let pluginInstance = this.loaderMap.get(metadata.type).build(metadata)
|
||||||
if (!pluginInstance) { throw new Error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`) }
|
if (!pluginInstance) { throw new Error(`§4加载器 §c${metadata.type} §4加载插件 §c${metadata.name} §4失败!`) }
|
||||||
this.instanceMap.set(metadata.name, pluginInstance)
|
this.instanceMap.set(metadata.name, pluginInstance)
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export class PluginTaskManager {
|
|||||||
private taskManager: task.TaskManager
|
private taskManager: task.TaskManager
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.cancelTask(plugin))
|
process.on('plugin.after.disable', this.cancelTask.bind(this))
|
||||||
}
|
}
|
||||||
|
|
||||||
private cancelTask(pluginInstance: plugin.Plugin) {
|
private cancelTask(pluginInstance: plugin.Plugin) {
|
||||||
|
|||||||
67
packages/plugins/docs/MiaoBlockly.md
Normal file
67
packages/plugins/docs/MiaoBlockly.md
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
# MiaoBlockly
|
||||||
|
|
||||||
|
## 前言
|
||||||
|
|
||||||
|
- 嗯 我又来了
|
||||||
|
- 之前承诺的 MiaoScript 腐竹可以用的版本
|
||||||
|
- 第一个 Demo 版本 MiaoBlockly 写完了
|
||||||
|
|
||||||
|
### 什么是 MiaoBlockly
|
||||||
|
|
||||||
|
#### ~~对于开发者~~(开发一般不会用这玩意儿)
|
||||||
|
|
||||||
|
#### 对于腐竹
|
||||||
|
- 可以在网页上开发一些简单的插件
|
||||||
|
- 拖动方块就能实现了
|
||||||
|
|
||||||
|
### 图片展示
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### MiaoBlockly 的兼容性
|
||||||
|
- 跨端兼容 Sponge Bukkit BungeeCord
|
||||||
|
- Bukkit 支持 1.12.2 +(由于1.12.2以下版本Netty版本过老需要适配 后续兼容到1.7.10)
|
||||||
|
- Sponge
|
||||||
|
- CatServer 1.12.2+
|
||||||
|
- BungeeCord
|
||||||
|
|
||||||
|
### 安装教程
|
||||||
|
- 安装 `MiaoConsole` [站内地址](https://www.mcbbs.net/thread-1129227-1-1.html) 没错 就是装 MiaoConsole
|
||||||
|
- 因为 `MiaoBlockly` 底层还是运行的 js 只是用 `Blockly` 生成了代码而已
|
||||||
|
- 需要 `MiaoConsole` 是因为需要和服务器通信
|
||||||
|
|
||||||
|
### 使用教程
|
||||||
|
- 查看启动日志 获取临时 `Token`
|
||||||
|
- 或者 执行 `mconsole token` 获得临时Token
|
||||||
|
- 打开 `http://ms.yumc.pw/blockly.html`
|
||||||
|
- 在地址栏输入服务器地址 需要带上端口
|
||||||
|
- 在 Token 栏输入获取到的 Token
|
||||||
|
- 点击链接即可
|
||||||
|
|
||||||
|
### 编辑器使用
|
||||||
|
- 默认界面有一个插件主体
|
||||||
|
- 拖动积木 右侧会自动生成代码
|
||||||
|
- 在代码界面 按下 `Ctrl + S` 代码会自动传送到服务器 并且重载插件
|
||||||
|
- 更多功能还在开发
|
||||||
|
|
||||||
|
### RoadMap
|
||||||
|
- 开发聊天相关功能
|
||||||
|
- 完善事件相关功能
|
||||||
|
- 开发命令相关功能
|
||||||
|
- 开发跨服相关功能
|
||||||
|
- 统一各个端之间的事件(工作量较大 可能会咕咕咕)
|
||||||
|
- 脚本商城 方便开发和腐竹之前的 PY 交易
|
||||||
|
- 脚本打包成 Jar 方便部署
|
||||||
|
|
||||||
|
### Miao系列插件
|
||||||
|
|
||||||
|
- [[经济]MiaoReward —— 喵式奖励 让玩家看广告为服务器提供收入吧[1.7.10+全版本]](https://www.mcbbs.net/thread-1121423-1-1.html)
|
||||||
|
- [[编程]MiaoBlockly —— 喵式积木 用简单的积木来写插件吧[1.12.2+全版本]](https://www.mcbbs.net/thread-1129411-1-1.html)
|
||||||
|
- [[编程]MiaoConsole —— 喵式终端 通过MC端口直接控制服务器 调试插件[1.12.2+全版本]](https://www.mcbbs.net/thread-1129227-1-1.html)
|
||||||
|
- [[管理]MiaoBind —— 喵式绑定 兼容SoulBound的绑定插件 支持自定义关键词[1.7+全版本]](https://www.mcbbs.net/thread-922072-1-1.html)
|
||||||
|
- [[信息]MiaoBoard —— 喵式记分板 自定义动态记分板[1.7+全版本]](https://www.mcbbs.net/thread-631482-1-1.html)
|
||||||
|
- [[聊天]MiaoChat —— 喵式聊天 多功能自定义聊天格式 新增支持跨服[1.7.10+全版本]](https://www.mcbbs.net/thread-631240-1-1.html)
|
||||||
|
- [[菜单]MiaoMenu —— 喵式菜单 强大的自定义菜单 支持多种自定义操作[1.7+全版本]](https://www.mcbbs.net/thread-860047-1-1.html)
|
||||||
|
- [[管理]YUM —— 全能的服务器插件管理工具 全自动安装插件 更新插件[1.7.2+全版本]](https://www.mcbbs.net/thread-701333-1-1.html)
|
||||||
|
|
||||||
|
本插件所用所有代码均为原创,不存在借用/抄袭等行为
|
||||||
@@ -1,12 +1,24 @@
|
|||||||
|
# MiaoConsole
|
||||||
|
|
||||||
## 前言
|
## 前言
|
||||||
|
|
||||||
> 各位开发 在调试Minecraft插件的时候 是不是经常面临下列情况
|
> 各位开发 在调试Minecraft插件的时候 是不是经常面临下列情况
|
||||||
- 编译等半天 重启等半天 测试找不到问题
|
- 编译等半天 重启等半天 测试找不到问题
|
||||||
- 后台 IDE SCP/FTP 来回切换
|
- 后台 IDE SCP/FTP 来回切换
|
||||||
|
|
||||||
### 什么是MiaoConsole
|
> 各位腐竹 在开服的时候 是不是经常遇到下列情况
|
||||||
- MiaoConsole 是 基于 MiaoScript 开发的 在线调试工具
|
- 修改一个配置文件 经常格式错误
|
||||||
- 通过复用 Minecraft的Netty 通道 实现服务器端口 在线调试(并不是Java的调试哦)
|
- 各种报错看不懂 插件依赖找不到
|
||||||
|
|
||||||
|
### 什么是 MiaoConsole
|
||||||
|
|
||||||
|
#### 对于开发者
|
||||||
|
- MiaoConsole 是 基于 `MiaoScript` 开发的 在线调试工具
|
||||||
|
- 通过复用 Minecraft 的 Netty 通道 实现服务器端口 `MiaoScript` 在线调试
|
||||||
|
|
||||||
|
#### 对于腐竹
|
||||||
|
- 可以在网页上实时看到服务器日志
|
||||||
|
- 共享 Token 给插件开发者 让其帮助调试服务器
|
||||||
|
|
||||||
### 工具动图
|
### 工具动图
|
||||||
|
|
||||||
@@ -16,8 +28,8 @@
|
|||||||
### MiaoConsole 有哪些功能
|
### MiaoConsole 有哪些功能
|
||||||
- 无需编译 上传等步骤 实时在线debug
|
- 无需编译 上传等步骤 实时在线debug
|
||||||
- 实时转发服务端日志 无需来回切换
|
- 实时转发服务端日志 无需来回切换
|
||||||
- 基于Nashorn的动态脚本语言
|
- 基于 Nashorn 的动态脚本语言
|
||||||
- 基于TypeScript的自动补全逻辑(以实现BungeeCord Sponge Bukkit的API全自动补全)
|
- 基于 TypeScript 的自动补全逻辑(以实现BungeeCord Sponge Bukkit的API全自动补全)
|
||||||
|
|
||||||
### MiaoConsole 的兼容性
|
### MiaoConsole 的兼容性
|
||||||
- 跨端兼容 Sponge Bukkit BungeeCord
|
- 跨端兼容 Sponge Bukkit BungeeCord
|
||||||
@@ -27,25 +39,27 @@
|
|||||||
- BungeeCord ~~终端转发暂未兼容~~ 已经能兼容了
|
- BungeeCord ~~终端转发暂未兼容~~ 已经能兼容了
|
||||||
|
|
||||||
### 安装教程
|
### 安装教程
|
||||||
- 安装MiaoScript [下载地址](http://w.yumc.pw/free.html#MiaoScript-download)
|
- 安装 `MiaoScript` [站内地址](https://www.mcbbs.net/thread-774401-1-1.html)
|
||||||
- 首次启动 等待加载基础环境类库
|
- 如果你已经安装了 Yum 可以通过 Yum 快速安装 `/yum install MiaoScript`
|
||||||
- 执行 `mpm i MiaoConsole`
|
- 等待 MiaoScript 引擎启动完成(首次启动可能需要10-20秒 依赖于您的网络环境)
|
||||||
|
- 执行 `mspm i MiaoConsole`
|
||||||
|
|
||||||
### 使用教程
|
### 使用教程
|
||||||
- 执行 `mconsole token` 获得临时Token
|
- 查看启动日志 获取临时 `Token`
|
||||||
|
- 或者 执行 `mconsole token` 获得临时Token
|
||||||
- 打开 `http://ms.yumc.pw/console.html`
|
- 打开 `http://ms.yumc.pw/console.html`
|
||||||
- 在地址栏输入服务器地址 需要带上端口
|
- 在地址栏输入服务器地址 需要带上端口
|
||||||
- 在Token栏输入获取到的Token
|
- 在 Token 栏输入获取到的 Token
|
||||||
- 点击链接即可
|
- 点击链接即可
|
||||||
|
|
||||||
### 终端使用
|
### 终端使用
|
||||||
- 支持实时传输服务器日志到终端
|
- 支持实时传输服务器日志到终端
|
||||||
- 直接在终端输入命令 会转发到服务器
|
- 直接在终端输入命令 会转发到服务器
|
||||||
- 目前暂不支持命令自动补全
|
- 支持命令自动补全
|
||||||
- 支持命令历史
|
- 支持命令历史
|
||||||
|
|
||||||
### 代码编辑器使用
|
### 代码编辑器使用
|
||||||
- 支持 Java 的 lang包和util包自动补全
|
- 支持 Java 的类自动补全
|
||||||
- 支持服务端所有代码补全
|
- 支持服务端所有代码补全
|
||||||
- 注意 暂时不支持自动导入包 所以需要手动输入全类名
|
- 注意 暂时不支持自动导入包 所以需要手动输入全类名
|
||||||
- 快捷键说明(选中代码后 只会执行选中部分)
|
- 快捷键说明(选中代码后 只会执行选中部分)
|
||||||
@@ -53,8 +67,27 @@
|
|||||||
- Ctrl + E 执行命令
|
- Ctrl + E 执行命令
|
||||||
- Ctrl + Q 切换代码页
|
- Ctrl + Q 切换代码页
|
||||||
|
|
||||||
|
## 插件源码
|
||||||
|
|
||||||
|
- [MiaoScript包管理中心](https://git.yumc.pw/circlecloud/ms/src/branch/master/packages/plugins/src/MiaoConsole.ts)
|
||||||
|
|
||||||
### RoadMap
|
### RoadMap
|
||||||
- 支持命令自动补全
|
- 支持 Java 类的自动补全
|
||||||
- 支持常用的开发脚本
|
- 支持命令自动补全(已完成)
|
||||||
- 支持快捷操作服务器数据
|
- 支持常用的开发脚本(开发中)
|
||||||
|
- 支持快捷操作服务器数据(开发中)
|
||||||
- 支持在线编辑服务器文件(开发了一半)
|
- 支持在线编辑服务器文件(开发了一半)
|
||||||
|
- 配置文件格式效验(开发中)
|
||||||
|
|
||||||
|
### Miao系列插件
|
||||||
|
|
||||||
|
- [[经济]MiaoReward —— 喵式奖励 让玩家看广告为服务器提供收入吧[1.7.10+全版本]](https://www.mcbbs.net/thread-1121423-1-1.html)
|
||||||
|
- [[编程]MiaoBlockly —— 喵式积木 用简单的积木来写插件吧[1.12.2+全版本]](https://www.mcbbs.net/thread-1129411-1-1.html)
|
||||||
|
- [[编程]MiaoConsole —— 喵式终端 通过MC端口直接控制服务器 调试插件[1.12.2+全版本]](https://www.mcbbs.net/thread-1129227-1-1.html)
|
||||||
|
- [[管理]MiaoBind —— 喵式绑定 兼容SoulBound的绑定插件 支持自定义关键词[1.7+全版本]](https://www.mcbbs.net/thread-922072-1-1.html)
|
||||||
|
- [[信息]MiaoBoard —— 喵式记分板 自定义动态记分板[1.7+全版本]](https://www.mcbbs.net/thread-631482-1-1.html)
|
||||||
|
- [[聊天]MiaoChat —— 喵式聊天 多功能自定义聊天格式 新增支持跨服[1.7.10+全版本]](https://www.mcbbs.net/thread-631240-1-1.html)
|
||||||
|
- [[菜单]MiaoMenu —— 喵式菜单 强大的自定义菜单 支持多种自定义操作[1.7+全版本]](https://www.mcbbs.net/thread-860047-1-1.html)
|
||||||
|
- [[管理]YUM —— 全能的服务器插件管理工具 全自动安装插件 更新插件[1.7.2+全版本]](https://www.mcbbs.net/thread-701333-1-1.html)
|
||||||
|
|
||||||
|
本插件所用所有代码均为原创,不存在借用/抄袭等行为
|
||||||
|
|||||||
24
packages/plugins/docs/MiaoPlugin.md
Normal file
24
packages/plugins/docs/MiaoPlugin.md
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
### Miao系列插件
|
||||||
|
|
||||||
|
- [[经济]MiaoReward —— 喵式奖励 让玩家看广告为服务器提供收入吧[1.7.10+全版本]](https://www.mcbbs.net/thread-1121423-1-1.html)
|
||||||
|
- [[编程]MiaoBlockly —— 喵式积木 用简单的积木来写插件吧[1.12.2+全版本]](https://www.mcbbs.net/thread-1129411-1-1.html)
|
||||||
|
- [[编程]MiaoConsole —— 喵式终端 通过MC端口直接控制服务器 调试插件[1.12.2+全版本]](https://www.mcbbs.net/thread-1129227-1-1.html)
|
||||||
|
- [[管理]MiaoBind —— 喵式绑定 兼容SoulBound的绑定插件 支持自定义关键词[1.7+全版本]](https://www.mcbbs.net/thread-922072-1-1.html)
|
||||||
|
- [[信息]MiaoBoard —— 喵式记分板 自定义动态记分板[1.7+全版本]](https://www.mcbbs.net/thread-631482-1-1.html)
|
||||||
|
- [[聊天]MiaoChat —— 喵式聊天 多功能自定义聊天格式 新增支持跨服[1.7.10+全版本]](https://www.mcbbs.net/thread-631240-1-1.html)
|
||||||
|
- [[菜单]MiaoMenu —— 喵式菜单 强大的自定义菜单 支持多种自定义操作[1.7+全版本]](https://www.mcbbs.net/thread-860047-1-1.html)
|
||||||
|
- [[管理]YUM —— 全能的服务器插件管理工具 全自动安装插件 更新插件[1.7.2+全版本]](https://www.mcbbs.net/thread-701333-1-1.html)
|
||||||
|
|
||||||
|
[size=20px][b]Miao系列插件[/b][/size]
|
||||||
|
|
||||||
|
[size=16px][list]
|
||||||
|
[*][url=https://www.mcbbs.net/thread-1121423-1-1.html][经济]MiaoReward —— 喵式奖励 让玩家看广告为服务器提供收入吧[1.7.10+全版本][/url]
|
||||||
|
[*][url=https://www.mcbbs.net/thread-1129411-1-1.html][编程]MiaoBlockly —— 喵式积木 用简单的积木来写插件吧[1.12.2+全版本][/url]
|
||||||
|
[*][url=https://www.mcbbs.net/thread-1129227-1-1.html][编程]MiaoConsole —— 喵式终端 通过MC端口直接控制服务器 调试插件[1.12.2+全版本][/url]
|
||||||
|
[*][url=https://www.mcbbs.net/thread-922072-1-1.html][管理]MiaoBind —— 喵式绑定 兼容SoulBound的绑定插件 支持自定义关键词[1.7+全版本][/url]
|
||||||
|
[*][url=https://www.mcbbs.net/thread-631482-1-1.html][信息]MiaoBoard —— 喵式记分板 自定义动态记分板[1.7+全版本][/url]
|
||||||
|
[*][url=https://www.mcbbs.net/thread-631240-1-1.html][聊天]MiaoChat —— 喵式聊天 多功能自定义聊天格式 新增支持跨服[1.7.10+全版本][/url]
|
||||||
|
[*][url=https://www.mcbbs.net/thread-860047-1-1.html][菜单]MiaoMenu —— 喵式菜单 强大的自定义菜单 支持多种自定义操作[1.7+全版本][/url]
|
||||||
|
[*][url=https://www.mcbbs.net/thread-701333-1-1.html][管理]YUM —— 全能的服务器插件管理工具 全自动安装插件 更新插件[1.7.2+全版本][/url][/list][/size]
|
||||||
|
|
||||||
|
[size=16px]本插件所用所有代码均为原创,不存在借用/抄袭等行为[/size]
|
||||||
@@ -6,7 +6,16 @@
|
|||||||
- 快来接入 喵式奖励
|
- 快来接入 喵式奖励
|
||||||
- 通过QQ小程序广告 增加服务器收入
|
- 通过QQ小程序广告 增加服务器收入
|
||||||
|
|
||||||
|
### 先来一张近期的服务器提现订单
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
## 插件展示
|
## 插件展示
|
||||||
|
|
||||||
|
> 多图预警 折叠了
|
||||||
|
|
||||||
|
`[spoiler]`
|
||||||
|
|
||||||
- 插件帮助
|
- 插件帮助
|
||||||
- 扫码绑定
|
- 扫码绑定
|
||||||
- 查看个人信息
|
- 查看个人信息
|
||||||
@@ -20,6 +29,9 @@
|
|||||||
- 玩家扫码兑换完成
|
- 玩家扫码兑换完成
|
||||||
- 腐竹扫码确认
|
- 腐竹扫码确认
|
||||||
- 腐竹扫码完成
|
- 腐竹扫码完成
|
||||||
|
|
||||||
|
`[/spoiler]`
|
||||||
|
|
||||||
## 插件命令
|
## 插件命令
|
||||||
```
|
```
|
||||||
>mrd
|
>mrd
|
||||||
@@ -38,6 +50,8 @@
|
|||||||
[17:56:54 INFO]: [MS][MRD] 比如 设置了0.001 那就是 玩家至少 1000喵币 才能兑换!
|
[17:56:54 INFO]: [MS][MRD] 比如 设置了0.001 那就是 玩家至少 1000喵币 才能兑换!
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 接下来就是赚钱的操作
|
||||||
|
|
||||||
## 插件安装/配置
|
## 插件安装/配置
|
||||||
|
|
||||||
### 基础准备工作
|
### 基础准备工作
|
||||||
@@ -46,23 +60,25 @@
|
|||||||
- 个人中心 => 配置面板 => 圈云盒子客服群
|
- 个人中心 => 配置面板 => 圈云盒子客服群
|
||||||
- 打开群详情 加群
|
- 打开群详情 加群
|
||||||
|
|
||||||
### 接下来就是赚钱的操作
|
### 申请账号
|
||||||
|
- 打开 [圈云盒子管理后台](https://reward.yumc.pw)
|
||||||
|
- 扫码登录 并且加入客服群
|
||||||
|
- 创建一个服务器 等待管理员审核通过
|
||||||
|
|
||||||
|
`[hide]`
|
||||||
|
|
||||||
### 服务器准备工作
|
### 服务器准备工作
|
||||||
- 打开 [圈云盒子管理后台](https://reward.yumc.pw)
|
- 安装 `MiaoScript` [站内地址](https://www.mcbbs.net/thread-774401-1-1.html)
|
||||||
- 先安装 `MiaoScript` [站内地址](https://www.mcbbs.net/thread-774401-1-1.html)
|
- 如果你已经安装了 Yum 可以通过 Yum 快速安装 `/yum install MiaoScript`
|
||||||
- 可以通过 Yum 快速安装 `/yum install MiaoScript`
|
|
||||||
- 等待 MiaoScript 引擎启动完成(首次启动可能需要10-20秒 依赖于您的网络环境)
|
- 等待 MiaoScript 引擎启动完成(首次启动可能需要10-20秒 依赖于您的网络环境)
|
||||||
- 执行 `/mspm install MiaoReward`
|
- 执行 `/mspm install MiaoReward` 安装 MiaoReward 脚本插件
|
||||||
|
- 完成安装
|
||||||
|
|
||||||
### 绑定服务器
|
### 绑定服务器
|
||||||
- 由于当前框架存在BUG 请先执行 `/mspm reload MiaoReward` 生成配置文件
|
|
||||||
- 执行 `/mrd bind server`
|
- 执行 `/mrd bind server`
|
||||||
- 使用QQ扫码
|
- 使用QQ扫码 => 选择需要绑定的服务器 => 完成绑定
|
||||||
- 选择需要绑定的服务器
|
|
||||||
- 完成绑定
|
|
||||||
- 配置服务器兑换比例
|
- 配置服务器兑换比例
|
||||||
- 执行 `/mrd ratio 0.001` (最低为 1:0.0001)
|
- 执行 `/mrd ratio <兑换比例>` (最低为 1:0.0001)
|
||||||
- 执行兑换比例确认指令
|
- 执行兑换比例确认指令
|
||||||
- 执行 `/mrd server` 查看服务器信息
|
- 执行 `/mrd server` 查看服务器信息
|
||||||
- 如果群组服需要绑定多台服务器(前提是每个服务器都有玩家在)
|
- 如果群组服需要绑定多台服务器(前提是每个服务器都有玩家在)
|
||||||
@@ -118,12 +134,18 @@ prefix: '§6[§b广告系统§6]§r'
|
|||||||
|
|
||||||
## 插件源码
|
## 插件源码
|
||||||
|
|
||||||
- [MiaoScript包管理中心](http://ms.yumc.pw/api/plugin/download/name/MiaoReward)
|
- [MiaoScript包管理中心](https://git.yumc.pw/circlecloud/ms/src/branch/master/packages/plugins/src/MiaoReward.ts)
|
||||||
|
|
||||||
|
`[/hide]`
|
||||||
|
|
||||||
|
## 更新日志
|
||||||
|
- 2020-10-12 完成提现功能
|
||||||
|
- 2020-10-06 使用发包的方式展示地图
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
- 绑定服务器(已完成)
|
- 绑定服务器(已完成)
|
||||||
- 绑定玩家(已完成)
|
- 绑定玩家(已完成)
|
||||||
- 兑换喵币(已完成)
|
- 兑换喵币(已完成)
|
||||||
- 自助开通服务器(开发中)
|
- [自助开通](https://reward.yumc.pw)服务器(已完成)
|
||||||
- 自助兑换RMB(开发中)
|
- [自助兑换](https://reward.yumc.pw)RMB(已完成)
|
||||||
- 自助提现(开发中)
|
- [自助提现](https://reward.yumc.pw)(已完成)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "@ccms/plugins",
|
"name": "@ccms/plugins",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript plugins package",
|
"description": "MiaoScript plugins package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -20,16 +20,19 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@javatypes/bukkit-api": "^0.0.3",
|
||||||
|
"@javatypes/bungee-api": "^0.0.3",
|
||||||
|
"@javatypes/sponge-api": "^0.0.3",
|
||||||
"@javatypes/spring-data-redis": "^0.0.3",
|
"@javatypes/spring-data-redis": "^0.0.3",
|
||||||
"@javatypes/spring-web": "^0.0.3",
|
"@javatypes/spring-web": "^0.0.3",
|
||||||
"@javatypes/tomcat": "^0.0.3",
|
"@javatypes/tomcat": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8",
|
"@ccms/container": "^0.10.1",
|
||||||
"@ccms/plugin": "^0.9.8"
|
"@ccms/plugin": "^0.10.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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" />
|
/// <reference types="@ccms/nashorn" />
|
||||||
|
|
||||||
import { plugin as pluginApi, server, task, constants, command } from '@ccms/api'
|
import { plugin as pluginApi, server, task, constants, command } from '@ccms/api'
|
||||||
import { plugin, interfaces, cmd, tab, enable, config, disable } from '@ccms/plugin'
|
import { plugin, interfaces, cmd, tab, enable, config, disable, PluginConfig } from '@ccms/plugin'
|
||||||
import { inject, ContainerInstance, Container } from '@ccms/container'
|
import { ContainerInstance, Container, Autowired } from '@ccms/container'
|
||||||
import io, { Server as SocketIOServer, Socket as SocketIOSocket } from '@ccms/websocket'
|
import io, { Server as SocketIOServer, Socket as SocketIOSocket } from '@ccms/websocket'
|
||||||
import * as fs from '@ccms/common/dist/fs'
|
import * as fs from '@ccms/common/dist/fs'
|
||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
@@ -19,22 +19,22 @@ let help = [
|
|||||||
'§6/mconsole §areload §6- §3重载插件',
|
'§6/mconsole §areload §6- §3重载插件',
|
||||||
]
|
]
|
||||||
|
|
||||||
@plugin({ name: 'MiaoConsole', prefix: 'Console', version: '1.0.0', author: 'MiaoWoo', servers: ['!nukkit'], source: __filename })
|
@plugin({ prefix: 'Console', version: '1.0.0', author: 'MiaoWoo', servers: ['!nukkit'], source: __filename })
|
||||||
export class MiaoConsole extends interfaces.Plugin {
|
export class MiaoConsole extends interfaces.Plugin {
|
||||||
@inject(ContainerInstance)
|
@Autowired(ContainerInstance)
|
||||||
private container: Container
|
private container: Container
|
||||||
@inject(server.ServerType)
|
@Autowired(server.ServerType)
|
||||||
private serverType: string
|
private serverType: string
|
||||||
@inject(server.Server)
|
@Autowired(pluginApi.PluginFolder)
|
||||||
private server: server.Server
|
|
||||||
@inject(command.Command)
|
|
||||||
private command: command.Command
|
|
||||||
@inject(task.TaskManager)
|
|
||||||
private task: task.TaskManager
|
|
||||||
@inject(pluginApi.PluginManager)
|
|
||||||
private pluginManager: pluginApi.PluginManager
|
|
||||||
@inject(pluginApi.PluginFolder)
|
|
||||||
private pluginFolder: string
|
private pluginFolder: string
|
||||||
|
@Autowired()
|
||||||
|
private server: server.Server
|
||||||
|
@Autowired()
|
||||||
|
private command: command.Command
|
||||||
|
@Autowired()
|
||||||
|
private task: task.TaskManager
|
||||||
|
@Autowired()
|
||||||
|
private pluginManager: pluginApi.PluginManager
|
||||||
|
|
||||||
private token: string
|
private token: string
|
||||||
private instance: any
|
private instance: any
|
||||||
@@ -46,7 +46,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
private logCache: string[] = []
|
private logCache: string[] = []
|
||||||
|
|
||||||
@config()
|
@config()
|
||||||
private secret = { token: undefined }
|
private secret: PluginConfig = { token: undefined }
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
if (this.secret.token) {
|
if (this.secret.token) {
|
||||||
@@ -90,6 +90,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
cmdtoken(sender: any, sub: string, token: string) {
|
cmdtoken(sender: any, sub: string, token: string) {
|
||||||
if (sub == "set") {
|
if (sub == "set") {
|
||||||
this.secret.token = this.token = token
|
this.secret.token = this.token = token
|
||||||
|
this.secret.save()
|
||||||
this.logger.sender(sender, '§a已保存§6服务器登录Token:§3', this.token, '§4请勿分享给其他人 防止服务器被攻击!')
|
this.logger.sender(sender, '§a已保存§6服务器登录Token:§3', this.token, '§4请勿分享给其他人 防止服务器被攻击!')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -185,8 +186,8 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
@disable({ servers: [constants.ServerType.Bukkit, constants.ServerType.Sponge] })
|
@disable({ servers: [constants.ServerType.Bukkit, constants.ServerType.Sponge] })
|
||||||
removeLog4jForward() {
|
removeLog4jForward() {
|
||||||
try {
|
try {
|
||||||
this.appender.stop()
|
this.appender?.stop()
|
||||||
this.rootLogger.removeAppender(this.appender)
|
this.rootLogger?.removeAppender(this.appender)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
}
|
}
|
||||||
@@ -195,7 +196,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
@disable({ servers: [constants.ServerType.Bungee] })
|
@disable({ servers: [constants.ServerType.Bungee] })
|
||||||
removeLoggerForward() {
|
removeLoggerForward() {
|
||||||
try {
|
try {
|
||||||
this.rootLogger.removeHandler(this.handler)
|
this.rootLogger?.removeHandler(this.handler)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
}
|
}
|
||||||
@@ -204,7 +205,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
@disable({ servers: [constants.ServerType.Spring] })
|
@disable({ servers: [constants.ServerType.Spring] })
|
||||||
removeLogbackForward() {
|
removeLogbackForward() {
|
||||||
try {
|
try {
|
||||||
this.rootLogger.detachAppender(this.LOGBACK_APPENDER_NAME)
|
this.rootLogger?.detachAppender(this.LOGBACK_APPENDER_NAME)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
}
|
}
|
||||||
@@ -216,6 +217,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
root: fs.concat(root, 'wwwroot')
|
root: fs.concat(root, 'wwwroot')
|
||||||
})
|
})
|
||||||
this.container.bind(io.Instance).toConstantValue(this.socketIOServer)
|
this.container.bind(io.Instance).toConstantValue(this.socketIOServer)
|
||||||
|
process.emit('websocket.create', this.socketIOServer)
|
||||||
}
|
}
|
||||||
|
|
||||||
startSocketIOServer() {
|
startSocketIOServer() {
|
||||||
@@ -224,20 +226,19 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
namespace.on('connect', (client: SocketIOSocket) => {
|
namespace.on('connect', (client: SocketIOSocket) => {
|
||||||
if (!this.token) {
|
if (!this.token) {
|
||||||
this.logger.console(`§6客户端 §b${client.id} §a请求连接 §4服务器尚未设置 Token 无法连接!`)
|
this.logger.console(`§6客户端 §b${client.id} §a请求连接 §4服务器尚未设置 Token 无法连接!`)
|
||||||
client.emit('unauthorized')
|
client.emit('unauthorized', () => client.disconnect(true))
|
||||||
client.disconnect(true)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (this.token != client.handshake.query.token) {
|
if (this.token != client.handshake.query.token) {
|
||||||
this.logger.console(`§6客户端 §b${client.id} §c无效请求 §4请提供正确Token后再次连接!`)
|
this.logger.console(`§6客户端 §b${client.id} §c无效请求 §4请提供正确Token后再次连接!`)
|
||||||
client.emit('unauthorized')
|
client.emit('unauthorized', () => client.disconnect(true))
|
||||||
client.disconnect(true)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
this.initWebSocketClient(client)
|
this.initWebSocketClient(client)
|
||||||
this.logCache.forEach(msg => client.emit('log', msg))
|
this.logCache.forEach(msg => client.emit('log', msg))
|
||||||
this.logger.console(`§6客户端 §b${client.id} §a新建连接 ${this.rootLogger ? '启动日志转发' : '§4转发日志启动失败'}...`)
|
this.logger.console(`§6客户端 §b${client.id} §a新建连接 ${this.rootLogger ? '启动日志转发' : '§4转发日志启动失败'}...`)
|
||||||
})
|
})
|
||||||
|
process.emit('websocket.start', this.socketIOServer)
|
||||||
}
|
}
|
||||||
|
|
||||||
private initWebSocketClient(client: SocketIOSocket) {
|
private initWebSocketClient(client: SocketIOSocket) {
|
||||||
@@ -280,7 +281,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
|||||||
if (!dir.isDirectory()) {
|
if (!dir.isDirectory()) {
|
||||||
return fn(undefined, `${file} 不是一个目录!`)
|
return fn(undefined, `${file} 不是一个目录!`)
|
||||||
}
|
}
|
||||||
fn(fs.list(dir))
|
fn(fs.list(dir).map(f => f.name))
|
||||||
})
|
})
|
||||||
client.on('error', (error) => {
|
client.on('error', (error) => {
|
||||||
this.logger.console(`§6客户端 §b${client.id} §c触发异常: ${error}`)
|
this.logger.console(`§6客户端 §b${client.id} §c触发异常: ${error}`)
|
||||||
|
|||||||
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']
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,31 @@
|
|||||||
import { task, server, constants } from "@ccms/api";
|
import { task, server, constants } from "@ccms/api"
|
||||||
import { inject } from "@ccms/container";
|
import { Autowired, JSClass } from "@ccms/container"
|
||||||
import { plugin, interfaces, cmd } from "@ccms/plugin";
|
import { plugin, interfaces } from "@ccms/plugin"
|
||||||
|
|
||||||
import http from '@ccms/common/dist/http'
|
let createPacketAdapterFunction = eval(`
|
||||||
import * as fs from '@ccms/common/dist/fs'
|
function(cls, plugin, type, onPacketSending){
|
||||||
|
return new cls(plugin, type) {
|
||||||
|
onPacketSending: onPacketSending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
|
||||||
@plugin({ name: 'MiaoProtocol', prefix: 'MPTL', version: '1.0.0', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
@plugin({ prefix: 'MPTL', version: '1.0.0', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||||
export class MiaoProtocol extends interfaces.Plugin {
|
export class MiaoProtocol extends interfaces.Plugin {
|
||||||
@inject(server.Server)
|
@Autowired()
|
||||||
private server: server.Server;
|
private server: server.Server
|
||||||
@inject(task.TaskManager)
|
@Autowired()
|
||||||
private taskManager: task.TaskManager;
|
private taskManager: task.TaskManager
|
||||||
|
|
||||||
|
@JSClass('com.comphenix.protocol.events.PacketAdapter')
|
||||||
|
private PacketAdapter
|
||||||
|
@JSClass('com.comphenix.protocol.PacketType')
|
||||||
|
private PacketType
|
||||||
|
@JSClass('com.comphenix.protocol.ProtocolLibrary')
|
||||||
|
private ProtocolLibrary
|
||||||
|
|
||||||
private pipeline: any
|
private pipeline: any
|
||||||
|
private adapter: any
|
||||||
|
|
||||||
enable() {
|
enable() {
|
||||||
let count = 0
|
let count = 0
|
||||||
@@ -25,6 +38,29 @@ export class MiaoProtocol extends interfaces.Plugin {
|
|||||||
this.logger.console('§cNetty通道注入失败 §4所有功能将无法使用!')
|
this.logger.console('§cNetty通道注入失败 §4所有功能将无法使用!')
|
||||||
}
|
}
|
||||||
}).later(20).timer(40).submit()
|
}).later(20).timer(40).submit()
|
||||||
|
this.initPacketAdapter()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
disable() {
|
||||||
|
this.ProtocolLibrary.getProtocolManager().removePacketListener(this.adapter)
|
||||||
|
}
|
||||||
|
|
||||||
|
createPacketAdapter(onPacketSending: (event) => void) {
|
||||||
|
return createPacketAdapterFunction(this.PacketAdapter, base.getInstance(), [this.PacketType.Play.Server.MAP], onPacketSending)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)}
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,48 +6,9 @@ import { QRCode, QRErrorCorrectLevel } from '@ccms/common/dist/qrcode'
|
|||||||
import { Autowired, JSClass, optional } from '@ccms/container'
|
import { Autowired, JSClass, optional } from '@ccms/container'
|
||||||
import http from '@ccms/common/dist/http'
|
import http from '@ccms/common/dist/http'
|
||||||
|
|
||||||
let MapView
|
|
||||||
let Bukkit
|
|
||||||
let MapRenderer
|
|
||||||
let ItemStack
|
|
||||||
let Material
|
|
||||||
|
|
||||||
try {
|
|
||||||
MapView = Java.type('org.bukkit.map.MapView')
|
|
||||||
Bukkit = Java.type('org.bukkit.Bukkit')
|
|
||||||
MapRenderer = Java.type('org.bukkit.map.MapRenderer')
|
|
||||||
ItemStack = Java.type('org.bukkit.inventory.ItemStack')
|
|
||||||
Material = Java.type('org.bukkit.Material')
|
|
||||||
} catch (error) {
|
|
||||||
}
|
|
||||||
|
|
||||||
const BufferedImage = Java.type('java.awt.image.BufferedImage')
|
const BufferedImage = Java.type('java.awt.image.BufferedImage')
|
||||||
const Color = Java.type('java.awt.Color')
|
const Color = Java.type('java.awt.Color')
|
||||||
|
const Bytes = Java.type('byte[]')
|
||||||
class QRCodeRender {
|
|
||||||
private _proxy
|
|
||||||
private image
|
|
||||||
private rendered = false
|
|
||||||
constructor() {
|
|
||||||
const MapRendererAdapter = Java.extend(MapRenderer, {
|
|
||||||
render: (_mapView, mapCanvas, _player) => {
|
|
||||||
if (this.rendered) return
|
|
||||||
if (this.image) {
|
|
||||||
mapCanvas.drawImage(0, 0, this.image)
|
|
||||||
}
|
|
||||||
this.rendered = true
|
|
||||||
}
|
|
||||||
})
|
|
||||||
this._proxy = new MapRendererAdapter()
|
|
||||||
}
|
|
||||||
setImage(image) {
|
|
||||||
this.image = image
|
|
||||||
this.rendered = false
|
|
||||||
}
|
|
||||||
getHandler() {
|
|
||||||
return this._proxy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PlaceholderAPI {
|
interface PlaceholderAPI {
|
||||||
registerPlaceholderHook: (key: string, onPlaceholderRequest: (player, s) => string) => void
|
registerPlaceholderHook: (key: string, onPlaceholderRequest: (player, s) => string) => void
|
||||||
@@ -62,18 +23,20 @@ interface UserInfo {
|
|||||||
box: string
|
box: string
|
||||||
}
|
}
|
||||||
|
|
||||||
@JSPlugin({ prefix: 'MRD', version: '1.3.3', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
let createPacketAdapterFunction = eval(`
|
||||||
|
function(cls, plugin, type, onPacketSending){
|
||||||
|
return new cls(plugin, type) {
|
||||||
|
onPacketSending: onPacketSending
|
||||||
|
}
|
||||||
|
}`)
|
||||||
|
|
||||||
|
@JSPlugin({ prefix: 'MRD', version: '1.4.2', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||||
export class MiaoReward extends interfaces.Plugin {
|
export class MiaoReward extends interfaces.Plugin {
|
||||||
private serverInfo: any
|
private serverInfo: any
|
||||||
private cacheBindUuid = ''
|
private cacheBindUuid = ''
|
||||||
private zeroMapView = undefined
|
private zeroMapView = undefined
|
||||||
private zeroMapRender: QRCodeRender = undefined
|
private playerImageCache = new Map<string, any>()
|
||||||
private isBinding = false
|
private playerTaskCache = new Map<string, task.Cancelable>()
|
||||||
private bindingUser = 'unknow'
|
|
||||||
private bindingTask = undefined
|
|
||||||
private bindingLeftTime = 45
|
|
||||||
private bindingNotify = new java.util.HashSet<org.bukkit.entity.Player>()
|
|
||||||
private drawCooldown = new Map<string, number>()
|
|
||||||
private playerInfoCache = new Map<string, UserInfo>()
|
private playerInfoCache = new Map<string, UserInfo>()
|
||||||
|
|
||||||
private downgrade = false
|
private downgrade = false
|
||||||
@@ -90,34 +53,55 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
private bungee: proxy.BungeeCord
|
private bungee: proxy.BungeeCord
|
||||||
|
|
||||||
@Config()
|
@Config()
|
||||||
private config: PluginConfig = {
|
private config: PluginConfig & {
|
||||||
prefix: '§6[§b广告系统§6]§r',
|
prefix: string
|
||||||
serverId: '',
|
serverId: string
|
||||||
serverToken: '',
|
serverToken: string
|
||||||
drawCommand: 'p give %player_name% %amount%',
|
drawCommand: string
|
||||||
drawCooldown: 300
|
coinName: string
|
||||||
}
|
} = {
|
||||||
|
prefix: '§6[§b广告系统§6]§r',
|
||||||
|
serverId: '',
|
||||||
|
serverToken: '',
|
||||||
|
drawCommand: 'p give %player_name% %amount%',
|
||||||
|
coinName: '点券'
|
||||||
|
}
|
||||||
|
|
||||||
|
@JSClass('org.bukkit.Bukkit')
|
||||||
|
private Bukkit: any
|
||||||
|
|
||||||
@JSClass('me.clip.placeholderapi.PlaceholderAPI')
|
@JSClass('me.clip.placeholderapi.PlaceholderAPI')
|
||||||
private PlaceholderAPI: PlaceholderAPI
|
private PlaceholderAPI: PlaceholderAPI
|
||||||
@JSClass('me.clip.placeholderapi.PlaceholderHook')
|
@JSClass('me.clip.placeholderapi.PlaceholderHook')
|
||||||
private PlaceholderHook: any
|
private PlaceholderHook: any
|
||||||
|
|
||||||
|
@JSClass('com.comphenix.protocol.ProtocolLibrary')
|
||||||
|
private ProtocolLibrary: any
|
||||||
|
@JSClass('com.comphenix.protocol.PacketType')
|
||||||
|
private PacketType: any
|
||||||
|
@JSClass('com.comphenix.protocol.events.PacketAdapter')
|
||||||
|
private PacketAdapter: any
|
||||||
|
|
||||||
|
private adapter: any
|
||||||
|
private itemStackArrayLength: number
|
||||||
|
|
||||||
private isBungeeCord = undefined
|
private isBungeeCord = undefined
|
||||||
private channelOff: { off: () => void }
|
private channelOff: { off: () => void }
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
this.config.prefix = this.config.prefix || '§6[§b广告系统§6]§r'
|
this.config.prefix = this.config.prefix || '§6[§b广告系统§6]§r'
|
||||||
this.config.drawCommand = this.config.drawCommand || 'p give %player_name% %amount%'
|
this.config.drawCommand = this.config.drawCommand || 'p give %player_name% %amount%'
|
||||||
this.config.drawCooldown = this.config.drawCooldown || 300
|
if (!this.config.coinName) {
|
||||||
|
this.config.coinName = '点券'
|
||||||
|
this.config.save()
|
||||||
|
}
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
this.logger.prefix = this.config.prefix
|
this.logger.prefix = this.config.prefix
|
||||||
this.downgrade = Bukkit.getServer().class.name.split('.')[3] == "v1_7_R4"
|
this.downgrade = this.Bukkit.server.class.name.split('.')[3] == "v1_7_R4"
|
||||||
this.updateServerInfo()
|
this.updateServerInfo(null, () => this.updateOnlinePlayersInfo())
|
||||||
this.updateOnlinePlayersInfo()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateServerInfo(player?: any) {
|
private updateServerInfo(player?: any, cb?: () => void) {
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
if (this.config.serverId) {
|
if (this.config.serverId) {
|
||||||
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
||||||
@@ -127,6 +111,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
if (result.code == 200) {
|
if (result.code == 200) {
|
||||||
this.serverInfo = result.data
|
this.serverInfo = result.data
|
||||||
if (player) this.bungee.for(player).forward("ALL", "MiaoReward", { type: "updateServerInfo", data: result.data }).send()
|
if (player) this.bungee.for(player).forward("ALL", "MiaoReward", { type: "updateServerInfo", data: result.data }).send()
|
||||||
|
cb?.()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).async().submit()
|
}).async().submit()
|
||||||
@@ -203,16 +188,67 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
|
|
||||||
private initZeroMap() {
|
private initZeroMap() {
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
this.zeroMapRender = new QRCodeRender()
|
this.zeroMapView = this.Bukkit.getMap(0) || this.Bukkit.createMap(this.Bukkit.getWorlds()[0])
|
||||||
this.zeroMapView = Bukkit.getMap(0) || Bukkit.createMap(Bukkit.getWorlds()[0])
|
this.zeroMapView.setScale(org.bukkit.map.MapView.Scale.FARTHEST)
|
||||||
this.zeroMapView.setScale(MapView.Scale.FARTHEST)
|
this.zeroMapView.getRenderers().clear()
|
||||||
this.zeroMapView.getRenderers().forEach(r => this.zeroMapView.removeRenderer(r))
|
|
||||||
this.zeroMapView.addRenderer(this.zeroMapRender.getHandler())
|
|
||||||
}).submit()
|
}).submit()
|
||||||
|
var minecraftVersion = this.ProtocolLibrary.getProtocolManager().getMinecraftVersion()
|
||||||
|
this.itemStackArrayLength = minecraftVersion.getMinor() < 9 ? 45 : 46
|
||||||
|
this.initPacketAdapter()
|
||||||
|
}
|
||||||
|
|
||||||
|
createPacketAdapter(onPacketSending: (event) => void) {
|
||||||
|
return createPacketAdapterFunction(this.PacketAdapter, base.getInstance(), [this.PacketType.Play.Server.MAP], onPacketSending)
|
||||||
|
}
|
||||||
|
|
||||||
|
initPacketAdapter() {
|
||||||
|
this.adapter = this.createPacketAdapter((event) => {
|
||||||
|
let integers = event.getPacket().getIntegers().getValues()
|
||||||
|
let mapId = integers.get(0)
|
||||||
|
let player = event.getPlayer()
|
||||||
|
if (mapId == this.zeroMapView.getId() && this.playerImageCache.has(player.getName())) {
|
||||||
|
let bytes = this.playerImageCache.get(player.getName())
|
||||||
|
if (!this.downgrade) {
|
||||||
|
event.getPacket().getByteArrays().write(0, bytes)
|
||||||
|
event.getPacket().getIntegers().write(3, 128)
|
||||||
|
event.getPacket().getIntegers().write(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)
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendWindowItems(player: org.bukkit.entity.Player, mapItem: any) {
|
||||||
|
var protocolManager = this.ProtocolLibrary.getProtocolManager()
|
||||||
|
try {
|
||||||
|
let ItemStackArray = Java.type('org.bukkit.inventory.ItemStack[]')
|
||||||
|
let arritemStack = new ItemStackArray(this.itemStackArrayLength)
|
||||||
|
java.util.Arrays.fill(arritemStack, new org.bukkit.inventory.ItemStack(org.bukkit.Material.AIR))
|
||||||
|
arritemStack[36 + player.getInventory().getHeldItemSlot()] = mapItem
|
||||||
|
var packetContainer = protocolManager.createPacket(this.PacketType.Play.Server.WINDOW_ITEMS)
|
||||||
|
if (packetContainer.getItemArrayModifier().size() > 0) {
|
||||||
|
packetContainer.getItemArrayModifier().write(0, arritemStack)
|
||||||
|
} else {
|
||||||
|
packetContainer.getItemListModifier().write(0, java.util.Arrays.asList(arritemStack))
|
||||||
|
}
|
||||||
|
protocolManager.sendServerPacket(player, packetContainer)
|
||||||
|
} catch (ex) {
|
||||||
|
console.ex(ex)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
disable() {
|
disable() {
|
||||||
this.PlaceholderAPI.unregisterPlaceholderHook("mrd")
|
this.PlaceholderAPI?.unregisterPlaceholderHook("mrd")
|
||||||
|
this.adapter && this.ProtocolLibrary.getProtocolManager().removePacketListener(this.adapter)
|
||||||
Java.from(this.server.getOnlinePlayers()).forEach(p => this.checkAndClear(p))
|
Java.from(this.server.getOnlinePlayers()).forEach(p => this.checkAndClear(p))
|
||||||
this.channelOff?.off()
|
this.channelOff?.off()
|
||||||
}
|
}
|
||||||
@@ -276,42 +312,28 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private bindCheck(sender: org.bukkit.entity.Player, cooldown: number) {
|
private bindCheck(sender: org.bukkit.entity.Player) {
|
||||||
if (this.isBinding) {
|
let scanning = this.playerTaskCache.has(sender.getName())
|
||||||
let bindUser = Bukkit.getPlayerExact(this.bindingUser)
|
if (scanning) {
|
||||||
if (bindUser && bindUser.isOnline() && this.isHoldQrCodeItem(bindUser)) {
|
this.logger.sender(sender, "§4当前正在进行扫码 请稍候重试!")
|
||||||
this.bindingNotify.add(sender)
|
|
||||||
this.logger.sender(sender, [
|
|
||||||
"§c当前 §a" + this.bindingUser + " §c玩家正在扫码",
|
|
||||||
"§6请等待 §e" + this.bindingLeftTime + "秒 §6后重试...",
|
|
||||||
"§a玩家操作完成后将会通知您继续操作..."
|
|
||||||
])
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (this.drawCooldown.has(sender.getName()) && !sender.hasPermission('mrd.admin')) {
|
return scanning
|
||||||
let leftTime = cooldown - (Date.now() - this.drawCooldown.get(sender.getName())) / 1000
|
}
|
||||||
if (leftTime > 0) {
|
|
||||||
this.logger.sender(sender, `§c扫码功能冷却中 剩余 ${leftTime} 秒!`)
|
cmdopen(sender: org.bukkit.entity.Player) {
|
||||||
return true
|
if (this.bindCheck(sender)) return
|
||||||
}
|
this.logger.sender(sender, '§a正在获取小程序二维码...')
|
||||||
}
|
let sync = { scaned: false }
|
||||||
this.drawCooldown.set(sender.getName(), Date.now())
|
this.setItemAndTp(sender, 'https://m.q.qq.com/a/p/1110360279?s=' + encodeURIComponent(`pages/my/index`), sync)
|
||||||
this.isBinding = true
|
this.taskManager.create(() => sync.scaned = true).later(20 * 50).submit()
|
||||||
this.bindingUser = sender.getName()
|
|
||||||
this.bindingNotify.clear()
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdbind(sender: org.bukkit.entity.Player, server: boolean) {
|
cmdbind(sender: org.bukkit.entity.Player, server: boolean) {
|
||||||
if (this.bindCheck(sender, 60)) return
|
|
||||||
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
||||||
if (sender.getItemInHand()?.getType() !== Material.AIR) { return this.logger.sender(sender, "§c请空手执行此命令!") }
|
if (this.bindCheck(sender)) return
|
||||||
if (server) {
|
if (server) {
|
||||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4您没有配置服务器的权限!') }
|
|
||||||
this.bindServer(sender)
|
this.bindServer(sender)
|
||||||
} else {
|
} else {
|
||||||
if (!this.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
|
||||||
this.bindUser(sender)
|
this.bindUser(sender)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -326,7 +348,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
if (amount % 100 !== 0) {
|
if (amount % 100 !== 0) {
|
||||||
return this.logger.sender(sender, '§4金额必须是100倍数!')
|
return this.logger.sender(sender, '§4金额必须是100倍数!')
|
||||||
}
|
}
|
||||||
if (this.bindCheck(sender, this.config.drawCooldown)) { return }
|
if (this.bindCheck(sender)) { return }
|
||||||
this.scanAuth(sender,
|
this.scanAuth(sender,
|
||||||
'draw', {
|
'draw', {
|
||||||
title: '兑换授权',
|
title: '兑换授权',
|
||||||
@@ -363,11 +385,11 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
let command = this.config.drawCommand.replace('%player_name%', sender.getName()).replace('%amount%', draw.data)
|
let command = this.config.drawCommand.replace('%player_name%', sender.getName()).replace('%amount%', draw.data)
|
||||||
if (!this.server.dispatchConsoleCommand(command)) {
|
if (!this.server.dispatchConsoleCommand(command)) {
|
||||||
return this.sendError(sender, ...draw.msg.split('\n'), `§6执行结果: §4已扣除 §c${amount} §4喵币`, `§6执行命令: §3/${command} §c可能存在异常`)
|
return this.sendError(sender, ...draw.msg.split('\n').map(s => s.replace('点券', this.config.coinName)), `§6执行结果: §4已扣除 §c${amount} §4喵币`, `§6执行命令: §3/${command} §c可能存在异常`)
|
||||||
}
|
}
|
||||||
this.logger.sender(sender, draw.msg.split('\n'))
|
this.logger.sender(sender, draw.msg.split('\n').map(s => s.replace('点券', this.config.coinName)))
|
||||||
this.sendBroadcast(sender, `${this.config.prefix}§6玩家 §b${sender.getName()} §6成功将 §a${amount}喵币 §6兑换成 §c${draw.data}点券!`)
|
this.sendBroadcast(sender, `${this.config.prefix}§6玩家 §b${sender.getName()} §6成功将 §a${amount}喵币 §6兑换成 §c${draw.data}${this.config.coinName}!`)
|
||||||
this.sendBroadcast(sender, `${this.config.prefix}§c/mrd help §b查看广告系统帮助 §6快来一起看广告赚点券吧!`)
|
this.sendBroadcast(sender, `${this.config.prefix}§c/mrd help §b查看广告系统帮助 §6快来一起看广告赚${this.config.coinName}吧!`)
|
||||||
}).submit()
|
}).submit()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -429,14 +451,13 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
let [ratio, mbr, msg] = this.ratio2string(ratioStr)
|
let [ratio, mbr, msg] = this.ratio2string(ratioStr)
|
||||||
if (!confirm) {
|
if (!confirm) {
|
||||||
return this.logger.sender(sender, [
|
return this.logger.sender(sender, [
|
||||||
'§4警告: 您正在设置服务器喵币/点券兑换比例 设置后将实时生效!',
|
`§4警告: 您正在设置服务器喵币/${this.config.coinName}兑换比例 设置后将实时生效!`,
|
||||||
`§6您设置的兑换比例为 ` + msg,
|
`§6您设置的兑换比例为 ` + msg,
|
||||||
`§6玩家至少需要 §a${mbr}喵币 §6才可以兑换点券!`,
|
`§6玩家至少需要 §a${mbr}喵币 §6才可以兑换${this.config.coinName}!`,
|
||||||
`§6请执行 §b/mrd ratio §c${ratio} §econfirm §c确认修改!`
|
`§6请执行 §b/mrd ratio §c${ratio} §econfirm §c确认修改!`
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
if (confirm != 'confirm') return this.logger.sender(sender, `§6请执行 §b/mrd ratio §c${ratio} §econfirm §c确认修改!`)
|
if (confirm != 'confirm') return this.logger.sender(sender, `§6请执行 §b/mrd ratio §c${ratio} §econfirm §c确认修改!`)
|
||||||
if (this.bindCheck(sender, 60)) return
|
|
||||||
this.scanAuth(sender, "ratio", {
|
this.scanAuth(sender, "ratio", {
|
||||||
title: `是否授权 ${this.serverInfo.name} 调整兑换比例`,
|
title: `是否授权 ${this.serverInfo.name} 调整兑换比例`,
|
||||||
content: [
|
content: [
|
||||||
@@ -470,10 +491,10 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
private ratio2string(ratio) {
|
private ratio2string(ratio) {
|
||||||
ratio = parseFloat(ratio)
|
ratio = parseFloat(ratio)
|
||||||
if (ratio > 1) {
|
if (ratio > 1) {
|
||||||
return [ratio, 1, `§c${ratio} §6就是 §a1喵币 §6=> §c${ratio}点券!`]
|
return [ratio, 1, `§c${ratio} §6就是 §a1喵币 §6=> §c${ratio}${this.config.coinName}!`]
|
||||||
}
|
}
|
||||||
let mbr = Math.round(1 / ratio * 10000) / 10000
|
let mbr = Math.round(1 / ratio * 10000) / 10000
|
||||||
return [ratio, mbr, `§c${ratio} §6就是 §a${mbr}喵币 §6=> §c1点券!`]
|
return [ratio, mbr, `§c${ratio} §6就是 §a${mbr}喵币 §6=> §c1${this.config.coinName}!`]
|
||||||
}
|
}
|
||||||
|
|
||||||
private sendBroadcast(player, message) {
|
private sendBroadcast(player, message) {
|
||||||
@@ -482,6 +503,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private bindServer(sender: org.bukkit.entity.Player) {
|
private bindServer(sender: org.bukkit.entity.Player) {
|
||||||
|
if (!sender.isOp()) { return this.logger.sender(sender, '§4您没有配置服务器的权限!') }
|
||||||
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
||||||
let scanObj = http.get(`https://reward.yumc.pw/server/scan`)
|
let scanObj = http.get(`https://reward.yumc.pw/server/scan`)
|
||||||
if (scanObj.code !== 200) {
|
if (scanObj.code !== 200) {
|
||||||
@@ -508,8 +530,7 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private bindUser(sender: org.bukkit.entity.Player) {
|
private bindUser(sender: org.bukkit.entity.Player) {
|
||||||
if (!this.config.serverId || !this.config.serverToken) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
if (!this.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||||
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
|
||||||
let check = this.httpPost(`https://reward.yumc.pw/server/query`, {
|
let check = this.httpPost(`https://reward.yumc.pw/server/query`, {
|
||||||
id: this.config.serverId,
|
id: this.config.serverId,
|
||||||
token: this.config.serverToken
|
token: this.config.serverToken
|
||||||
@@ -519,8 +540,10 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
let queryUser = this.queryUser(sender)
|
let queryUser = this.queryUser(sender)
|
||||||
if (queryUser.code == 200) {
|
if (queryUser.code == 200) {
|
||||||
return this.logger.sender(sender, ['§4当前用户已绑定! §c如需解绑 请联系腐竹!', '§b如需看广告请进QQ群 §a点击聊天框上的圈云盒子!'])
|
this.logger.sender(sender, ['§a当前用户已绑定! §3如需看广告请扫码进入!'])
|
||||||
|
return this.cmdopen(sender)
|
||||||
}
|
}
|
||||||
|
this.logger.sender(sender, '§a正在请求二维码 请稍候...')
|
||||||
let bindUrl = 'https://m.q.qq.com/a/p/1110360279?s=' + encodeURIComponent(`pages/my/index?bindType=user&serverId=${this.config.serverId}&uuid=${sender.getUniqueId().toString()}&username=${sender.getName()}`)
|
let bindUrl = 'https://m.q.qq.com/a/p/1110360279?s=' + encodeURIComponent(`pages/my/index?bindType=user&serverId=${this.config.serverId}&uuid=${sender.getUniqueId().toString()}&username=${sender.getName()}`)
|
||||||
let sync = { scaned: false, timeout: false }
|
let sync = { scaned: false, timeout: false }
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
@@ -550,45 +573,50 @@ export class MiaoReward extends interfaces.Plugin {
|
|||||||
|
|
||||||
private setItemAndTp(sender: org.bukkit.entity.Player, content: string, sync: { scaned: boolean }) {
|
private setItemAndTp(sender: org.bukkit.entity.Player, content: string, sync: { scaned: boolean }) {
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
this.bindingLeftTime = 30
|
let bindingLeftTime = 55
|
||||||
this.bindingTask = this.taskManager.create(() => {
|
let task = this.taskManager.create(() => {
|
||||||
try {
|
try {
|
||||||
if (sync.scaned || !sender.isOnline() || !this.isHoldQrCodeItem(sender) || --this.bindingLeftTime < 0) {
|
if (sync.scaned || !sender.isOnline() || !this.isHoldQrCodeItem(sender) || --bindingLeftTime < 0) {
|
||||||
if (this.bindingLeftTime < 0) {
|
if (bindingLeftTime < 0) {
|
||||||
this.logger.sender(sender, '§c二维码已过期 请重新获取 如已扫码请忽略!')
|
this.logger.sender(sender, '§c二维码已过期 请重新获取 如已扫码请忽略!')
|
||||||
|
task.cancel()
|
||||||
}
|
}
|
||||||
this.cancelTask(sender)
|
this.cancelTask(sender)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
this.sendActionBar(sender, `§c§l手机QQ扫描二维码 剩余 ${this.bindingLeftTime} 秒...`)
|
this.sendActionBar(sender, `§c§l手机QQ扫描二维码 剩余 ${bindingLeftTime} 秒...`)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
}
|
}
|
||||||
}).async().later(20).timer(20).submit()
|
}, this).async().later(20).timer(20).submit()
|
||||||
sender.setItemInHand(this.createQrCodeMapItem(content))
|
this.playerTaskCache.set(sender.getName(), task)
|
||||||
if (this.downgrade) {
|
if (this.downgrade) {
|
||||||
this.logger.sender(sender, '§c低版本客户端 二维码渲染中 请等待 6 秒 稍候扫码!')
|
this.logger.sender(sender, '§c低版本客户端 二维码渲染中 请等待 3 秒 稍候扫码!')
|
||||||
let waitTask = this.taskManager.create(() => {
|
let waitTask = this.taskManager.create(() => {
|
||||||
let temp = sender.getLocation()
|
let temp = sender.getLocation()
|
||||||
temp.setPitch(-90)
|
temp.setPitch(-90)
|
||||||
sender.teleport(temp)
|
sender.teleport(temp)
|
||||||
}).later(20).timer(20).submit()
|
}, this).later(0).timer(20).submit()
|
||||||
this.taskManager.create(() => {
|
this.taskManager.create(() => {
|
||||||
waitTask.cancel()
|
waitTask.cancel()
|
||||||
let temp = sender.getLocation()
|
let temp = sender.getLocation()
|
||||||
temp.setPitch(90)
|
temp.setPitch(90)
|
||||||
sender.teleport(temp)
|
sender.teleport(temp)
|
||||||
}).later(150).submit()
|
}).later(80).submit()
|
||||||
} else {
|
}
|
||||||
|
this.playerImageCache.set(sender.getName(), org.bukkit.map.MapPalette.imageToBytes(this.createQrcode(content)))
|
||||||
|
if (!this.downgrade) {
|
||||||
let temp = sender.getLocation()
|
let temp = sender.getLocation()
|
||||||
temp.setPitch(90)
|
temp.setPitch(90)
|
||||||
sender.teleport(temp)
|
sender.teleport(temp)
|
||||||
}
|
}
|
||||||
|
this.sendWindowItems(sender, this.createQrCodeMapItem())
|
||||||
|
sender.sendMap(this.zeroMapView)
|
||||||
}).submit()
|
}).submit()
|
||||||
}
|
}
|
||||||
|
|
||||||
private queryUser(sender: org.bukkit.entity.Player, sync = false) {
|
private queryUser(sender: org.bukkit.entity.Player, sync = false) {
|
||||||
if (!this.config.serverId || !this.config.serverToken) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
if (!this.serverInfo) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||||
let result = this.httpPost(`https://reward.yumc.pw/server/queryUser`, {
|
let result = this.httpPost(`https://reward.yumc.pw/server/queryUser`, {
|
||||||
id: this.config.serverId,
|
id: this.config.serverId,
|
||||||
token: this.config.serverToken,
|
token: this.config.serverToken,
|
||||||
@@ -636,9 +664,9 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
private createQrCodeMapItem(content: string) {
|
private createQrCodeMapItem() {
|
||||||
let item: org.bukkit.inventory.ItemStack
|
let item: org.bukkit.inventory.ItemStack
|
||||||
item = new ItemStack(Material.FILLED_MAP || Material.MAP)
|
item = new org.bukkit.inventory.ItemStack(org.bukkit.Material.FILLED_MAP || org.bukkit.Material.MAP)
|
||||||
let meta = <org.bukkit.inventory.meta.MapMeta>item.getItemMeta()
|
let meta = <org.bukkit.inventory.meta.MapMeta>item.getItemMeta()
|
||||||
if (meta.setMapView) {
|
if (meta.setMapView) {
|
||||||
meta.setMapView(this.zeroMapView)
|
meta.setMapView(this.zeroMapView)
|
||||||
@@ -650,7 +678,6 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
meta.setDisplayName('§c请使用手机QQ扫描二维码!')
|
meta.setDisplayName('§c请使用手机QQ扫描二维码!')
|
||||||
meta.setLore(["QRCODE"])
|
meta.setLore(["QRCODE"])
|
||||||
item.setItemMeta(meta)
|
item.setItemMeta(meta)
|
||||||
this.zeroMapRender.setImage(this.createQrcode(content))
|
|
||||||
return item
|
return item
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -691,30 +718,19 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
const player = event.getPlayer()
|
const player = event.getPlayer()
|
||||||
this.bungeeCordDetect(player)
|
this.bungeeCordDetect(player)
|
||||||
this.updatePlayerInfo(player)
|
this.updatePlayerInfo(player)
|
||||||
|
this.taskManager.create(() => this.logger.sender(player, `§a本服已使用喵式奖励 §3可以看广告赚${this.config.coinName} §c/mrd help §b查看帮助!`)).later(50).submit()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Listener()
|
@Listener()
|
||||||
PlayerDropItemEvent(event: org.bukkit.event.player.PlayerDropItemEvent) {
|
PlayerDropItemEvent(event: org.bukkit.event.player.PlayerDropItemEvent) {
|
||||||
if (this.isQrCodeItem(event.getItemDrop().getItemStack())) {
|
if (this.checkAndClear(event.getPlayer())) {
|
||||||
event.getItemDrop().remove()
|
event.setCancelled(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Listener()
|
@Listener()
|
||||||
PlayerItemHeldEvent(event: org.bukkit.event.player.PlayerItemHeldEvent) {
|
PlayerItemHeldEvent(event: org.bukkit.event.player.PlayerItemHeldEvent) {
|
||||||
let inv = event.getPlayer().getInventory()
|
this.checkAndClear(event.getPlayer())
|
||||||
if (this.isQrCodeItem(inv.getItem(event.getPreviousSlot() as any))) {
|
|
||||||
inv.setItem(event.getPreviousSlot(), null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Listener()
|
|
||||||
InventoryClickEvent(event: org.bukkit.event.inventory.InventoryClickEvent) {
|
|
||||||
let item = event.getCurrentItem()
|
|
||||||
if (this.isQrCodeItem(item)) {
|
|
||||||
event.getInventory().setItem(event.getSlot(), null)
|
|
||||||
event.setCancelled(true)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Listener()
|
@Listener()
|
||||||
@@ -723,36 +739,23 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
}
|
}
|
||||||
|
|
||||||
private cancelTask(player) {
|
private cancelTask(player) {
|
||||||
if (!this.isBinding) return
|
if (!this.playerTaskCache.has(player.getName())) { return }
|
||||||
this.isBinding = false
|
|
||||||
this.bindingTask.cancel()
|
|
||||||
this.bindingTask = undefined
|
|
||||||
this.bindingUser = 'unknow'
|
|
||||||
this.checkAndClear(player)
|
this.checkAndClear(player)
|
||||||
this.sendActionBar(player, "")
|
this.sendActionBar(player, "")
|
||||||
this.zeroMapRender.setImage(undefined)
|
player.updateInventory()
|
||||||
//@ts-ignore
|
this.playerTaskCache.get(player.getName()).cancel()
|
||||||
this.bindingNotify.forEach(p => {
|
this.playerTaskCache.delete(player.getName())
|
||||||
if (p.isOnline()) {
|
this.playerImageCache.delete(player.getName())
|
||||||
this.logger.sender(p, `§6用户 §a${player.getName()} §6扫码已完成 §a您可以继续操作!`)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private isHoldQrCodeItem(player: org.bukkit.entity.Player) {
|
private isHoldQrCodeItem(player: org.bukkit.entity.Player) {
|
||||||
return this.isQrCodeItem(player.getItemInHand())
|
return this.playerImageCache.has(player.getName())
|
||||||
}
|
}
|
||||||
|
|
||||||
private checkAndClear(player: org.bukkit.entity.Player) {
|
private checkAndClear(player: org.bukkit.entity.Player) {
|
||||||
if (this.isHoldQrCodeItem(player)) {
|
if (this.isHoldQrCodeItem(player)) {
|
||||||
player.setItemInHand(null)
|
this.playerImageCache.delete(player.getName())
|
||||||
}
|
return true
|
||||||
}
|
|
||||||
|
|
||||||
private isQrCodeItem(item: org.bukkit.inventory.ItemStack): boolean {
|
|
||||||
if (!item || item.getType() == Material.AIR) { return false }
|
|
||||||
if ((item.getType() == Material.MAP || item.getType() == Material.FILLED_MAP) && item.hasItemMeta()) {
|
|
||||||
return Java.from(item.getItemMeta().getLore()).indexOf('QRCODE') != -1
|
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -761,19 +764,20 @@ CAST TIME : ${Date.now() - startTime}`)
|
|||||||
let help = [
|
let help = [
|
||||||
`§6====== ${this.config.prefix} §a帮助菜单 §6======`,
|
`§6====== ${this.config.prefix} §a帮助菜单 §6======`,
|
||||||
`§6/mrd bind §a绑定圈云盒子`,
|
`§6/mrd bind §a绑定圈云盒子`,
|
||||||
|
`§6/mrd open §a打开圈云盒子`,
|
||||||
`§6/mrd query §a查询当前账户`,
|
`§6/mrd query §a查询当前账户`,
|
||||||
`§6/mrd draw §e<兑换数量> §a兑换点券`
|
`§6/mrd draw §e<兑换数量> §a兑换${this.config.coinName}`
|
||||||
]
|
]
|
||||||
if (sender.isOp()) {
|
if (sender.isOp()) {
|
||||||
help = help.concat([
|
help = help.concat([
|
||||||
`§c由于您是管理员 以为您展示额外命令`,
|
`§c由于您是管理员 以为您展示额外命令`,
|
||||||
`§6/mrd bind server §a绑定服务器`,
|
`§6/mrd bind server §a绑定服务器`,
|
||||||
`§6/mrd ratio §e<兑换比例> §a设置喵币/点券兑换比例`,
|
`§6/mrd ratio §e<兑换比例> §a设置喵币/${this.config.coinName}兑换比例`,
|
||||||
`§6/mrd statistic §3近期收入统计`,
|
`§6/mrd statistic §3近期收入统计`,
|
||||||
`§6/mrd rank <boardcast>(是否公告) §2今日兑换排行`,
|
`§6/mrd rank <boardcast>(是否公告) §2今日兑换排行`,
|
||||||
`§6/mrd server §c当前服务器信息`,
|
`§6/mrd server §c当前服务器信息`,
|
||||||
`§6兑换比例设置说明: §b默认比例为 0.001 §6=> §a1000喵币 §6兑换 §c1点券`,
|
`§6兑换比例设置说明: §b默认比例为 0.001 §6=> §a1000喵币 §6兑换 §c1${this.config.coinName}`,
|
||||||
`§c注意 设置比例后 玩家兑换点券数量不能少于 1点券`,
|
`§c注意 设置比例后 玩家兑换${this.config.coinName}数量不能少于 1${this.config.coinName}`,
|
||||||
`§c比如 设置了0.001 那就是 玩家至少 1000喵币 才能兑换!`
|
`§c比如 设置了0.001 那就是 玩家至少 1000喵币 才能兑换!`
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ let langMap = {
|
|||||||
'install.finish': '§6插件 §b{name} §6版本 §3{version} §a安装成功!',
|
'install.finish': '§6插件 §b{name} §6版本 §3{version} §a安装成功!',
|
||||||
'update.finish': '§6插件 §b{name} §6版本 §3{version} §a更新成功!',
|
'update.finish': '§6插件 §b{name} §6版本 §3{version} §a更新成功!',
|
||||||
'upgrade.confirm': '§6您正在尝试更新 §bMiaoScript §c核心 §6请执行 §b/mpm §aupgrade §cconfirm §6确认执行!',
|
'upgrade.confirm': '§6您正在尝试更新 §bMiaoScript §c核心 §6请执行 §b/mpm §aupgrade §cconfirm §6确认执行!',
|
||||||
|
'upgrade.start': '§6开始§a更新 §bMiaoScript §6核心 §c正在清理 node_modules 请稍候...',
|
||||||
'upgrade.failed': '§6尝试热更新 §bMiaoScript §c核心 §4失败! §6请重启服务器完成更新...',
|
'upgrade.failed': '§6尝试热更新 §bMiaoScript §c核心 §4失败! §6请重启服务器完成更新...',
|
||||||
'deploy.token.not.exists': '§4请先配置发布Token!',
|
'deploy.token.not.exists': '§4请先配置发布Token!',
|
||||||
'deploy.success': '§6插件 §b{name} §6版本 §3{version} §a发布成功! §6服务器返回: §a{msg}',
|
'deploy.success': '§6插件 §b{name} §6版本 §3{version} §a发布成功! §6服务器返回: §a{msg}',
|
||||||
@@ -104,7 +105,7 @@ class SpongeFakeSender extends FakeSender {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@JSPlugin({ prefix: 'PM', version: '1.3.0', author: 'MiaoWoo', source: __filename })
|
@JSPlugin({ prefix: 'PM', version: '1.3.1', author: 'MiaoWoo', source: __filename })
|
||||||
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||||
@Autowired()
|
@Autowired()
|
||||||
private pluginManager: pluginApi.PluginManager
|
private pluginManager: pluginApi.PluginManager
|
||||||
@@ -326,6 +327,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
let enginePath = fs.path(fs.file(root, 'node_modules'))
|
let enginePath = fs.path(fs.file(root, 'node_modules'))
|
||||||
if (enginePath.startsWith(root)) {
|
if (enginePath.startsWith(root)) {
|
||||||
try {
|
try {
|
||||||
|
this.i18n(sender, 'upgrade.start')
|
||||||
base.delete(enginePath)
|
base.delete(enginePath)
|
||||||
this.cmdrestart(sender)
|
this.cmdrestart(sender)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
@@ -381,20 +383,22 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cmdrestart(sender: any) {
|
cmdrestart(sender: any) {
|
||||||
if (this.serverType === "sponge") {
|
setTimeout(() => {
|
||||||
setTimeout(() => this.server.dispatchConsoleCommand('sponge plugins reload'), 0)
|
if (this.serverType === "sponge") {
|
||||||
return
|
this.server.dispatchConsoleCommand('sponge plugins reload')
|
||||||
}
|
return
|
||||||
try {
|
}
|
||||||
this.logger.sender(sender, '§6Reloading §3MiaoScript Engine...')
|
try {
|
||||||
ScriptEngineContextHolder.disableEngine()
|
this.logger.sender(sender, '§6Reloading §3MiaoScript Engine...')
|
||||||
Packages.java.lang.System.gc()
|
ScriptEngineContextHolder.disableEngine()
|
||||||
ScriptEngineContextHolder.enableEngine()
|
Packages.java.lang.System.gc()
|
||||||
this.logger.sender(sender, '§3MiaoScript Engine §6Reload §aSuccessful...')
|
ScriptEngineContextHolder.enableEngine()
|
||||||
} catch (ex) {
|
this.logger.sender(sender, '§3MiaoScript Engine §6Reload §aSuccessful...')
|
||||||
this.logger.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex)
|
} catch (ex) {
|
||||||
this.logger.sender(sender, this.logger.stack(ex))
|
this.logger.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex)
|
||||||
}
|
this.logger.sender(sender, this.logger.stack(ex))
|
||||||
|
}
|
||||||
|
}, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdrun(sender: any, ...args: any[]) {
|
cmdrun(sender: any, ...args: any[]) {
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ export class MiaoSpring extends interfaces.Plugin {
|
|||||||
preHandle: (ctx: Context) => {
|
preHandle: (ctx: Context) => {
|
||||||
const index = foundMap.indexOf(ctx.request.getRequestURI())
|
const index = foundMap.indexOf(ctx.request.getRequestURI())
|
||||||
if (index != -1) {
|
if (index != -1) {
|
||||||
return this.ResponseEntity.status(this.HttpStatus.FOUND).header('Location', foundMap[index + 1]).build()
|
return this.ResponseEntity.status(org.springframework.http.HttpStatus.FOUND).header('Location', foundMap[index + 1]).build()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
1
packages/protocol/.npmignore
Symbolic link
1
packages/protocol/.npmignore
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../../.npmignore
|
||||||
27
packages/protocol/package.json
Normal file
27
packages/protocol/package.json
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"name": "@ccms/protocol",
|
||||||
|
"version": "0.10.1",
|
||||||
|
"description": "MiaoScript protocol package",
|
||||||
|
"keywords": [
|
||||||
|
"miaoscript",
|
||||||
|
"minecraft",
|
||||||
|
"bukkit",
|
||||||
|
"sponge"
|
||||||
|
],
|
||||||
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
|
"license": "ISC",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"types": "dist/index.d.ts",
|
||||||
|
"scripts": {
|
||||||
|
"clean": "rimraf dist",
|
||||||
|
"watch": "tsc --watch",
|
||||||
|
"build": "yarn clean && tsc",
|
||||||
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^4.0.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
1
packages/protocol/src/index.ts
Normal file
1
packages/protocol/src/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export { }
|
||||||
7
packages/protocol/tsconfig.json
Normal file
7
packages/protocol/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": "src",
|
||||||
|
"outDir": "dist"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/sponge",
|
"name": "@ccms/sponge",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/sponge-api": "^0.0.3",
|
"@javatypes/sponge-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.10.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,24 +9,22 @@ const TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class SpongeTaskManager extends task.TaskManager {
|
export class SpongeTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
|
||||||
private pluginInstance: any
|
|
||||||
private syncExecutor: any
|
private syncExecutor: any
|
||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
initialize() {
|
initialize() {
|
||||||
this.syncExecutor = Sponge.getScheduler().createSyncExecutor(this.pluginInstance)
|
this.syncExecutor = Sponge.getScheduler().createSyncExecutor(base.getInstance())
|
||||||
}
|
}
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
return new SpongeTask(this.pluginInstance, func)
|
return new SpongeTask(owner, func, id)
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
return this.syncExecutor.schedule(new Callable({ call: () => func() }), java.lang.Long.valueOf(0), TimeUnit.NANOSECONDS).get()
|
return this.syncExecutor.schedule(new Callable({ call: () => func() }), java.lang.Long.valueOf(0), TimeUnit.NANOSECONDS).get()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
Sponge.getScheduler().getScheduledTasks(this.pluginInstance).forEach((task: task.Cancelable) => task.cancel())
|
Sponge.getScheduler().getScheduledTasks(base.getInstance()).forEach((task: task.Cancelable) => task.cancel())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +34,6 @@ export class SpongeTask extends task.Task {
|
|||||||
if (this.isAsync) { run.async() }
|
if (this.isAsync) { run.async() }
|
||||||
if (this.laterTime) { run.delayTicks(this.laterTime) }
|
if (this.laterTime) { run.delayTicks(this.laterTime) }
|
||||||
if (this.interval) { run.intervalTicks(this.interval) }
|
if (this.interval) { run.intervalTicks(this.interval) }
|
||||||
return run.submit(this.plugin)
|
return run.submit(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/spring",
|
"name": "@ccms/spring",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript spring package",
|
"description": "MiaoScript spring package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,12 +21,12 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8",
|
"@ccms/container": "^0.10.1",
|
||||||
"@ccms/database": "^0.9.8"
|
"@ccms/database": "^0.10.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,32 @@
|
|||||||
import { server } from '@ccms/api'
|
import { constants, server } from '@ccms/api'
|
||||||
import { provideSingleton, inject } from '@ccms/container'
|
import { provideSingleton, postConstruct, Autowired, Container, ContainerInstance } from '@ccms/container'
|
||||||
import { NativePluginManager } from '@ccms/api'
|
|
||||||
import { CommandMap } from './internal/command'
|
import { CommandMap } from './internal/command'
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
export class SpringServer implements server.Server {
|
export class SpringServer extends server.Server {
|
||||||
@inject(CommandMap)
|
@Autowired(ContainerInstance)
|
||||||
|
private container: Container
|
||||||
|
@Autowired()
|
||||||
private commandMap: CommandMap
|
private commandMap: CommandMap
|
||||||
|
|
||||||
|
private nettyPipeline = base.getInstance().getAutowireCapableBeanFactory()
|
||||||
|
private rootLogger = Packages.org.slf4j.LoggerFactory.getLogger("root") || global.logger
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
initialize() {
|
||||||
|
this.container.bind(constants.ServiceIdentifier.NettyPipeline).toConstantValue(this.nettyPipeline)
|
||||||
|
this.container.bind(constants.ServiceIdentifier.RootLogger).toConstantValue(this.rootLogger)
|
||||||
|
}
|
||||||
|
|
||||||
getVersion(): string {
|
getVersion(): string {
|
||||||
return "SpringFramework"
|
return "SpringFramework"
|
||||||
}
|
}
|
||||||
getPlayer(name: string) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getOnlinePlayers(): any[] {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getConsoleSender() {
|
getConsoleSender() {
|
||||||
return {
|
return {
|
||||||
name: 'CONSOLE',
|
name: 'CONSOLE',
|
||||||
sendMessage: (message: string) => console.console(message)
|
sendMessage: (message: string) => console.console(message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
getService(service: string) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
dispatchCommand(sender: any, command: string): boolean {
|
dispatchCommand(sender: any, command: string): boolean {
|
||||||
let cmd_args = command.split(" ")
|
let cmd_args = command.split(" ")
|
||||||
return this.commandMap.dispatch(sender, cmd_args.shift(), cmd_args || [])
|
return this.commandMap.dispatch(sender, cmd_args.shift(), cmd_args || [])
|
||||||
@@ -33,16 +34,10 @@ export class SpringServer implements server.Server {
|
|||||||
dispatchConsoleCommand(command: string): boolean {
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
return this.dispatchCommand(this.getConsoleSender(), command)
|
return this.dispatchCommand(this.getConsoleSender(), command)
|
||||||
}
|
}
|
||||||
getPluginsFolder(): string {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getNativePluginManager(): NativePluginManager {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getNettyPipeline() {
|
getNettyPipeline() {
|
||||||
return base.getInstance().getAutowireCapableBeanFactory()
|
return this.nettyPipeline
|
||||||
}
|
}
|
||||||
getRootLogger() {
|
getRootLogger() {
|
||||||
return Packages.org.slf4j.LoggerFactory.getLogger("root") || global.logger
|
return this.rootLogger
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { task, plugin } from '@ccms/api'
|
|||||||
import { inject, provideSingleton } from '@ccms/container'
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
import thread_pool from '@ccms/common/dist/thread-pool'
|
import thread_pool from '@ccms/common/dist/thread-pool'
|
||||||
|
|
||||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
|
||||||
const AtomicBoolean = Java.type("java.util.concurrent.atomic.AtomicBoolean")
|
const AtomicBoolean = Java.type("java.util.concurrent.atomic.AtomicBoolean")
|
||||||
const Thread = Java.type('java.lang.Thread')
|
const Thread = Java.type('java.lang.Thread')
|
||||||
|
|
||||||
@@ -11,21 +10,19 @@ export class SpringTaskManager extends task.TaskManager {
|
|||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
|
|
||||||
private taskId: any
|
|
||||||
private tasks: { [s: string]: task.Cancelable }
|
private tasks: { [s: string]: task.Cancelable }
|
||||||
private executor: java.util.concurrent.ThreadPoolExecutor
|
private executor: java.util.concurrent.ThreadPoolExecutor
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super()
|
super()
|
||||||
this.taskId = new AtomicInteger(0)
|
|
||||||
this.tasks = {}
|
this.tasks = {}
|
||||||
this.executor = thread_pool.create({
|
this.executor = thread_pool.create({
|
||||||
groupName: '@ccms/spring'
|
groupName: '@ccms/spring'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
return new SpringTask(this.pluginInstance, func, this)
|
return new SpringTask(owner, func, id, this)
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func()
|
return func()
|
||||||
@@ -51,8 +48,8 @@ export class SpringTask extends task.Task {
|
|||||||
private taskManager: SpringTaskManager
|
private taskManager: SpringTaskManager
|
||||||
private running = new AtomicBoolean(true)
|
private running = new AtomicBoolean(true)
|
||||||
|
|
||||||
constructor(plugin: any, func: Function, taskManager: SpringTaskManager) {
|
constructor(owner: plugin.Plugin, func: Function, id: number, taskManager: SpringTaskManager) {
|
||||||
super(plugin, func)
|
super(owner, func, id)
|
||||||
this.id = taskManager.nextId()
|
this.id = taskManager.nextId()
|
||||||
this.taskManager = taskManager
|
this.taskManager = taskManager
|
||||||
}
|
}
|
||||||
@@ -83,19 +80,16 @@ export class SpringTask extends task.Task {
|
|||||||
this.cancel()
|
this.cancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
cancel0(): any {
|
cancel0() {
|
||||||
var wasRunning = this.running.getAndSet(false)
|
var wasRunning = this.running.getAndSet(false)
|
||||||
if (wasRunning) {
|
if (wasRunning) {
|
||||||
this.taskManager.cancel(this.id)
|
this.taskManager.cancel(this.id)
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
submit0(...args: any[]) {
|
submit0(...args: any[]) {
|
||||||
this.taskManager.submit(this.id, this, () => this.run(...args))
|
this.taskManager.submit(this.id, this, () => this.run(...args))
|
||||||
return {
|
|
||||||
cancel: () => {
|
|
||||||
return this.cancel0()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/web",
|
"name": "@ccms/web",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript web package",
|
"description": "MiaoScript web package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -26,10 +26,10 @@
|
|||||||
"@javatypes/tomcat": "^0.0.3",
|
"@javatypes/tomcat": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.10.1",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.10.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/websocket",
|
"name": "@ccms/websocket",
|
||||||
"version": "0.9.8",
|
"version": "0.10.1",
|
||||||
"description": "MiaoScript websocket package",
|
"description": "MiaoScript websocket package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,10 +19,10 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.10.1",
|
||||||
"@javatypes/tomcat-websocket-api": "^0.0.3",
|
"@javatypes/tomcat-websocket-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ const TextWebSocketFrameMatcher = TypeParameterMatcher.get(base.getClass('io.net
|
|||||||
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
||||||
|
|
||||||
export abstract class TextWebSocketFrameHandlerAdapter {
|
export abstract class TextWebSocketFrameHandlerAdapter {
|
||||||
private _Handler;
|
private _Handler
|
||||||
constructor() {
|
constructor() {
|
||||||
let TextWebSocketFrameHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
let TextWebSocketFrameHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
||||||
userEventTriggered: this.userEventTriggered.bind(this),
|
userEventTriggered: this.userEventTriggered.bind(this),
|
||||||
@@ -13,12 +13,12 @@ export abstract class TextWebSocketFrameHandlerAdapter {
|
|||||||
channelRead0: this.channelRead0.bind(this),
|
channelRead0: this.channelRead0.bind(this),
|
||||||
exceptionCaught: this.exceptionCaught.bind(this)
|
exceptionCaught: this.exceptionCaught.bind(this)
|
||||||
})
|
})
|
||||||
this._Handler = new TextWebSocketFrameHandlerAdapterImpl();
|
this._Handler = new TextWebSocketFrameHandlerAdapterImpl()
|
||||||
}
|
}
|
||||||
abstract userEventTriggered(ctx: any, evt: any);
|
abstract userEventTriggered(ctx: any, evt: any)
|
||||||
abstract channelRead0(ctx: any, msg: any);
|
abstract channelRead0(ctx: any, msg: any)
|
||||||
abstract exceptionCaught(ctx: any, cause: Error);
|
abstract exceptionCaught(ctx: any, cause: Error)
|
||||||
getHandler() {
|
getHandler() {
|
||||||
return this._Handler;
|
return this._Handler
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,19 @@
|
|||||||
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
|
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
|
||||||
|
|
||||||
export abstract class WebSocketHandlerAdapter {
|
export abstract class WebSocketHandlerAdapter {
|
||||||
private _Handler;
|
private _Handler
|
||||||
constructor() {
|
constructor() {
|
||||||
let ChannelInboundHandlerAdapterImpl = Java.extend(ChannelInboundHandlerAdapter, {
|
let ChannelInboundHandlerAdapterImpl = Java.extend(ChannelInboundHandlerAdapter, {
|
||||||
channelRead: this.channelRead.bind(this),
|
channelRead: this.channelRead.bind(this),
|
||||||
|
channelUnregistered: this.exceptionCaught.bind(this),
|
||||||
exceptionCaught: this.exceptionCaught.bind(this)
|
exceptionCaught: this.exceptionCaught.bind(this)
|
||||||
})
|
})
|
||||||
this._Handler = new ChannelInboundHandlerAdapterImpl()
|
this._Handler = new ChannelInboundHandlerAdapterImpl()
|
||||||
}
|
}
|
||||||
abstract channelRead(ctx: any, channel: any);
|
abstract channelRead(ctx: any, channel: any)
|
||||||
abstract exceptionCaught(ctx: any, cause: Error);
|
abstract channelUnregistered(ctx: any)
|
||||||
|
abstract exceptionCaught(ctx: any, cause: Error)
|
||||||
getHandler() {
|
getHandler() {
|
||||||
return this._Handler;
|
return this._Handler
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,40 +1,40 @@
|
|||||||
import { EventEmitter } from 'events'
|
import { EventEmitter } from 'events'
|
||||||
import { SocketIO } from '../socket-io/interfaces';
|
import { SocketIO } from '../socket-io/interfaces'
|
||||||
import { AttributeKeys } from './constants';
|
import { AttributeKeys } from './constants'
|
||||||
|
|
||||||
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
|
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
|
||||||
|
|
||||||
export class NettyClient extends EventEmitter implements SocketIO.EngineSocket {
|
export class NettyClient extends EventEmitter implements SocketIO.EngineSocket {
|
||||||
private _id: string;
|
private _id: string
|
||||||
private channel: any
|
private channel: any
|
||||||
|
|
||||||
server: any;
|
server: any
|
||||||
readyState: string;
|
readyState: string
|
||||||
remoteAddress: string;
|
remoteAddress: string
|
||||||
upgraded: boolean;
|
upgraded: boolean
|
||||||
request: any;
|
request: any
|
||||||
transport: any;
|
transport: any
|
||||||
|
|
||||||
constructor(server: any, channel: any) {
|
constructor(server: any, channel: any) {
|
||||||
super();
|
super()
|
||||||
this.server = server;
|
this.server = server
|
||||||
this.readyState = 'open';
|
this.readyState = 'open'
|
||||||
this.remoteAddress = channel.remoteAddress() + ''
|
this.remoteAddress = channel.remoteAddress() + ''
|
||||||
this.upgraded = true;
|
this.upgraded = true
|
||||||
this.request = channel.attr(AttributeKeys.Request).get();
|
this.request = channel.attr(AttributeKeys.Request).get()
|
||||||
this.transport = null;
|
this.transport = null
|
||||||
|
|
||||||
this.channel = channel;
|
this.channel = channel
|
||||||
this._id = channel.id();
|
this._id = channel.id() + ''
|
||||||
}
|
}
|
||||||
|
|
||||||
get id() {
|
get id() {
|
||||||
return this._id;
|
return this._id
|
||||||
}
|
}
|
||||||
send(text: string) {
|
send(text: string) {
|
||||||
this.channel.writeAndFlush(new TextWebSocketFrame(text))
|
this.channel.writeAndFlush(new TextWebSocketFrame(text))
|
||||||
}
|
}
|
||||||
close() {
|
close() {
|
||||||
this.channel.close();
|
this.channel.close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,14 +9,14 @@ import { WebSocketDetect } from './websocket_detect'
|
|||||||
import { WebSocketHandler } from './websocket_handler'
|
import { WebSocketHandler } from './websocket_handler'
|
||||||
|
|
||||||
class NettyWebSocketServer extends EventEmitter {
|
class NettyWebSocketServer extends EventEmitter {
|
||||||
private pipeline: any;
|
private pipeline: any
|
||||||
private allClients: { [key: string]: NettyClient };
|
private clients: Map<string, NettyClient>
|
||||||
|
|
||||||
constructor(pipeline: any, options: ServerOptions) {
|
constructor(pipeline: any, options: ServerOptions) {
|
||||||
super()
|
super()
|
||||||
this.allClients = {};
|
this.clients = new Map()
|
||||||
this.pipeline = pipeline;
|
this.pipeline = pipeline
|
||||||
let connectEvent = options.event;
|
let connectEvent = options.event
|
||||||
try { this.pipeline.remove(Keys.Detect) } catch (error) { }
|
try { this.pipeline.remove(Keys.Detect) } catch (error) { }
|
||||||
this.pipeline.addFirst(Keys.Detect, new WebSocketDetect(connectEvent).getHandler())
|
this.pipeline.addFirst(Keys.Detect, new WebSocketDetect(connectEvent).getHandler())
|
||||||
connectEvent.on(ServerEvent.detect, (ctx, channel) => {
|
connectEvent.on(ServerEvent.detect, (ctx, channel) => {
|
||||||
@@ -24,22 +24,42 @@ class NettyWebSocketServer extends EventEmitter {
|
|||||||
ctx.fireChannelRead(channel)
|
ctx.fireChannelRead(channel)
|
||||||
})
|
})
|
||||||
connectEvent.on(ServerEvent.connect, (ctx) => {
|
connectEvent.on(ServerEvent.connect, (ctx) => {
|
||||||
|
let cid = ctx?.channel().id() + ''
|
||||||
let nettyClient = new NettyClient(this, ctx.channel())
|
let nettyClient = new NettyClient(this, ctx.channel())
|
||||||
this.allClients[nettyClient.id] = nettyClient
|
this.clients.set(cid, nettyClient)
|
||||||
this.emit(ServerEvent.connect, nettyClient)
|
this.emit(ServerEvent.connect, nettyClient)
|
||||||
})
|
})
|
||||||
connectEvent.on(ServerEvent.message, (ctx, msg) => {
|
connectEvent.on(ServerEvent.message, (ctx, msg) => {
|
||||||
this.emit(ServerEvent.message, this.allClients[ctx.channel().id()], msg.text())
|
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) => {
|
connectEvent.on(ServerEvent.error, (ctx, cause) => {
|
||||||
this.emit(ServerEvent.error, this.allClients[ctx.channel().id()], 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() {
|
close() {
|
||||||
if (this.pipeline.names().contains(Keys.Detect)) {
|
if (this.pipeline.names().contains(Keys.Detect)) {
|
||||||
this.pipeline.remove(Keys.Detect)
|
this.pipeline.remove(Keys.Detect)
|
||||||
}
|
}
|
||||||
Object.values(this.allClients).forEach(client => client.close())
|
this.clients.forEach(client => client.close())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,15 +3,19 @@ import { WebSocketHandlerAdapter } from "../netty"
|
|||||||
import { ServerEvent } from '../socket-io/constants'
|
import { ServerEvent } from '../socket-io/constants'
|
||||||
|
|
||||||
export class WebSocketDetect extends WebSocketHandlerAdapter {
|
export class WebSocketDetect extends WebSocketHandlerAdapter {
|
||||||
private event: EventEmitter;
|
private event: EventEmitter
|
||||||
constructor(event: EventEmitter) {
|
constructor(event: EventEmitter) {
|
||||||
super()
|
super()
|
||||||
this.event = event;
|
this.event = event
|
||||||
}
|
}
|
||||||
channelRead(ctx: any, channel: any) {
|
channelRead(ctx: any, channel: any) {
|
||||||
this.event.emit(ServerEvent.detect, ctx, channel);
|
this.event.emit(ServerEvent.detect, ctx, channel)
|
||||||
|
}
|
||||||
|
channelUnregistered(ctx: any) {
|
||||||
|
this.event.emit(ServerEvent.disconnect, ctx, 'client disconnect')
|
||||||
|
ctx.fireChannelUnregistered()
|
||||||
}
|
}
|
||||||
exceptionCaught(ctx: any, cause: Error) {
|
exceptionCaught(ctx: any, cause: Error) {
|
||||||
this.event.emit(ServerEvent.error, ctx, cause);
|
this.event.emit(ServerEvent.error, ctx, cause)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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')
|
const WebSocketServerProtocolHandler = Java.type('io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler')
|
||||||
|
|
||||||
export class WebSocketHandler extends WebSocketHandlerAdapter {
|
export class WebSocketHandler extends WebSocketHandlerAdapter {
|
||||||
private options: ServerOptions;
|
private options: ServerOptions
|
||||||
constructor(options: ServerOptions) {
|
constructor(options: ServerOptions) {
|
||||||
super()
|
super()
|
||||||
this.options = options;
|
this.options = options
|
||||||
}
|
}
|
||||||
channelRead(ctx: any, msg: any) {
|
channelRead(ctx: any, msg: any) {
|
||||||
msg.markReaderIndex()
|
msg.markReaderIndex()
|
||||||
@@ -32,6 +32,7 @@ export class WebSocketHandler extends WebSocketHandlerAdapter {
|
|||||||
pipeline.addLast('chunk', new ChunkedWriteHandler())
|
pipeline.addLast('chunk', new ChunkedWriteHandler())
|
||||||
pipeline.addLast('httpobj', new HttpObjectAggregator(64 * 1024))
|
pipeline.addLast('httpobj', new HttpObjectAggregator(64 * 1024))
|
||||||
pipeline.addLast('http_request', new HttpRequestHandler(this.options).getHandler())
|
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', new WebSocketServerProtocolHandler(this.options.path, true))
|
||||||
pipeline.addLast('websocket_handler', new TextWebSocketFrameHandler(this.options).getHandler())
|
pipeline.addLast('websocket_handler', new TextWebSocketFrameHandler(this.options).getHandler())
|
||||||
}
|
}
|
||||||
@@ -39,6 +40,12 @@ export class WebSocketHandler extends WebSocketHandlerAdapter {
|
|||||||
msg.resetReaderIndex()
|
msg.resetReaderIndex()
|
||||||
ctx.fireChannelRead(msg)
|
ctx.fireChannelRead(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
channelUnregistered(ctx: any) {
|
||||||
|
this.options.event.emit(ServerEvent.disconnect, ctx, 'client disconnect')
|
||||||
|
ctx.fireChannelUnregistered()
|
||||||
|
}
|
||||||
|
|
||||||
exceptionCaught(ctx: any, cause: Error) {
|
exceptionCaught(ctx: any, cause: Error) {
|
||||||
this.options.event.emit(ServerEvent.error, ctx, cause)
|
this.options.event.emit(ServerEvent.error, ctx, cause)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ interface WebSocketServer extends EventEmitter {
|
|||||||
|
|
||||||
class Server implements SocketIO.Server {
|
class Server implements SocketIO.Server {
|
||||||
private websocketServer: WebSocketServer
|
private websocketServer: WebSocketServer
|
||||||
private allClients: { [key: string]: Client }
|
private allClients: Map<string, Client>
|
||||||
|
|
||||||
engine: { ws: any }
|
engine: { ws: any }
|
||||||
nsps: { [namespace: string]: Namespace }
|
nsps: { [namespace: string]: Namespace }
|
||||||
@@ -35,7 +35,7 @@ class Server implements SocketIO.Server {
|
|||||||
|
|
||||||
constructor(instance: any, options: ServerOptions) {
|
constructor(instance: any, options: ServerOptions) {
|
||||||
if (!instance) { throw new Error('instance can\'t be undefiend!') }
|
if (!instance) { throw new Error('instance can\'t be undefiend!') }
|
||||||
this.allClients = {}
|
this.allClients = new Map()
|
||||||
this.nsps = {}
|
this.nsps = {}
|
||||||
this.sockets = new Namespace('/', this)
|
this.sockets = new Namespace('/', this)
|
||||||
this.nsps['/'] = this.sockets
|
this.nsps['/'] = this.sockets
|
||||||
@@ -99,18 +99,17 @@ class Server implements SocketIO.Server {
|
|||||||
bind(srv: any): SocketIO.Server {
|
bind(srv: any): SocketIO.Server {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
onconnection(socket: Client): SocketIO.Server {
|
onconnection(client: Client): SocketIO.Server {
|
||||||
this.allClients[socket.id] = socket
|
client.packet({
|
||||||
socket.packet({
|
|
||||||
type: PacketTypes.OPEN,
|
type: PacketTypes.OPEN,
|
||||||
data: {
|
data: {
|
||||||
sid: socket.id,
|
sid: client.id,
|
||||||
upgrades: [],
|
upgrades: [],
|
||||||
pingInterval: 25000,
|
pingInterval: 25000,
|
||||||
pingTimeout: 5000
|
pingTimeout: 5000
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
this.sockets.add(socket)
|
this.sockets.add(client)
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
of(nsp: string): Namespace {
|
of(nsp: string): Namespace {
|
||||||
@@ -164,20 +163,35 @@ class Server implements SocketIO.Server {
|
|||||||
private initServer() {
|
private initServer() {
|
||||||
this.websocketServer.on(ServerEvent.connect, (socket: SocketIO.EngineSocket) => {
|
this.websocketServer.on(ServerEvent.connect, (socket: SocketIO.EngineSocket) => {
|
||||||
let client = new Client(this, socket)
|
let client = new Client(this, socket)
|
||||||
|
this.allClients.set(socket.id, client)
|
||||||
this.onconnection(client)
|
this.onconnection(client)
|
||||||
})
|
})
|
||||||
this.websocketServer.on(ServerEvent.message, (socket: SocketIO.EngineSocket, text) => {
|
this.websocketServer.on(ServerEvent.message, (socket: SocketIO.EngineSocket, text) => {
|
||||||
this.processPacket(this.parser.decode(text), this.allClients[socket.id])
|
if (this.allClients.has(socket.id)) {
|
||||||
|
this.processPacket(this.parser.decode(text), this.allClients.get(socket.id))
|
||||||
|
} else {
|
||||||
|
console.error(`unknow engine socket ${socket.id} reciver message ${text}`)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
this.websocketServer.on(ServerEvent.disconnect, (socket: SocketIO.EngineSocket, reason) => {
|
this.websocketServer.on(ServerEvent.disconnect, (socket: SocketIO.EngineSocket, reason) => {
|
||||||
this.allClients[socket.id].onclose(reason)
|
if (this.allClients.has(socket.id)) {
|
||||||
delete this.allClients[socket.id]
|
this.allClients.get(socket.id).onclose(reason)
|
||||||
|
this.allClients.delete(socket.id)
|
||||||
|
} else {
|
||||||
|
console.error(`unknow engine socket ${socket?.id} disconnect cause ${reason}`)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
this.websocketServer.on(ServerEvent.error, (socket: SocketIO.EngineSocket, cause) => {
|
this.websocketServer.on(ServerEvent.error, (socket: SocketIO.EngineSocket, cause) => {
|
||||||
if (socket.listeners(ServerEvent.error).length) {
|
if (this.allClients.has(socket?.id)) {
|
||||||
socket.emit(ServerEvent.error, cause)
|
if (socket.listeners(ServerEvent.error).length) {
|
||||||
|
socket.emit(ServerEvent.error, cause)
|
||||||
|
} else {
|
||||||
|
console.error(`engine socket ${socket.id} cause error: ${cause}`)
|
||||||
|
console.ex(cause)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
console.error(`client ${socket.id} cause error: ${cause}`)
|
console.error(`unknow engine socket ${socket?.id} cause error: ${cause}`)
|
||||||
|
console.ex(cause)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -219,5 +233,6 @@ export {
|
|||||||
Server,
|
Server,
|
||||||
Socket,
|
Socket,
|
||||||
Client,
|
Client,
|
||||||
|
Namespace,
|
||||||
ServerOptions
|
ServerOptions
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,40 +1,40 @@
|
|||||||
import { EventEmitter } from 'events'
|
import { EventEmitter } from 'events'
|
||||||
|
|
||||||
import { Client } from './client'
|
import { Client } from './client'
|
||||||
import { SocketIO } from './interfaces';
|
import { SocketIO } from './interfaces'
|
||||||
import { ServerEvent } from './constants';
|
import { ServerEvent } from './constants'
|
||||||
import { Socket } from './socket';
|
import { Socket } from './socket'
|
||||||
import { Adapter } from './adapter';
|
import { Adapter } from './adapter'
|
||||||
import { Server } from './index'
|
import { Server } from './index'
|
||||||
import { Packet } from './packet';
|
import { Packet } from './packet'
|
||||||
import { PacketTypes, SubPacketTypes } from './types';
|
import { PacketTypes, SubPacketTypes } from './types'
|
||||||
|
|
||||||
export class Namespace extends EventEmitter implements SocketIO.Namespace {
|
export class Namespace extends EventEmitter implements SocketIO.Namespace {
|
||||||
name: string;
|
name: string
|
||||||
server: Server;
|
server: Server
|
||||||
sockets: { [id: string]: Socket; };
|
sockets: { [id: string]: Socket }
|
||||||
connected: { [id: string]: Socket; };
|
connected: { [id: string]: Socket }
|
||||||
adapter: SocketIO.Adapter;
|
adapter: SocketIO.Adapter
|
||||||
json: SocketIO.Namespace;
|
json: SocketIO.Namespace
|
||||||
|
|
||||||
fns: any[];
|
fns: any[]
|
||||||
ids: number;
|
ids: number
|
||||||
rooms: string[];
|
rooms: string[]
|
||||||
flags: { [key: string]: boolean };
|
flags: { [key: string]: boolean }
|
||||||
|
|
||||||
private events = ['connect', 'connection', 'newListener']
|
private events = ['connect', 'connection', 'newListener']
|
||||||
|
|
||||||
constructor(name: string, server: Server) {
|
constructor(name: string, server: Server) {
|
||||||
super();
|
super()
|
||||||
this.name = name;
|
this.name = name
|
||||||
this.server = server;
|
this.server = server
|
||||||
this.sockets = {};
|
this.sockets = {}
|
||||||
this.connected = {};
|
this.connected = {}
|
||||||
this.fns = [];
|
this.fns = []
|
||||||
this.ids = 0;
|
this.ids = 0
|
||||||
this.rooms = [];
|
this.rooms = []
|
||||||
this.flags = {};
|
this.flags = {}
|
||||||
this.adapter = new Adapter(this);
|
this.adapter = new Adapter(this)
|
||||||
}
|
}
|
||||||
initAdapter() {
|
initAdapter() {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@@ -42,39 +42,39 @@ export class Namespace extends EventEmitter implements SocketIO.Namespace {
|
|||||||
}
|
}
|
||||||
add(client: Client, query?: any, callback?: () => void) {
|
add(client: Client, query?: any, callback?: () => void) {
|
||||||
// client.conn.request.url();
|
// client.conn.request.url();
|
||||||
let socket = new Socket(this, client, {});
|
let socket = new Socket(this, client, {})
|
||||||
this.sockets[client.id] = socket;
|
this.sockets[client.id] = socket
|
||||||
client.nsps[this.name] = socket;
|
client.nsps[this.name] = socket
|
||||||
this.onconnection(socket);
|
this.onconnection(socket)
|
||||||
return socket;
|
return socket
|
||||||
}
|
}
|
||||||
del(client: Client) {
|
del(client: Client) {
|
||||||
let socket = this.sockets[client.id];
|
let socket = this.sockets[client.id]
|
||||||
socket.disconnect();
|
socket.disconnect()
|
||||||
delete this.sockets[client.id];
|
delete this.sockets[client.id]
|
||||||
}
|
}
|
||||||
use(fn: (socket: SocketIO.Socket, fn: (err?: any) => void) => void): SocketIO.Namespace {
|
use(fn: (socket: SocketIO.Socket, fn: (err?: any) => void) => void): SocketIO.Namespace {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
to(room: string): SocketIO.Namespace {
|
to(room: string): SocketIO.Namespace {
|
||||||
if (!~this.rooms.indexOf(room)) this.rooms.push(room);
|
if (!~this.rooms.indexOf(room)) this.rooms.push(room)
|
||||||
return this;
|
return this
|
||||||
}
|
}
|
||||||
in(room: string): SocketIO.Namespace {
|
in(room: string): SocketIO.Namespace {
|
||||||
return this.to(room);
|
return this.to(room)
|
||||||
}
|
}
|
||||||
send(...args: any[]): SocketIO.Namespace {
|
send(...args: any[]): SocketIO.Namespace {
|
||||||
super.emit('message', ...args)
|
super.emit('message', ...args)
|
||||||
return this;
|
return this
|
||||||
}
|
}
|
||||||
write(...args: any[]): SocketIO.Namespace {
|
write(...args: any[]): SocketIO.Namespace {
|
||||||
return this.send(...args);
|
return this.send(...args)
|
||||||
}
|
}
|
||||||
emit(event: string, ...args: any[]): boolean {
|
emit(event: string, ...args: any[]): boolean {
|
||||||
if (~this.events.indexOf(event)) {
|
if (~this.events.indexOf(event)) {
|
||||||
super.emit(event, ...args);
|
super.emit(event, ...args)
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
return this;
|
return this
|
||||||
}
|
}
|
||||||
// set up packet object
|
// set up packet object
|
||||||
var packet = {
|
var packet = {
|
||||||
@@ -85,54 +85,58 @@ export class Namespace extends EventEmitter implements SocketIO.Namespace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ('function' == typeof args[args.length - 1]) {
|
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 rooms = this.rooms.slice(0)
|
||||||
var flags = Object.assign({}, this.flags);
|
var flags = Object.assign({}, this.flags)
|
||||||
|
|
||||||
// reset flags
|
// reset flags
|
||||||
this.rooms = [];
|
this.rooms = []
|
||||||
this.flags = {};
|
this.flags = {}
|
||||||
|
|
||||||
this.adapter.broadcast(packet, {
|
this.adapter.broadcast(packet, {
|
||||||
rooms: rooms,
|
rooms: rooms,
|
||||||
flags: flags
|
flags: flags
|
||||||
});
|
})
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
return this;
|
return this
|
||||||
}
|
}
|
||||||
hasBin(args: any[]) {
|
hasBin(args: any[]) {
|
||||||
return false;
|
return false
|
||||||
}
|
}
|
||||||
clients(fn: Function): SocketIO.Namespace {
|
clients(fn: (sockets: Socket[]) => SocketIO.Namespace): SocketIO.Namespace {
|
||||||
return fn(Object.values(this.sockets))
|
return fn(Object.values(this.sockets))
|
||||||
}
|
}
|
||||||
compress(compress: boolean): SocketIO.Namespace {
|
compress(compress: boolean): SocketIO.Namespace {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
process(packet: Packet, client: Client) {
|
process(packet: Packet, client: Client) {
|
||||||
switch (packet.sub_type) {
|
switch (packet.sub_type) {
|
||||||
case SubPacketTypes.CONNECT:
|
case SubPacketTypes.CONNECT:
|
||||||
this.add(client);
|
this.add(client)
|
||||||
break;
|
break
|
||||||
default:
|
default:
|
||||||
this.sockets[client.id].onpacket(packet);
|
this.sockets[client.id].onpacket(packet)
|
||||||
break;
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
remove(socket: Socket) {
|
remove(socket: Socket) {
|
||||||
if (this.sockets.hasOwnProperty(socket.id)) {
|
if (this.sockets.hasOwnProperty(socket.id)) {
|
||||||
delete this.sockets[socket.id];
|
delete this.sockets[socket.id]
|
||||||
} else {
|
} else {
|
||||||
// debug('ignoring remove for %s', socket.id);
|
// debug('ignoring remove for %s', socket.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
close() {
|
||||||
|
this.removeAllListeners('connect')
|
||||||
|
Object.values(this.sockets).forEach(socket => socket.disconnect(false))
|
||||||
|
}
|
||||||
private onconnection(socket: any) {
|
private onconnection(socket: any) {
|
||||||
let client = socket as Socket;
|
let client = socket as Socket
|
||||||
this.sockets[client.id] = client;
|
this.sockets[client.id] = client
|
||||||
|
this.emit(ServerEvent.connect, socket)
|
||||||
client.onconnect()
|
client.onconnect()
|
||||||
this.emit(ServerEvent.connect, socket);
|
this.emit(ServerEvent.connection, socket)
|
||||||
this.emit(ServerEvent.connection, socket);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export class TomcatClient extends EventEmitter implements SocketIO.EngineSocket
|
|||||||
this.transport = null
|
this.transport = null
|
||||||
|
|
||||||
this.session = session
|
this.session = session
|
||||||
this._id = session.getId()
|
this._id = session.getId() + ''
|
||||||
}
|
}
|
||||||
|
|
||||||
get id() {
|
get id() {
|
||||||
|
|||||||
@@ -15,28 +15,45 @@ type TomcatWebSocketSession = javax.websocket.Session
|
|||||||
class TomcatWebSocketServer extends EventEmitter {
|
class TomcatWebSocketServer extends EventEmitter {
|
||||||
private beanFactory: any
|
private beanFactory: any
|
||||||
private executor: any
|
private executor: any
|
||||||
private allClients: { [key: string]: SocketIO.EngineSocket }
|
private clients: Map<string, SocketIO.EngineSocket>
|
||||||
|
|
||||||
constructor(beanFactory: any, options: ServerOptions) {
|
constructor(beanFactory: any, options: ServerOptions) {
|
||||||
super()
|
super()
|
||||||
this.allClients = {}
|
this.clients = new Map()
|
||||||
this.beanFactory = beanFactory
|
this.beanFactory = beanFactory
|
||||||
this.initThreadPool()
|
this.initThreadPool()
|
||||||
try { this.beanFactory.destroySingleton(ProxyBeanName) } catch (error) { }
|
try { this.beanFactory.destroySingleton(ProxyBeanName) } catch (error) { }
|
||||||
let NashornWebSocketServerProxy = Java.extend(WebSocketServerProxy, {
|
let NashornWebSocketServerProxy = Java.extend(WebSocketServerProxy, {
|
||||||
onOpen: (session: TomcatWebSocketSession) => {
|
onOpen: (session: TomcatWebSocketSession) => {
|
||||||
|
let cid = `${session?.getId()}`
|
||||||
let tomcatClient = new TomcatClient(this, session)
|
let tomcatClient = new TomcatClient(this, session)
|
||||||
this.allClients[session.getId()] = tomcatClient
|
this.clients.set(cid, tomcatClient)
|
||||||
this.emit(ServerEvent.connect, tomcatClient)
|
this.emit(ServerEvent.connect, tomcatClient)
|
||||||
},
|
},
|
||||||
onMessage: (session: TomcatWebSocketSession, message: string) => {
|
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) => {
|
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) => {
|
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())
|
this.beanFactory.registerSingleton(ProxyBeanName, new NashornWebSocketServerProxy())
|
||||||
@@ -52,7 +69,7 @@ class TomcatWebSocketServer extends EventEmitter {
|
|||||||
this.executor.initialize()
|
this.executor.initialize()
|
||||||
}
|
}
|
||||||
close() {
|
close() {
|
||||||
Object.values(this.allClients).forEach(client => client.close())
|
this.clients.forEach(client => client.close())
|
||||||
this.beanFactory.destroySingleton(ProxyBeanName)
|
this.beanFactory.destroySingleton(ProxyBeanName)
|
||||||
this.executor.shutdown()
|
this.executor.shutdown()
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user