Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9bfaf984c1 | |||
| 3c33ebf4e6 | |||
| 8af69c98f3 | |||
| 72277f4d1a | |||
| d85f75ba1f | |||
| ed14d317f4 | |||
| fb8a11ea05 | |||
| eae80fa30b | |||
| 3e69fc42d9 | |||
| c5595a65fb | |||
| df266905f2 | |||
| f8046e38be | |||
| 51fb5aece3 | |||
| 7a1dd3e7b3 | |||
| 8f3c799531 | |||
| 3389dbd566 | |||
| 54604e10b8 | |||
| d7247bae19 | |||
| 3ee2dcad0b | |||
| bc19021c63 | |||
| e9a4f2f351 |
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.6",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/amqp",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript amqp package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,17 +19,17 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/common": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/common": "^0.9.4",
|
||||
"@ccms/container": "^0.9.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.0",
|
||||
"@ccms/nashorn": "^0.9.4",
|
||||
"@javatypes/amqp-client": "^0.0.2",
|
||||
"@javatypes/spring-amqp": "^0.0.2",
|
||||
"@javatypes/spring-rabbit": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/api",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,9 +19,9 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/common": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2",
|
||||
"@ccms/ployfill": "^0.9.2",
|
||||
"@ccms/common": "^0.9.4",
|
||||
"@ccms/container": "^0.9.4",
|
||||
"@ccms/ployfill": "^0.9.4",
|
||||
"base64-js": "^1.3.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
@@ -29,6 +29,6 @@
|
||||
"@types/base64-js": "^1.3.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,15 @@ import { injectable } from '@ccms/container'
|
||||
export namespace chat {
|
||||
@injectable()
|
||||
export abstract class Chat {
|
||||
/**
|
||||
* sendJsonChat
|
||||
* @param sender reciver
|
||||
* @param json json
|
||||
* @param type chat Type 0: chat 1: system 2: actionBar
|
||||
*/
|
||||
sendJson(sender: any, json: string | object, type = 0) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
sendMessage(sender: any, message: string) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export namespace command {
|
||||
*/
|
||||
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||
var cmd = this.create(plugin, name)
|
||||
if (!cmd) { throw Error("") }
|
||||
if (!cmd) { throw Error(`Plugin ${plugin.description.name} can't create Command ${name}!`) }
|
||||
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
||||
if (exec.cmd && typeof exec.cmd === "function") {
|
||||
this.onCommand(plugin, cmd, exec.cmd)
|
||||
@@ -24,6 +24,9 @@ export namespace command {
|
||||
this.onTabComplete(plugin, cmd, exec.tab)
|
||||
}
|
||||
}
|
||||
public tabComplete(sender: any, input: string, index?: number): string[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
/**
|
||||
* 取消命令注册
|
||||
* @param plugin 插件
|
||||
@@ -59,9 +62,9 @@ export namespace command {
|
||||
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
||||
return this.copyPartialMatches(complete, token)
|
||||
} catch (ex) {
|
||||
console.i18n("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||
console.i18n("ms.api.command.tab.completer.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||
console.ex(ex)
|
||||
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
||||
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,6 +138,8 @@ export namespace event {
|
||||
// add to cache Be used for close plugin to close event
|
||||
if (!listenerMap[name]) listenerMap[name] = []
|
||||
var off = () => {
|
||||
if (off['offed']) return
|
||||
off['offed'] = true
|
||||
this.unregister(eventCls, listener)
|
||||
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls), exec: executor }))
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import "@ccms/nashorn"
|
||||
export * from './chat'
|
||||
export * from './task'
|
||||
export * from './event'
|
||||
export * from './proxy'
|
||||
export * from './console'
|
||||
export * from './channel'
|
||||
export * from './command'
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
export namespace plugin {
|
||||
/**
|
||||
* MiaoScript Plugin
|
||||
@@ -11,23 +13,20 @@ export namespace plugin {
|
||||
* Runtime Plugin Instance
|
||||
*/
|
||||
export const PluginInstance = Symbol("PluginInstance")
|
||||
/**
|
||||
* MiaoScript Plugin Manager Symbol
|
||||
*/
|
||||
export const PluginManager = Symbol("PluginManager")
|
||||
/**
|
||||
* MiaoScript Plugin Manager Interface
|
||||
*/
|
||||
export interface PluginManager {
|
||||
scan(folder: string): void
|
||||
build(): void
|
||||
loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
|
||||
load(...args: any[]): void
|
||||
enable(...args: any[]): void
|
||||
disable(...args: any[]): void
|
||||
reload(...args: any[]): void
|
||||
getPlugin(name: string): plugin.Plugin
|
||||
getPlugins(): Map<string, plugin.Plugin>
|
||||
@injectable()
|
||||
export abstract class PluginManager {
|
||||
abstract scan(folder: string): void
|
||||
abstract build(): void
|
||||
abstract loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
|
||||
abstract load(...args: any[]): void
|
||||
abstract enable(...args: any[]): void
|
||||
abstract disable(...args: any[]): void
|
||||
abstract reload(...args: any[]): void
|
||||
abstract getPlugin(name: string): plugin.Plugin
|
||||
abstract getPlugins(): Map<string, plugin.Plugin>
|
||||
}
|
||||
export const PluginScanner = Symbol("PluginScanner")
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,8 @@ import { injectable, inject } from '@ccms/container'
|
||||
import { NativePluginManager } from './native_plugin'
|
||||
import { constants } from '../../constants'
|
||||
|
||||
export { NativePluginManager } from './native_plugin'
|
||||
|
||||
export namespace server {
|
||||
/**
|
||||
* Runtime ServerType
|
||||
@@ -13,10 +15,6 @@ export namespace server {
|
||||
* Runtime Console
|
||||
*/
|
||||
export const Console = Symbol("Console")
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
export const Server = Symbol("Server")
|
||||
/**
|
||||
* Runtime Server Instance
|
||||
*/
|
||||
@@ -24,21 +22,44 @@ export namespace server {
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
export interface Server {
|
||||
getVersion(): string
|
||||
getPlayer(name: string): any
|
||||
getOnlinePlayers(): any[]
|
||||
getConsoleSender(): any
|
||||
getService(service: string): any
|
||||
dispatchCommand(sender: string | any, command: string): boolean
|
||||
dispatchConsoleCommand(command: string): boolean
|
||||
getPluginsFolder(): string
|
||||
getNativePluginManager(): NativePluginManager
|
||||
getDedicatedServer?(): any
|
||||
getNettyPipeline(): any
|
||||
getRootLogger(): any
|
||||
sendJson(sender: string | any, json: object | string): void
|
||||
tabComplete?(sender: string | any, input: string, index?: number): string[]
|
||||
@injectable()
|
||||
export abstract class Server {
|
||||
getVersion(): string {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getPlayer(name: string): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getOnlinePlayers(): any[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getConsoleSender(): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getService(service: string): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchCommand(sender: string | any, command: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getPluginsFolder(): string {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getNativePluginManager(): NativePluginManager {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getDedicatedServer?(): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getNettyPipeline(): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getRootLogger(): any {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
}
|
||||
@injectable()
|
||||
export class ServerChecker {
|
||||
@@ -58,56 +79,15 @@ export namespace server {
|
||||
}
|
||||
}
|
||||
@injectable()
|
||||
export abstract class ReflectServer implements server.Server {
|
||||
export abstract class ReflectServer extends server.Server {
|
||||
protected pipeline: any
|
||||
protected rootLogger: any
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this.reflect()
|
||||
}
|
||||
|
||||
getVersion(): string {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getPlayer(name: string) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getOnlinePlayers(): any[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getConsoleSender() {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getService(service: string) {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchCommand(sender: any, command: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getPluginsFolder(): string {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getNativePluginManager(): NativePluginManager {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getDedicatedServer() {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getNettyPipeline() {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
getRootLogger() {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
sendJson(sender: any, json: string | object): void {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
tabComplete?(sender: any, input: string, index?: number): string[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
protected reflect() {
|
||||
try {
|
||||
let consoleServer = this.getDedicatedServer()
|
||||
|
||||
160
packages/api/src/proxy.ts
Normal file
160
packages/api/src/proxy.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import { provideSingleton, Autowired } from '@ccms/container'
|
||||
import { channel } from './channel'
|
||||
|
||||
export namespace proxy {
|
||||
const ByteArrayOutputStream = Java.type('java.io.ByteArrayOutputStream')
|
||||
const DataOutputStream = Java.type('java.io.DataOutputStream')
|
||||
namespace bungeecord {
|
||||
const CHANNEL_NAME = "BungeeCord"
|
||||
export class SubChannelBuilder {
|
||||
private channel: channel.Channel
|
||||
private player: any
|
||||
private params: string[]
|
||||
constructor(channel: channel.Channel, player: any) {
|
||||
this.channel = channel
|
||||
this.player = player
|
||||
this.params = []
|
||||
}
|
||||
connect(server: string) {
|
||||
this.params.push("Connect")
|
||||
this.params.push(server)
|
||||
return this.finalSend()
|
||||
}
|
||||
connectOther(player: string, server: string) {
|
||||
this.params.push("ConnectOther")
|
||||
this.params.push(player)
|
||||
this.params.push(server)
|
||||
return this.finalSend()
|
||||
}
|
||||
ip() {
|
||||
this.params.push("IP")
|
||||
return this.finalSend()
|
||||
}
|
||||
ipOther(player: string) {
|
||||
this.params.push("IPOther")
|
||||
this.params.push(player)
|
||||
return this.finalSend()
|
||||
}
|
||||
playerCount(server: string | "ALL") {
|
||||
this.params.push("PlayerCount")
|
||||
this.params.push(server)
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Get a list of players connected on a certain server, or on ALL the servers.
|
||||
* @param server count server
|
||||
* Response:
|
||||
* String server = in.readUTF(); // The name of the server you got the player list of, as given in args.
|
||||
* String[] playerList = in.readUTF().split(", ");
|
||||
*/
|
||||
playerList(server: string | "ALL") {
|
||||
this.params.push("PlayerList")
|
||||
this.params.push(server)
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Get a list of server name strings, as defined in BungeeCord's config.yml
|
||||
* Response:
|
||||
* String[] serverList = in.readUTF().split(", ");
|
||||
*/
|
||||
getServers() {
|
||||
this.params.push("GetServers")
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Get this server's name, as defined in BungeeCord's config.yml
|
||||
*/
|
||||
getServer() {
|
||||
this.params.push("GetServer")
|
||||
return this.finalSend()
|
||||
}
|
||||
broadcast(message: string) {
|
||||
this.message("ALL", message)
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Send a message (as in, a chat message) to the specified player.
|
||||
* @param player who reciver message
|
||||
* @param message message content
|
||||
*/
|
||||
message(player: string | "ALL", message: string) {
|
||||
this.params.push("Message")
|
||||
this.params.push(player)
|
||||
this.params.push(message)
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Send a raw message (as in, a chat message) to the specified player. The advantage of this method over Message is that you can include click events and hover events.
|
||||
* @param player who reciver message
|
||||
* @param message message content
|
||||
*/
|
||||
messageRaw(player: string | "ALL", json: string) {
|
||||
this.params.push("MessageRaw")
|
||||
this.params.push(player)
|
||||
this.params.push(json)
|
||||
return this.finalSend()
|
||||
}
|
||||
forwardAll(channel: string, data: any) {
|
||||
return this.forward("ALL", channel, data)
|
||||
}
|
||||
/**
|
||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||
* Remember, the sending and receiving server(s) need to have a player online.
|
||||
* @param server reciver
|
||||
* @param channel channelName
|
||||
* @param data data
|
||||
*/
|
||||
forward(server: string | "ALL", channel: string, data: any) {
|
||||
this.params.push("Forward")
|
||||
this.params.push(server)
|
||||
this.params.push(channel)
|
||||
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
|
||||
return this.finalSend()
|
||||
}
|
||||
/**
|
||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||
* Remember, the sending and receiving server(s) need to have a player online.
|
||||
* @param server reciver
|
||||
* @param channel channelName
|
||||
* @param data data
|
||||
*/
|
||||
forwardToPlayer(server: string | "ALL", channel: string, data: any) {
|
||||
this.params.push("Forward")
|
||||
this.params.push(server)
|
||||
this.params.push(channel)
|
||||
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
|
||||
return this.finalSend()
|
||||
}
|
||||
generic(...args: string[]) {
|
||||
args && this.params.concat(...args)
|
||||
return this.finalSend()
|
||||
}
|
||||
private send(...middlewares: ((out: java.io.DataOutputStream) => void)[]) {
|
||||
let byteArray = new ByteArrayOutputStream()
|
||||
let out = new DataOutputStream(byteArray)
|
||||
this.params.forEach(utf => out.writeUTF(utf))
|
||||
for (let middleware of middlewares) {
|
||||
middleware(out)
|
||||
}
|
||||
return this.channel.send(this.player, CHANNEL_NAME, byteArray.toByteArray())
|
||||
}
|
||||
private finalSend() {
|
||||
return {
|
||||
send: this.send.bind(this)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@provideSingleton(BungeeCord)
|
||||
export class BungeeCord {
|
||||
@Autowired()
|
||||
private channel: channel.Channel
|
||||
/**
|
||||
* 获得代理
|
||||
* @param player 玩家
|
||||
*/
|
||||
for(player: any): bungeecord.SubChannelBuilder {
|
||||
return new bungeecord.SubChannelBuilder(this.channel, player)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,62 @@
|
||||
import { plugin } from './index'
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
export namespace task {
|
||||
export const TaskManager = Symbol('TaskManager')
|
||||
export interface TaskManager {
|
||||
@injectable()
|
||||
export abstract class TaskManager {
|
||||
protected cacheTasks = new Map<string, task.Task[]>()
|
||||
|
||||
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
||||
if (!this.cacheTasks.has(plugin.description.name)) {
|
||||
this.cacheTasks.set(plugin.description.name, [])
|
||||
}
|
||||
this.cacheTasks.get(plugin.description.name).push(task)
|
||||
return task
|
||||
}
|
||||
protected pluginDisable(plugin: plugin.Plugin) {
|
||||
if (this.cacheTasks.has(plugin.description.name)) {
|
||||
this.cacheTasks.get(plugin.description.name).forEach(task => task.cancel())
|
||||
this.cacheTasks.delete(plugin.description.name)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 创建任务
|
||||
* @param func 任务内容
|
||||
*/
|
||||
create(func: Function): task.Task;
|
||||
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
||||
let task = this.create0(func)
|
||||
if (plugin) { return this.pluginCreate(plugin, task) }
|
||||
return task
|
||||
}
|
||||
abstract create0(func: Function): task.Task
|
||||
/**
|
||||
* 在主线程执行代码
|
||||
* @param func 执行内容
|
||||
*/
|
||||
callSyncMethod(func: Function): any;
|
||||
abstract callSyncMethod(func: Function): any
|
||||
/**
|
||||
* 关闭任务管理器
|
||||
*/
|
||||
disable();
|
||||
disable(plugin?: plugin.Plugin) {
|
||||
if (plugin) { return this.pluginDisable(plugin) }
|
||||
this.disable0()
|
||||
}
|
||||
abstract disable0()
|
||||
}
|
||||
/**
|
||||
* 任务抽象
|
||||
*/
|
||||
export abstract class Task {
|
||||
protected plugin: any;
|
||||
protected func: Function;
|
||||
protected plugin: any
|
||||
protected func: Function
|
||||
protected isAsync: boolean = false;
|
||||
protected laterTime: number = 0;
|
||||
protected interval: number = 0;
|
||||
|
||||
constructor(plugin: any, func: Function) {
|
||||
this.plugin = plugin;
|
||||
this.func = func;
|
||||
this.plugin = plugin
|
||||
this.func = func
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,8 +64,8 @@ export namespace task {
|
||||
* @param isAsync 是否异步
|
||||
*/
|
||||
async(isAsync: boolean = true): task.Task {
|
||||
this.isAsync = isAsync;
|
||||
return this;
|
||||
this.isAsync = isAsync
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -45,8 +73,8 @@ export namespace task {
|
||||
* @param tick 延时 Tick
|
||||
*/
|
||||
later(tick: number): task.Task {
|
||||
this.laterTime = tick;
|
||||
return this;
|
||||
this.laterTime = tick
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,16 +82,23 @@ export namespace task {
|
||||
* @param tick 循环时间 Tick
|
||||
*/
|
||||
timer(tick: number): task.Task {
|
||||
this.interval = tick;
|
||||
return this;
|
||||
this.interval = tick
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消任务
|
||||
*/
|
||||
cancel(): boolean {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
|
||||
protected run(...args: any[]): void {
|
||||
try {
|
||||
this.func(...args);
|
||||
this.func(...args)
|
||||
} catch (ex) {
|
||||
console.console('§4插件执行任务时发生错误', ex)
|
||||
console.ex(ex);
|
||||
console.ex(ex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,12 +106,22 @@ export namespace task {
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
*/
|
||||
abstract submit(...args: any[]): Cancelable;
|
||||
submit(...args: any[]): Cancelable {
|
||||
let cancelable = this.submit0(...args)
|
||||
this.cancel = cancelable.cancel
|
||||
return cancelable
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
*/
|
||||
abstract submit0(...args: any[]): Cancelable
|
||||
}
|
||||
/**
|
||||
* 返可取消的对象
|
||||
*/
|
||||
export interface Cancelable {
|
||||
cancel(): boolean;
|
||||
cancel(): boolean
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bukkit",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/spigot-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/common": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/common": "^0.9.4",
|
||||
"@ccms/container": "^0.9.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,20 @@ import bukkitChat from './enhance/chat'
|
||||
|
||||
@provideSingleton(chat.Chat)
|
||||
export class BukkitChat extends chat.Chat {
|
||||
sendJson(sender: any, json: string | object, type = 0) {
|
||||
bukkitChat.send(sender, typeof json === "string" ? json : JSON.stringify(json), type)
|
||||
}
|
||||
sendMessage(sender: any, message: string) {
|
||||
bukkitChat.send(sender, JSON.stringify({ text: message }), 0)
|
||||
this.sendJson(sender, { text: message }, 0)
|
||||
}
|
||||
sendActionBar(sender: any, message: string) {
|
||||
bukkitChat.send(sender, JSON.stringify({ text: message }), 2)
|
||||
this.sendJson(sender, { text: message }, 2)
|
||||
}
|
||||
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
||||
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
|
||||
try {
|
||||
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
|
||||
} catch (error) {
|
||||
sender.sendTitle(title, subtitle)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,44 +4,47 @@ import { command, plugin } from '@ccms/api'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||
|
||||
let Bukkit = org.bukkit.Bukkit;
|
||||
let TabCompleter = Java.type('org.bukkit.command.TabCompleter');
|
||||
let PluginCommand = Java.type('org.bukkit.command.PluginCommand');
|
||||
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor');
|
||||
let Bukkit = org.bukkit.Bukkit
|
||||
let TabCompleter = Java.type('org.bukkit.command.TabCompleter')
|
||||
let PluginCommand = Java.type('org.bukkit.command.PluginCommand')
|
||||
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor')
|
||||
|
||||
@provideSingleton(command.Command)
|
||||
export class BukkitCommand extends command.Command {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
private commandMap: any;
|
||||
private commandMap: any
|
||||
|
||||
@postConstruct()
|
||||
init() {
|
||||
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get();
|
||||
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get()
|
||||
}
|
||||
create(plugin: any, command: string) {
|
||||
var cmd = this.commandMap.getCommand(command)
|
||||
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
||||
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get();
|
||||
this.commandMap.register(plugin.description.name, cmd);
|
||||
return cmd;
|
||||
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get()
|
||||
this.commandMap.register(plugin.description.name, cmd)
|
||||
return cmd
|
||||
}
|
||||
remove(plugin: any, command: string) {
|
||||
var cmd = this.commandMap.getCommand(command)
|
||||
if (cmd && cmd instanceof PluginCommand) {
|
||||
cmd.unregister(this.commandMap);
|
||||
cmd.unregister(this.commandMap)
|
||||
}
|
||||
}
|
||||
tabComplete(sender: any, input: string, index?: number): string[] {
|
||||
return Java.from(this.commandMap.tabComplete(sender, input))
|
||||
}
|
||||
onCommand(plugin: any, command: any, executor: Function) {
|
||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||
command.setExecutor(new CommandExecutor({
|
||||
onCommand: super.setExecutor(plugin, command, executor)
|
||||
}));
|
||||
}))
|
||||
}
|
||||
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||
command.setTabCompleter(new TabCompleter({
|
||||
onTabComplete: super.setTabCompleter(plugin, command, tabCompleter)
|
||||
}));
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,16 +54,4 @@ export class BukkitServer extends server.ReflectServer {
|
||||
getRootLogger() {
|
||||
return this.rootLogger
|
||||
}
|
||||
sendJson(sender: string | any, json: object | string): void {
|
||||
if (typeof sender === "string") {
|
||||
sender = this.getPlayer(sender)
|
||||
}
|
||||
let result = chat.json(sender, typeof json == "string" ? json : JSON.stringify(json))
|
||||
if (result !== false) {
|
||||
this.dispatchConsoleCommand(result)
|
||||
}
|
||||
}
|
||||
tabComplete?(sender: any, input: string, index?: number): string[] {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,28 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container';
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
|
||||
const Bukkit = Java.type('org.bukkit.Bukkit');
|
||||
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable');
|
||||
const Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable')
|
||||
const Callable = Java.type('java.util.concurrent.Callable')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class BukkitTaskManager implements task.TaskManager {
|
||||
export class BukkitTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private pluginInstance: any
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new BukkitTask(this.pluginInstance, func);
|
||||
create0(func: Function): task.Task {
|
||||
return new BukkitTask(this.pluginInstance, func)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
||||
}
|
||||
disable() {
|
||||
Bukkit.getScheduler().cancelTasks(this.pluginInstance);
|
||||
disable0() {
|
||||
Bukkit.getScheduler().cancelTasks(this.pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
export class BukkitTask extends task.Task {
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
submit0(...args: any[]): task.Cancelable {
|
||||
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/bungee",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/bungee-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/common": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/common": "^0.9.4",
|
||||
"@ccms/container": "^0.9.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,20 +6,20 @@ const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||
@provideSingleton(channel.Channel)
|
||||
export class BungeeChannel extends channel.Channel {
|
||||
@inject(event.Event)
|
||||
private eventManager: event.Event;
|
||||
private eventManager: event.Event
|
||||
|
||||
send(player: any, channel: string, data: any) {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
register(channel: string, listener: channel.ChannelListener) {
|
||||
Bungee.registerChannel(channel);
|
||||
Bungee.registerChannel(channel)
|
||||
// console.console('§6[§eWARN§6] §eMiaoScript channel in BungeeCord only register. you need self hanler PluginMessageEvent!')
|
||||
return this.eventManager.listen({ description: { name: channel } }, "PluginMessageEvent", (event: net.md_5.bungee.api.event.PluginMessageEvent) => {
|
||||
listener(event.getData(), event)
|
||||
})
|
||||
}
|
||||
unregister(channel: string, listener: any) {
|
||||
Bungee.unregisterChannel(channel);
|
||||
listener.off();
|
||||
unregister(channel: string, off: any) {
|
||||
Bungee.unregisterChannel(channel)
|
||||
off()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,29 +3,29 @@ import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
||||
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
|
||||
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
export class BungeeServer implements server.Server {
|
||||
private pluginsFolder: string;
|
||||
private pipeline: any;
|
||||
private rootLogger: any;
|
||||
private pluginsFolder: string
|
||||
private pipeline: any
|
||||
private rootLogger: any
|
||||
|
||||
@inject(task.TaskManager)
|
||||
private task: task.TaskManager
|
||||
|
||||
constructor() {
|
||||
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath();
|
||||
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath()
|
||||
}
|
||||
|
||||
@postConstruct()
|
||||
initialize() {
|
||||
let count = 0;
|
||||
let count = 0
|
||||
let wait = this.task.create(() => {
|
||||
try {
|
||||
// @ts-ignore
|
||||
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
||||
wait.cancel();
|
||||
wait.cancel()
|
||||
} catch (ex) {
|
||||
count++
|
||||
if (count > 50) {
|
||||
@@ -44,7 +44,7 @@ export class BungeeServer implements server.Server {
|
||||
}
|
||||
|
||||
getPlayer(name: string) {
|
||||
return Bungee.getPlayer(name);
|
||||
return Bungee.getPlayer(name)
|
||||
}
|
||||
getVersion(): string {
|
||||
return Bungee.getVersion()
|
||||
@@ -56,7 +56,7 @@ export class BungeeServer implements server.Server {
|
||||
return Bungee.getConsole()
|
||||
}
|
||||
getService(service: string) {
|
||||
throw new Error("Method not implemented.");
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
dispatchCommand(sender: string | any, command: string): boolean {
|
||||
if (typeof sender === 'string') {
|
||||
@@ -68,18 +68,15 @@ export class BungeeServer implements server.Server {
|
||||
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
|
||||
}
|
||||
getPluginsFolder(): string {
|
||||
return this.pluginsFolder;
|
||||
return this.pluginsFolder
|
||||
}
|
||||
getNativePluginManager() {
|
||||
return Bungee.getPluginManager() as any
|
||||
}
|
||||
getNettyPipeline() {
|
||||
return this.pipeline;
|
||||
return this.pipeline
|
||||
}
|
||||
getRootLogger() {
|
||||
return this.rootLogger;
|
||||
}
|
||||
sendJson(sender: string | any, json: string): void {
|
||||
throw new Error("Method not implemented.");
|
||||
return this.rootLogger
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container';
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
|
||||
var Runnable = Java.type('java.lang.Runnable')
|
||||
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class BungeeTaskManager implements task.TaskManager {
|
||||
export class BungeeTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private pluginInstance: any
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new BungeeTask(this.pluginInstance, func);
|
||||
create0(func: Function): task.Task {
|
||||
return new BungeeTask(this.pluginInstance, func)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func();
|
||||
return func()
|
||||
}
|
||||
disable() {
|
||||
disable0() {
|
||||
this.pluginInstance.getProxy().getScheduler().cancel(this.pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
export class BungeeTask extends task.Task {
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
submit0(...args: any[]): task.Cancelable {
|
||||
let run = new Runnable({ run: () => this.run(...args) })
|
||||
if (this.isAsync) {
|
||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ccms/client",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.4",
|
||||
"description": "MiaoScript client package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,10 +22,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"minecraft-protocol": "^1.13.0"
|
||||
"minecraft-protocol": "^1.16.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,12 @@ import { $ } from './color'
|
||||
export function attachEvents(client) {
|
||||
client.on('chat', (packet) => {
|
||||
// Listen for chat messages and echo them back.
|
||||
var jsonMsg = JSON.parse(packet.message);
|
||||
var jsonMsg = JSON.parse(packet.message)
|
||||
console.log($(jsonMsg))
|
||||
})
|
||||
client.on('state', (newState, oldState) => {
|
||||
console.log('Client Change State', oldState, 'to', newState)
|
||||
let targetServer = process.argv[3]
|
||||
let targetServer = process.argv[6]
|
||||
if (newState == "play" && targetServer) {
|
||||
setTimeout(() => {
|
||||
client.write('chat', {
|
||||
@@ -24,4 +24,10 @@ export function attachEvents(client) {
|
||||
} else if (packet.health > 0) {
|
||||
}
|
||||
})
|
||||
client.on('kick_disconnect', (packet) => {
|
||||
console.log($(packet.reason))
|
||||
})
|
||||
client.on('disconnect', (packet) => {
|
||||
console.log($(packet.reason))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,33 +5,52 @@ import { attachForge } from './forge'
|
||||
import { attachEvents } from './event'
|
||||
|
||||
let username = process.argv[2] || 'Mr_jtb'
|
||||
let version = process.argv[3] || '1.12.2'
|
||||
let address = process.argv[4] || '192.168.2.5:25577'
|
||||
let realAddress = address.split(":");
|
||||
let client = createConnection(realAddress[0], parseInt(realAddress[1] || "25565"), username)
|
||||
let password = process.argv[3] || ''
|
||||
let version = process.argv[4] || '1.12.2'
|
||||
let readAddress = process.argv[5] || '192.168.2.5:25577'
|
||||
let realAddress = readAddress.split(":")
|
||||
let address = realAddress[0]
|
||||
let port = parseInt(realAddress[1] || "25565")
|
||||
let client = commandLineCreateClient()
|
||||
|
||||
function createConnection(host: string, port: number, username: string) {
|
||||
function commandLineCreateClient() {
|
||||
return createConnection(address, port, username, password)
|
||||
}
|
||||
|
||||
function createConnection(host: string, port: number, username: string, password: string) {
|
||||
let client = createClient({
|
||||
version,
|
||||
host,
|
||||
port,
|
||||
username,
|
||||
skipValidation: true
|
||||
password,
|
||||
clientToken: 'd02c7f39-2376-45da-a5a5-50e24fa8b185',
|
||||
//@ts-ignore
|
||||
authServer: 'https://mcsso.yumc.pw/api/yggdrasil/authserver',
|
||||
sessionServer: 'https://mcsso.yumc.pw/api/yggdrasil/sessionserver'
|
||||
})
|
||||
|
||||
attachCommon(client)
|
||||
attachForge(client)
|
||||
attachEvents(client)
|
||||
return client;
|
||||
return client
|
||||
}
|
||||
|
||||
client.on('error', (error) => {
|
||||
console.log("Client Error", error)
|
||||
})
|
||||
|
||||
client.on('end', (resone) => {
|
||||
console.log("Client End Resone:", resone)
|
||||
client = createConnection('192.168.2.5', 25577, username)
|
||||
})
|
||||
function attachCommon(client) {
|
||||
client.on('error', (error) => {
|
||||
console.log("Client Error", error)
|
||||
})
|
||||
client.on('end', (resone) => {
|
||||
console.log("Client End Resone:", resone)
|
||||
if (`${resone}` != "SocketClosed") {
|
||||
setTimeout(() => {
|
||||
client = commandLineCreateClient()
|
||||
}, 500)
|
||||
} else {
|
||||
process.exit(0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const rl = createInterface({
|
||||
input: process.stdin,
|
||||
@@ -54,22 +73,22 @@ const rl = createInterface({
|
||||
rl.on('line', function (line) {
|
||||
switch (line) {
|
||||
case "":
|
||||
break;
|
||||
break
|
||||
case "eval":
|
||||
break;
|
||||
break
|
||||
case "write":
|
||||
break;
|
||||
break
|
||||
case "/respawn":
|
||||
client.write('client_command', { payload: 0 })
|
||||
break;
|
||||
break
|
||||
case "//reco":
|
||||
client.end("")
|
||||
client = createConnection('192.168.2.5', 25577, username)
|
||||
break;
|
||||
client = commandLineCreateClient()
|
||||
break
|
||||
case "//quit":
|
||||
console.info('Disconnected')
|
||||
client.end("")
|
||||
break;
|
||||
break
|
||||
case "//end":
|
||||
console.info('Forcibly ended client')
|
||||
process.exit(0)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/common",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.4",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,11 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.0",
|
||||
"@ccms/nashorn": "^0.9.4",
|
||||
"@javatypes/jdk": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/compile",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.4",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,6 +21,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/container",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.4",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,10 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.0",
|
||||
"@ccms/nashorn": "^0.9.4",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"inversify": "^5.0.1",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import "reflect-metadata"
|
||||
import { initContainer, getContainer } from './decorators'
|
||||
import { interfaces, Container } from 'inversify'
|
||||
import { interfaces, Container, inject, named } from 'inversify'
|
||||
import { fluentProvide } from 'inversify-binding-decorators'
|
||||
import { ioc } from "./constants"
|
||||
|
||||
@@ -59,9 +59,21 @@ export const JSClass = (className: string) => {
|
||||
* 自动注入实例由平台实现
|
||||
* @param className 类名
|
||||
*/
|
||||
export const Autowired = (className?: string | any) => {
|
||||
return function (target: any, propertyKey: string) {
|
||||
target[propertyKey] = getContainer().getNamed(ioc.Autowired, className || propertyKey)
|
||||
export const Autowired = (className?: any) => {
|
||||
return function (target: any, propertyKey: string, index?: number) {
|
||||
let container = getContainer()
|
||||
if (className instanceof Symbol || className instanceof Function) {
|
||||
return inject(className)(target, propertyKey, index)
|
||||
}
|
||||
let type = Reflect.getMetadata('design:type', target, propertyKey)
|
||||
if (type && type !== Object) {
|
||||
inject(type)(target, propertyKey, index)
|
||||
named(className || propertyKey)(target, propertyKey, index)
|
||||
} else if (container.isBound(ioc.Autowired)) {
|
||||
target[propertyKey] = container.getNamed(ioc.Autowired, className || propertyKey)
|
||||
} else {
|
||||
throw new Error(`No matching bindings found for target: ${target.constructor.name} type: ${type} named: ${className || propertyKey}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +82,7 @@ export const Autowired = (className?: string | any) => {
|
||||
* @param className 类名
|
||||
*/
|
||||
export const Resource = (resourceName?: string | any) => {
|
||||
return function (target: any, propertyKey: string) {
|
||||
return function (target: any, propertyKey: string, index?: number) {
|
||||
target[propertyKey] = getContainer().getNamed(ioc.Resource, resourceName || propertyKey)
|
||||
}
|
||||
}
|
||||
@@ -82,8 +94,18 @@ export const reduceMetadata = (ctx: interfaces.Context): any => {
|
||||
}, {})
|
||||
}
|
||||
|
||||
function initAutowired(container: Container) {
|
||||
container.bind(ioc.Autowired).toDynamicValue((ctx) => {
|
||||
var metadata: any = reduceMetadata(ctx)
|
||||
let key = Object.toString.call(metadata.named)
|
||||
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
|
||||
return undefined
|
||||
})
|
||||
}
|
||||
|
||||
export const DefaultContainer = new Container()
|
||||
initContainer(DefaultContainer)
|
||||
initAutowired(DefaultContainer)
|
||||
|
||||
export * from 'inversify'
|
||||
export * from './constants'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/core",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/container": "^0.9.4"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -49,10 +49,12 @@ class MiaoScriptCore {
|
||||
}
|
||||
|
||||
disable() {
|
||||
let disableStartTime = Date.now()
|
||||
console.i18n("ms.core.engine.disable")
|
||||
this.pluginManager.disable(this.pluginManager.getPlugins())
|
||||
this.taskManager.disable()
|
||||
process.exit(0)
|
||||
console.i18n("ms.core.engine.disable.finish", { version: 'v' + global.ScriptEngineVersion, time: (new Date().getTime() - disableStartTime) / 1000 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +88,7 @@ function detectServer(): constants.ServerType {
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
// @ts-ignore
|
||||
global.ScriptEngineVersion = require('../package.json').version
|
||||
try { engineLoad({ script: http.get("http://ms.yumc.pw/api/plugin/download/name/initialize"), name: 'core/initialize.js' }) } catch (error) { console.debug(error) }
|
||||
try {
|
||||
let corePackageStartTime = new Date().getTime()
|
||||
@@ -103,7 +105,7 @@ function initialize() {
|
||||
container.load(buildProviderModule())
|
||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
||||
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 })
|
||||
console.i18n("ms.core.engine.completed", { version: 'v' + global.ScriptEngineVersion, time: (Date.now() - global.ScriptEngineStartTime) / 1000 })
|
||||
return disable
|
||||
} catch (error) {
|
||||
console.i18n("ms.core.initialize.error", { error })
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/database",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript database package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,10 +22,10 @@
|
||||
"@javatypes/spring-jdbc": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/container": "^0.9.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,9 @@ ms.core.package.initialize: "初始化 MiaoScript 扩展 {scope}/core {scope}/{t
|
||||
ms.core.package.completed: "MiaoScript 扩展 {scope}/core {scope}/{type} {scope}/plugin 加载完成 耗时({time}s)"
|
||||
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
||||
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
||||
ms.core.engine.completed: "MiaoScript 脚本引擎 加载完毕... 耗时({time}s)!"
|
||||
ms.core.engine.disable: "关闭 MiaoScript 引擎..."
|
||||
ms.core.engine.completed: "MiaoScript 脚本引擎 {version} 加载完毕... 耗时({time}s)!"
|
||||
ms.core.engine.disable: "MiaoScript 关闭脚本引擎 请稍候..."
|
||||
ms.core.engine.disable.finish: "MiaoScript 脚本引擎 {version} 关闭完成... 耗时({time}s)!"
|
||||
ms.core.engine.disable.abnormal: "引擎异常启动或初始化未完成 跳过关闭流程..."
|
||||
|
||||
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/i18n",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.4",
|
||||
"description": "MiaoScript i18n package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,11 +19,11 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.0",
|
||||
"@ccms/nashorn": "^0.9.4",
|
||||
"@types/js-yaml": "^3.12.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "^3.14.0"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/keyvalue",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript keyvalue package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,18 +19,18 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/common": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/common": "^0.9.4",
|
||||
"@ccms/container": "^0.9.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.0",
|
||||
"@ccms/nashorn": "^0.9.4",
|
||||
"@javatypes/amqp-client": "^0.0.2",
|
||||
"@javatypes/spring-amqp": "^0.0.2",
|
||||
"@javatypes/spring-rabbit": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nashorn",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.4",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,6 +22,6 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,8 @@ declare global {
|
||||
logger: any
|
||||
debug: boolean
|
||||
level: string
|
||||
NashornEngineStartTime: number
|
||||
ScriptEngineVersion: string
|
||||
ScriptEngineStartTime: number
|
||||
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void
|
||||
noop: () => void
|
||||
console: Console
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nodejs",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.4",
|
||||
"description": "MiaoScript nodejs package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,10 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.0",
|
||||
"@ccms/nashorn": "^0.9.4",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/nukkit",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript nukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/nukkit-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/common": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/common": "^0.9.4",
|
||||
"@ccms/container": "^0.9.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,32 @@
|
||||
import { task, plugin } from '@ccms/api'
|
||||
import { inject, provideSingleton } from '@ccms/container';
|
||||
import { inject, provideSingleton } from '@ccms/container'
|
||||
|
||||
const NukkitRunnable = Java.type('cn.nukkit.scheduler.NukkitRunnable');
|
||||
const NukkitRunnable = Java.type('cn.nukkit.scheduler.NukkitRunnable')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class NukkitTaskManager implements task.TaskManager {
|
||||
export class NukkitTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any;
|
||||
private pluginInstance: any
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||
return new NukkitTask(this.pluginInstance, func);
|
||||
create0(func: Function): task.Task {
|
||||
return new NukkitTask(this.pluginInstance, func)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func()
|
||||
}
|
||||
disable() {
|
||||
disable0() {
|
||||
base.getInstance().getServer().getScheduler().cancelTask(this.pluginInstance)
|
||||
}
|
||||
}
|
||||
|
||||
export class NukkitTask extends task.Task {
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
submit0(...args: any[]): task.Cancelable {
|
||||
let run = new NukkitRunnable({ run: () => this.run(...args) })
|
||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||
if (this.interval) {
|
||||
run[funcName](this.plugin, this.laterTime, this.interval);
|
||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||
} else {
|
||||
run[funcName](this.plugin, this.laterTime);
|
||||
return run[funcName](this.plugin, this.laterTime)
|
||||
}
|
||||
return run;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/ployfill",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.4",
|
||||
"description": "MiaoScript ployfill package",
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
@@ -14,14 +14,14 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/i18n": "^0.9.2",
|
||||
"@ccms/nodejs": "^0.9.0",
|
||||
"@ccms/i18n": "^0.9.4",
|
||||
"@ccms/nodejs": "^0.9.4",
|
||||
"core-js": "^3.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.0",
|
||||
"@ccms/nashorn": "^0.9.4",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/plugin",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.6",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,13 +22,13 @@
|
||||
"@types/js-yaml": "^3.12.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/common": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2",
|
||||
"@ccms/i18n": "^0.9.2",
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/common": "^0.9.4",
|
||||
"@ccms/container": "^0.9.4",
|
||||
"@ccms/i18n": "^0.9.4",
|
||||
"js-yaml": "^3.14.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,35 @@
|
||||
import { command, plugin, server } from '@ccms/api'
|
||||
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||
import { provideSingleton, inject, Autowired } from '@ccms/container'
|
||||
import { getPluginCommandMetadata, getPluginTabCompleterMetadata } from './utils'
|
||||
|
||||
@provideSingleton(PluginCommandManager)
|
||||
export class PluginCommandManager {
|
||||
@inject(server.ServerChecker)
|
||||
private ServerChecker: server.ServerChecker
|
||||
@inject(command.Command)
|
||||
@Autowired()
|
||||
private CommandManager: command.Command
|
||||
@Autowired()
|
||||
private ServerChecker: server.ServerChecker
|
||||
|
||||
constructor() {
|
||||
process.on('plugin.before.enable', (plugin: plugin.Plugin) => this.registryCommand(plugin))
|
||||
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.unregistryCommand(plugin))
|
||||
process.on('plugin.before.enable', this.registryCommand.bind(this))
|
||||
process.on('plugin.after.disable', this.unregistryCommand.bind(this))
|
||||
}
|
||||
|
||||
private registryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||
for (const [_, cmd] of cmds) {
|
||||
let tab = tabs.get(cmd.name)
|
||||
if (!this.ServerChecker.check(cmd.servers)) { continue }
|
||||
this.CommandManager.on(pluginInstance, cmd.name, {
|
||||
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
||||
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
|
||||
})
|
||||
for (const cmd of cmds) {
|
||||
if (!this.ServerChecker.check(cmd.servers)) {
|
||||
console.debug(`[${pluginInstance.description.name}] ${cmd.target.constructor.name} incompatible command ${cmd.name} server(${cmd.servers}) ignore.`)
|
||||
continue
|
||||
}
|
||||
for (let command of [cmd.name, ...cmd.alias]) {
|
||||
this.CommandManager.on(pluginInstance, command, {
|
||||
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
||||
tab: tabs.has(command) ?
|
||||
pluginInstance[tabs.get(command).executor].bind(pluginInstance) :
|
||||
console.debug(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import * as yaml from 'js-yaml'
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
import { plugin } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
|
||||
import { interfaces } from './interfaces'
|
||||
import { getPluginConfigMetadata } from './utils'
|
||||
|
||||
export interface PluginConfigLoader {
|
||||
@@ -13,7 +16,7 @@ export class YamlPluginConfig implements PluginConfigLoader {
|
||||
return yaml.safeLoad(content)
|
||||
}
|
||||
dump(variable: any): string {
|
||||
return yaml.safeDump(variable, { skipInvalid: true })
|
||||
return yaml.safeDump(variable, { skipInvalid: true, lineWidth: 120 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,63 +25,68 @@ export class JsonPluginConfig implements PluginConfigLoader {
|
||||
return JSON.parse(content)
|
||||
}
|
||||
dump(variable: any): string {
|
||||
return JSON.stringify(variable)
|
||||
return JSON.stringify(variable, undefined, 4)
|
||||
}
|
||||
}
|
||||
|
||||
const configLoaderMap = new Map<string, PluginConfigLoader>()
|
||||
@provideSingleton(PluginConfigManager)
|
||||
export class PluginConfigManager {
|
||||
private configLoaderMap = new Map<string, PluginConfigLoader>()
|
||||
|
||||
export function getConfigLoader(format: string) {
|
||||
if (!configLoaderMap.has(format)) { throw new Error(`Unsupport config format ${format} !`) }
|
||||
return configLoaderMap.get(format)
|
||||
}
|
||||
constructor() {
|
||||
this.configLoaderMap.set("json", new JsonPluginConfig())
|
||||
let yaml = new YamlPluginConfig()
|
||||
this.configLoaderMap.set("yml", yaml)
|
||||
this.configLoaderMap.set("yaml", yaml)
|
||||
process.on('plugin.before.load', this.loadConfig.bind(this))
|
||||
process.on('plugin.after.disable', this.saveConfig.bind(this))
|
||||
}
|
||||
|
||||
function loadConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
try {
|
||||
let configFile = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, config.name + '.' + config.format)
|
||||
let configFactory = getConfigLoader(config.format)
|
||||
if (!fs.exists(configFile)) {
|
||||
base.save(configFile, configFactory.dump(plugin[config.variable]))
|
||||
console.i18n("ms.plugin.manager.config.save.default", { plugin: plugin.description.name, name: config.name, format: config.format })
|
||||
} else {
|
||||
Object.defineProperty(plugin, config.variable, { value: configFactory.load(base.read(configFile)) })
|
||||
plugin[config.variable].save = () => {
|
||||
let result = configFactory.dump(plugin[config.variable])
|
||||
base.save(configFile, result)
|
||||
console.debug(`[${plugin.description.name}] Save Config ${config.variable} to file ${configFile} result ${result}`)
|
||||
getConfigLoader(format: string) {
|
||||
if (!this.configLoaderMap.has(format)) { throw new Error(`Unsupport config format ${format} !`) }
|
||||
return this.configLoaderMap.get(format)
|
||||
}
|
||||
|
||||
loadConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
try {
|
||||
config.file = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, config.filename)
|
||||
let configLoader = this.getConfigLoader(config.format)
|
||||
if (!fs.exists(config.file)) {
|
||||
base.save(config.file, configLoader.dump(plugin[config.variable]))
|
||||
console.i18n("ms.plugin.manager.config.save.default", { plugin: plugin.description.name, name: config.name, format: config.format })
|
||||
} else {
|
||||
Object.defineProperty(plugin, config.variable, { value: configLoader.load(base.read(config.file)) })
|
||||
plugin[config.variable].save = () => this.saveConfig0(plugin, config)
|
||||
console.debug(`[${plugin.description.name}] Load Config ${config.variable} from file ${config.file} =>\n${JSON.stringify(plugin[config.variable], undefined, 4)}`)
|
||||
}
|
||||
console.debug(`[${plugin.description.name}] Load Config ${config.variable} from file ${configFile} result ${JSON.stringify(plugin[config.variable])}`)
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.config.load.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
|
||||
console.ex(error)
|
||||
}
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.config.load.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function saveConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
saveConfig(plugin: plugin.Plugin) {
|
||||
let configs = getPluginConfigMetadata(plugin)
|
||||
for (let [_, config] of configs) {
|
||||
this.saveConfig0(plugin, config)
|
||||
}
|
||||
}
|
||||
|
||||
private saveConfig0(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata) {
|
||||
try {
|
||||
let configFile = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, config.name + '.' + config.format)
|
||||
let configFactory = getConfigLoader(config.format)
|
||||
if (!config.readonly) { base.save(configFile, configFactory.dump(plugin[config.variable])) }
|
||||
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)
|
||||
let result = this.getConfigLoader(metadata.format).dump(plugin[metadata.variable])
|
||||
base.save(metadata.file, result)
|
||||
console.debug(`[${plugin.description.name}] Save Config ${metadata.variable} to file ${metadata.file} =>\n${result}`)
|
||||
return true
|
||||
} catch (error) {
|
||||
console.i18n("ms.plugin.manager.config.save.error", { plugin: plugin.description.name, name: config.name, format: config.format, error })
|
||||
console.i18n("ms.plugin.manager.config.save.error", { plugin: plugin.description.name, name: metadata.name, format: metadata.format, error })
|
||||
console.ex(error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function init() {
|
||||
configLoaderMap.set("json", new JsonPluginConfig())
|
||||
let yaml = new YamlPluginConfig()
|
||||
configLoaderMap.set("yml", yaml)
|
||||
configLoaderMap.set("yaml", yaml)
|
||||
process.on('plugin.before.load', loadConfig)
|
||||
process.on('plugin.after.load', saveConfig)
|
||||
}
|
||||
|
||||
init()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export const METADATA_KEY = {
|
||||
plugin: Symbol.for("@ccms/plugin:plugin"),
|
||||
souece: Symbol.for("@ccms/plugin:souece"),
|
||||
source: Symbol.for("@ccms/plugin:source"),
|
||||
cmd: Symbol.for("@ccms/plugin:cmd"),
|
||||
tab: Symbol.for("@ccms/plugin:tab"),
|
||||
listener: Symbol.for("@ccms/plugin:listener"),
|
||||
@@ -10,4 +10,4 @@ export const METADATA_KEY = {
|
||||
enable: Symbol.for("@ccms/plugin:stage:enable"),
|
||||
disable: Symbol.for("@ccms/plugin:stage:disable")
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export function plugin(metadata: pluginApi.PluginMetadata | any) {
|
||||
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect)
|
||||
const previousSources: Map<string, pluginApi.PluginMetadata> = getPluginSources()
|
||||
previousSources.set(metadata.source.toString(), metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.souece, previousSources, Reflect)
|
||||
Reflect.defineMetadata(METADATA_KEY.source, previousSources, Reflect)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,12 +30,11 @@ export function plugin(metadata: pluginApi.PluginMetadata | any) {
|
||||
export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key
|
||||
metadata.alias = metadata.alias || []
|
||||
metadata.target = target
|
||||
metadata.executor = key
|
||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginCommandMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor)
|
||||
Reflect.defineMetadata(METADATA_KEY.cmd, [metadata, ...getPluginCommandMetadata(target)], target.constructor)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,11 +46,13 @@ export function tab(metadata: interfaces.CommandMetadata = {}) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key)
|
||||
if (!metadata.name) { return }
|
||||
metadata.alias = metadata.alias || []
|
||||
metadata.target = target
|
||||
metadata.executor = key
|
||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginTabCompleterMetadata(target)
|
||||
let previousMetadata = getPluginTabCompleterMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
metadata.alias?.forEach((name) => previousMetadata.set(name, metadata))
|
||||
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor)
|
||||
}
|
||||
}
|
||||
@@ -65,8 +66,7 @@ export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
||||
metadata.name = metadata.name || key
|
||||
metadata.target = target
|
||||
metadata.executor = key
|
||||
const previousMetadata: interfaces.ListenerMetadata[] = getPluginListenerMetadata(target)
|
||||
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor)
|
||||
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...getPluginListenerMetadata(target)], target.constructor)
|
||||
Reflect.defineMetadata(METADATA_KEY.listener, metadata, target[key])
|
||||
}
|
||||
}
|
||||
@@ -77,9 +77,11 @@ export function config(metadata: interfaces.ConfigMetadata = {}) {
|
||||
metadata.variable = key
|
||||
metadata.version = metadata.version ?? 1
|
||||
metadata.format = metadata.format ?? 'yml'
|
||||
const previousMetadata: Map<string, interfaces.ConfigMetadata> = getPluginConfigMetadata(target)
|
||||
metadata.filename = metadata.filename ?? metadata.name + '.' + metadata.format
|
||||
let previousMetadata = getPluginConfigMetadata(target)
|
||||
previousMetadata.set(metadata.name, metadata)
|
||||
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor)
|
||||
Reflect.defineMetadata(METADATA_KEY.config, metadata, target[key])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,8 +90,7 @@ function stage(stage: string) {
|
||||
return function (target: any, key: string, value: any) {
|
||||
metadata.name = metadata.name || key
|
||||
metadata.executor = key
|
||||
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
|
||||
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor)
|
||||
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...getPluginStageMetadata(target, stage)], target.constructor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,31 @@
|
||||
import { event, plugin, server } from '@ccms/api'
|
||||
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||
import { provideSingleton, Autowired } from '@ccms/container'
|
||||
import { getPluginListenerMetadata } from './utils'
|
||||
|
||||
@provideSingleton(PluginEventManager)
|
||||
export class PluginEventManager {
|
||||
@inject(server.ServerChecker)
|
||||
private ServerChecker: server.ServerChecker
|
||||
@inject(event.Event)
|
||||
@Autowired()
|
||||
private EventManager: event.Event
|
||||
@Autowired()
|
||||
private ServerChecker: server.ServerChecker
|
||||
|
||||
constructor() {
|
||||
process.on('plugin.before.enable', (plugin: plugin.Plugin) => this.registryListener(plugin))
|
||||
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.unregistryListener(plugin))
|
||||
process.on('plugin.before.enable', this.registryListener.bind(this))
|
||||
process.on('plugin.after.disable', this.unregistryListener.bind(this))
|
||||
}
|
||||
|
||||
mapEventName() {
|
||||
return this.EventManager.mapEventName().toFixed(0)
|
||||
}
|
||||
|
||||
private registryListener(pluginInstance: plugin.Plugin) {
|
||||
let events = getPluginListenerMetadata(pluginInstance)
|
||||
for (const event of events) {
|
||||
// ignore space listener
|
||||
if (!this.ServerChecker.check(event.servers)) { continue }
|
||||
if (!this.ServerChecker.check(event.servers)) {
|
||||
console.debug(`[${pluginInstance.description.name}] ${event.target.constructor.name} incompatible event ${event.name} server(${event.servers}) ignore.`)
|
||||
continue
|
||||
}
|
||||
// here must bind this to pluginInstance
|
||||
let exec = event.target[event.executor]
|
||||
let execBinded = exec.bind(pluginInstance)
|
||||
|
||||
@@ -35,6 +35,10 @@ export namespace interfaces {
|
||||
executor?: string
|
||||
}
|
||||
export interface CommandMetadata extends ExecMetadata {
|
||||
/**
|
||||
* 命令别名
|
||||
*/
|
||||
alias?: string[]
|
||||
/**
|
||||
* 命令描述
|
||||
*/
|
||||
@@ -71,5 +75,13 @@ export namespace interfaces {
|
||||
* 是否为只读(关闭时将不会自动保存)
|
||||
*/
|
||||
readonly?: boolean
|
||||
/**
|
||||
* 配置文件名称
|
||||
*/
|
||||
filename?: string
|
||||
/**
|
||||
* 配置文件全路径
|
||||
*/
|
||||
file?: any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { plugin, server } from "@ccms/api"
|
||||
import { inject, ContainerInstance, Container, provideSingletonNamed } from "@ccms/container"
|
||||
import { inject, ContainerInstance, Container, provideSingletonNamed, Autowired } from "@ccms/container"
|
||||
|
||||
import { interfaces } from "../interfaces"
|
||||
import { getPluginStageMetadata, getPluginSources } from "../utils"
|
||||
@@ -11,7 +11,7 @@ export class IocLoader implements plugin.PluginLoader {
|
||||
type: string = LOADER_TYPE_NAME
|
||||
@inject(ContainerInstance)
|
||||
private container: Container
|
||||
@inject(server.ServerChecker)
|
||||
@Autowired()
|
||||
private serverChecker: server.ServerChecker
|
||||
|
||||
private pluginMetadataMap: Map<string, plugin.PluginMetadata>
|
||||
@@ -69,7 +69,7 @@ export class IocLoader implements plugin.PluginLoader {
|
||||
console.i18n('ms.plugin.manager.build.duplicate', { exists: pluginInstance.description.source, source: metadata.source })
|
||||
}
|
||||
this.container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
} catch{
|
||||
} catch {
|
||||
this.container.bind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import i18n from '@ccms/i18n'
|
||||
import { plugin, server, event } from '@ccms/api'
|
||||
import { inject, provideSingleton, Container, ContainerInstance } from '@ccms/container'
|
||||
import { inject, provideSingleton, Container, ContainerInstance, Autowired } from '@ccms/container'
|
||||
|
||||
import './config'
|
||||
import { interfaces } from './interfaces'
|
||||
import { PluginCommandManager } from './command'
|
||||
import { PluginTaskManager } from './task'
|
||||
import { PluginEventManager } from './event'
|
||||
import { PluginCommandManager } from './command'
|
||||
import { PluginConfigManager } from './config'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
|
||||
@@ -17,15 +19,18 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
private pluginInstance: any
|
||||
@inject(server.ServerType)
|
||||
private serverType: string
|
||||
@inject(event.Event)
|
||||
private EventManager: event.Event
|
||||
@inject(server.ServerChecker)
|
||||
|
||||
@Autowired()
|
||||
private serverChecker: server.ServerChecker
|
||||
|
||||
@inject(PluginCommandManager)
|
||||
private commandManager: PluginCommandManager
|
||||
@inject(PluginEventManager)
|
||||
@Autowired()
|
||||
private taskManager: PluginTaskManager
|
||||
@Autowired()
|
||||
private eventManager: PluginEventManager
|
||||
@Autowired()
|
||||
private configManager: PluginConfigManager
|
||||
@Autowired()
|
||||
private commandManager: PluginCommandManager
|
||||
|
||||
private initialized: boolean = false
|
||||
|
||||
@@ -43,15 +48,17 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
this.metadataMap = new Map()
|
||||
|
||||
// ignore unused
|
||||
this.commandManager
|
||||
this.taskManager
|
||||
this.eventManager
|
||||
this.configManager
|
||||
this.commandManager
|
||||
}
|
||||
|
||||
initialize() {
|
||||
if (this.pluginInstance === undefined) { throw new Error("Can't found Plugin Instance!") }
|
||||
if (this.initialized !== true) {
|
||||
console.i18n('ms.plugin.initialize', { plugin: this.pluginInstance, loader: Thread.currentThread().contextClassLoader })
|
||||
console.i18n('ms.plugin.event.map', { count: this.EventManager.mapEventName().toFixed(0), type: this.serverType })
|
||||
console.i18n('ms.plugin.event.map', { count: this.eventManager.mapEventName(), type: this.serverType })
|
||||
let pluginScanner = this.container.getAll<plugin.PluginScanner>(plugin.PluginScanner)
|
||||
pluginScanner.forEach((scanner) => {
|
||||
console.debug(`loading plugin sacnner ${scanner.type}...`)
|
||||
@@ -131,7 +138,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
||||
if (loader.require(loadMetadata).loaded) {
|
||||
loadMetadata.loader = loader
|
||||
let metadata = loadMetadata.metadata
|
||||
if (this.metadataMap.has(metadata.name)) {
|
||||
if (this.metadataMap.has(metadata.name) && this.instanceMap.has(metadata.name)) {
|
||||
let oldMetadata = this.metadataMap.get(metadata.name)
|
||||
throw new Error(`Plugin ${oldMetadata.name} is already load from ${oldMetadata.source}...`)
|
||||
}
|
||||
|
||||
16
packages/plugin/src/task.ts
Normal file
16
packages/plugin/src/task.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { plugin, task } from '@ccms/api'
|
||||
import { provideSingleton, Autowired } from '@ccms/container'
|
||||
|
||||
@provideSingleton(PluginTaskManager)
|
||||
export class PluginTaskManager {
|
||||
@Autowired()
|
||||
private taskManager: task.TaskManager
|
||||
|
||||
constructor() {
|
||||
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.cancelTask(plugin))
|
||||
}
|
||||
|
||||
private cancelTask(pluginInstance: plugin.Plugin) {
|
||||
this.taskManager.disable(pluginInstance)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ function getPlugin(name: string) {
|
||||
|
||||
function getPluginSources() {
|
||||
let pluginSources: Map<string, plugin.PluginMetadata> = Reflect.getMetadata(
|
||||
METADATA_KEY.souece,
|
||||
METADATA_KEY.source,
|
||||
Reflect
|
||||
) || pluginSourceCache
|
||||
return pluginSources
|
||||
@@ -37,10 +37,10 @@ function getPluginMetadata(target: any) {
|
||||
}
|
||||
|
||||
function getPluginCommandMetadata(target: any) {
|
||||
let commandMetadata: Map<string, interfaces.CommandMetadata> = Reflect.getMetadata(
|
||||
let commandMetadata: interfaces.CommandMetadata[] = Reflect.getMetadata(
|
||||
METADATA_KEY.cmd,
|
||||
target.constructor
|
||||
) || new Map<string, interfaces.CommandMetadata>()
|
||||
) || []
|
||||
return commandMetadata
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,12 @@
|
||||
- 玩家兑换公告
|
||||
- 配置兑换比例
|
||||
- 服务器信息查询
|
||||
|
||||
- 玩家请求授权
|
||||
- 玩家扫码
|
||||
- 玩家扫码确认
|
||||
- 玩家扫码兑换完成
|
||||
- 腐竹扫码确认
|
||||
- 腐竹扫码完成
|
||||
## 插件命令
|
||||
```
|
||||
>mrd
|
||||
@@ -36,15 +41,66 @@
|
||||
## 插件安装/配置
|
||||
|
||||
### 基础准备工作
|
||||
- 申请内测服务器账号
|
||||
- QQ搜索小程序 `圈云盒子` 并登录
|
||||
- 申请内测服务器账号 个人中心 => 配置面板 => 圈云盒子客服群 加群申请
|
||||
|
||||
### 服务器准备工作
|
||||
- 先安装 `MiaoScript` [站内地址]()
|
||||
- 执行 `mpm install MiaoReward`
|
||||
- 可以通过 Yum 快速安装 `/yum install MiaoScript`
|
||||
- 等待 MiaoScript 引擎启动完成(首次启动可能需要10-20秒 依赖于您的网络环境)
|
||||
- 执行 `/mspm install MiaoReward`
|
||||
|
||||
### 绑定服务器
|
||||
- 执行 `/mrd bind server`
|
||||
- 使用QQ扫码
|
||||
- 选择需要绑定的服务器
|
||||
- 完成绑定
|
||||
- 配置服务器兑换比例
|
||||
- 执行 `/mrd ratio 0.001` (最低为 1:0.0001)
|
||||
- 执行兑换比例确认指令
|
||||
- 执行 `/mrd server` 查看服务器信息
|
||||
- 如需绑定多台 可以直接复制绑定之后的 `MiaoScript/plugins/MiaoReward/config.yml` 文件到多台服务器上 然后 `/mrd reload` 重载插件
|
||||
|
||||
### QQ群配置
|
||||
- 打开小程序
|
||||
- 登录
|
||||
- 个人中心 => 设置面板 => 添加到群应用 => 选择你的QQ群
|
||||
- 配置群快捷栏 个人中心 => 设置面板 => 查看设置群快捷栏
|
||||
- 配置结果
|
||||
|
||||
### 玩家绑定账号
|
||||
- 执行 `/mrd bind`
|
||||
- 使用QQ扫码
|
||||
- 完成绑定
|
||||
|
||||
## 使用说明
|
||||
- 玩家可以通过下列方式获取喵币
|
||||
- 签到 5-10 喵币
|
||||
- 视频广告 5-15 喵币
|
||||
- 盒子广告 5-15 喵币
|
||||
- 获得的喵币可以在服务器兑换成对应的奖励
|
||||
- 腐竹可以在平台将喵币兑换成RMB(兑换比例请加群联系客服详谈)
|
||||
- 登录小程序后 个人中心 => 配置面板 => 圈云盒子客服群
|
||||
|
||||
## 配置文件
|
||||
|
||||
``` yaml
|
||||
# 服务器ID
|
||||
serverId: '16'
|
||||
# 服务器Token
|
||||
serverToken: d50d3f6e-2a59-460a-2b29-82b66c4bbf52
|
||||
# 兑换指令
|
||||
drawCommand: 'p give %player_name% %amount%'
|
||||
# 冷却时间
|
||||
drawCooldown: 300
|
||||
# 提示前缀
|
||||
prefix: '§6[§b广告系统§6]§r'
|
||||
```
|
||||
|
||||
## Roadmap
|
||||
- 绑定服务器(已完成)
|
||||
- 绑定玩家(已完成)
|
||||
- 兑换喵币(已完成)
|
||||
- 自助开通服务器(开发中)
|
||||
- 自助兑换RMB(开发中)
|
||||
- 自助提现(开发中)
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@ccms/plugins",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.6",
|
||||
"description": "MiaoScript plugins package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -25,11 +25,11 @@
|
||||
"@javatypes/tomcat": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2",
|
||||
"@ccms/plugin": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/container": "^0.9.4",
|
||||
"@ccms/plugin": "^0.9.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
/// <reference types="@javatypes/spigot-api" />
|
||||
/// <reference types="@javatypes/sponge-api" />
|
||||
|
||||
import { server, plugin as pluginApi, channel, constants } from '@ccms/api'
|
||||
import { inject, optional } from '@ccms/container';
|
||||
import { server, channel, constants, chat } from '@ccms/api'
|
||||
import { optional, Autowired } from '@ccms/container'
|
||||
import { plugin, interfaces, cmd, listener, tab, config, enable } from '@ccms/plugin'
|
||||
import Tellraw from '@ccms/common/dist/tellraw'
|
||||
|
||||
const ByteArrayInputStream = Java.type("java.io.ByteArrayInputStream");
|
||||
const ByteArrayOutputStream = Java.type("java.io.ByteArrayOutputStream");
|
||||
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
|
||||
const GZIPInputStream = Java.type("java.util.zip.GZIPInputStream");
|
||||
const GZIPOutputStream = Java.type("java.util.zip.GZIPOutputStream");
|
||||
const ByteArrayInputStream = Java.type("java.io.ByteArrayInputStream")
|
||||
const ByteArrayOutputStream = Java.type("java.io.ByteArrayOutputStream")
|
||||
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets")
|
||||
const GZIPInputStream = Java.type("java.util.zip.GZIPInputStream")
|
||||
const GZIPOutputStream = Java.type("java.util.zip.GZIPOutputStream")
|
||||
const BiConsumer = Java.type('java.util.function.BiConsumer')
|
||||
const ByteArray = Java.type("byte[]")
|
||||
|
||||
@@ -22,42 +22,45 @@ class MiaoMessage {
|
||||
private static MAX_MESSAGE_LENGTH = 32000;
|
||||
|
||||
private static copy(input, output) {
|
||||
let buffer = new ByteArray(1024);
|
||||
let n: number;
|
||||
let buffer = new ByteArray(1024)
|
||||
let n: number
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, n);
|
||||
output.write(buffer, 0, n)
|
||||
}
|
||||
input.close();
|
||||
output.close();
|
||||
input.close()
|
||||
output.close()
|
||||
}
|
||||
public static encode(input: any): any {
|
||||
return new MiaoMessage(input).encode();
|
||||
return new MiaoMessage(input).encode()
|
||||
}
|
||||
public static decode(input: any): MiaoMessage {
|
||||
let baos = new ByteArrayOutputStream();
|
||||
MiaoMessage.copy(new GZIPInputStream(new ByteArrayInputStream(input)), baos);
|
||||
return new MiaoMessage(baos.toString(StandardCharsets.UTF_8.name()));
|
||||
let baos = new ByteArrayOutputStream()
|
||||
MiaoMessage.copy(new GZIPInputStream(new ByteArrayInputStream(input)), baos)
|
||||
return new MiaoMessage(baos.toString(StandardCharsets.UTF_8.name()))
|
||||
}
|
||||
|
||||
// private String json;
|
||||
constructor(public json: any) { }
|
||||
|
||||
public encode(): any {
|
||||
let baos = new ByteArrayOutputStream();
|
||||
MiaoMessage.copy(new ByteArrayInputStream(this.json.getBytes(StandardCharsets.UTF_8)), new GZIPOutputStream(baos));
|
||||
if (baos.size() > MiaoMessage.MAX_MESSAGE_LENGTH) { return null; }
|
||||
return baos.toByteArray();
|
||||
let baos = new ByteArrayOutputStream()
|
||||
MiaoMessage.copy(new ByteArrayInputStream(this.json.getBytes(StandardCharsets.UTF_8)), new GZIPOutputStream(baos))
|
||||
if (baos.size() > MiaoMessage.MAX_MESSAGE_LENGTH) { return null }
|
||||
return baos.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
@plugin({ name: 'MiaoChat', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||
export class MiaoChat extends interfaces.Plugin {
|
||||
@inject(server.Server)
|
||||
@Autowired()
|
||||
private Server: server.Server
|
||||
@inject(channel.Channel)
|
||||
@optional() private Channel: channel.Channel
|
||||
@optional()
|
||||
@Autowired()
|
||||
private chat: chat.Chat
|
||||
@Autowired()
|
||||
private Channel: channel.Channel
|
||||
|
||||
private channelOff: { off: () => void };
|
||||
private channelOff: { off: () => void }
|
||||
|
||||
@config()
|
||||
private config = {
|
||||
@@ -129,34 +132,34 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
private chatFormats: any[];
|
||||
private styleFormats: any;
|
||||
private chatFormats: any[]
|
||||
private styleFormats: any
|
||||
// 用于匹配 '[xx]' 聊天格式
|
||||
private FORMAT_PATTERN = /[\[]([^\[\]]+)[\]]/ig;
|
||||
|
||||
private PlaceholderAPI: { setPlaceholders: (player: any, str: string) => string };
|
||||
private PlaceholderAPI: { setPlaceholders: (player: any, str: string) => string }
|
||||
|
||||
load() {
|
||||
this.chatFormats = Object.values(this.config.ChatFormats);
|
||||
this.chatFormats.sort(this.compare('index'));
|
||||
this.initFormat(this.chatFormats);
|
||||
this.styleFormats = this.config.StyleFormats;
|
||||
this.chatFormats = Object.values(this.config.ChatFormats)
|
||||
this.chatFormats.sort(this.compare('index'))
|
||||
this.initFormat(this.chatFormats)
|
||||
this.styleFormats = this.config.StyleFormats
|
||||
}
|
||||
|
||||
private compare(prop: string) {
|
||||
return function (obj1: { [x: string]: any; }, obj2: { [x: string]: any; }) {
|
||||
var val1 = obj1[prop];
|
||||
var val2 = obj2[prop];
|
||||
return function (obj1: { [x: string]: any }, obj2: { [x: string]: any }) {
|
||||
var val1 = obj1[prop]
|
||||
var val2 = obj2[prop]
|
||||
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
|
||||
val1 = Number(val1);
|
||||
val2 = Number(val2);
|
||||
val1 = Number(val1)
|
||||
val2 = Number(val2)
|
||||
}
|
||||
if (val1 < val2) {
|
||||
return -1;
|
||||
return -1
|
||||
} else if (val1 > val2) {
|
||||
return 1;
|
||||
return 1
|
||||
} else {
|
||||
return 0;
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -164,9 +167,14 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
enable() {
|
||||
this.PlaceholderAPI = {
|
||||
setPlaceholders: (player: any, string: string) => {
|
||||
return string;
|
||||
return string
|
||||
}
|
||||
}
|
||||
if (!this.chat) {
|
||||
this.logger.console('§4消息管理器注入失败 请检查当前服务器是否兼容...')
|
||||
this.AsyncPlayerChatEvent['off']()
|
||||
this.MessageChannelEvent$Chat['off']()
|
||||
}
|
||||
}
|
||||
|
||||
disable() {
|
||||
@@ -177,7 +185,7 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
// 尝试加载 Bukkit 的 PlaceholderAPI
|
||||
try {
|
||||
//@ts-ignore
|
||||
this.PlaceholderAPI = base.getClass("me.clip.placeholderapi.PlaceholderAPI").static;
|
||||
this.PlaceholderAPI = base.getClass("me.clip.placeholderapi.PlaceholderAPI").static
|
||||
this.logger.log('[PAPI] Found Bukkit PlaceholderAPI Hooking...')
|
||||
} catch (ex) {
|
||||
this.logger.console("§cCan't found me.clip.placeholderapi.PlaceholderAPI variable will not be replaced! Err: " + ex)
|
||||
@@ -187,14 +195,14 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
spongeenable() {
|
||||
// 尝试加载 Sponge 的 PlaceholderAPI
|
||||
try {
|
||||
var spongePapi = this.Server.getService('me.rojo8399.placeholderapi.PlaceholderService');
|
||||
var s = org.spongepowered.api.text.serializer.TextSerializers.formattingCode('§');
|
||||
var spongePapi = this.Server.getService('me.rojo8399.placeholderapi.PlaceholderService')
|
||||
var s = org.spongepowered.api.text.serializer.TextSerializers.formattingCode('§')
|
||||
if (spongePapi) {
|
||||
this.PlaceholderAPI = {
|
||||
setPlaceholders: (player: any, string: string) => {
|
||||
return s.serialize(spongePapi.replacePlaceholders(string, player, player));
|
||||
return s.serialize(spongePapi.replacePlaceholders(string, player, player))
|
||||
}
|
||||
};
|
||||
}
|
||||
this.logger.log('[PAPI] Found Sponge PlaceholderAPI Hooking...')
|
||||
}
|
||||
} catch (ex) {
|
||||
@@ -213,7 +221,7 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
this.channelOff = this.Channel?.listen(this, MiaoMessage.CHANNEL, (data, event: net.md_5.bungee.api.event.PluginMessageEvent) => {
|
||||
let bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||
if (event.getTag() == MiaoMessage.CHANNEL) {
|
||||
let origin = event.getSender().getAddress();
|
||||
let origin = event.getSender().getAddress()
|
||||
bungee.getServers().forEach(new BiConsumer({
|
||||
accept: (s, server) => {
|
||||
if (server.getAddress() != origin && server.getPlayers().size() > 0) {
|
||||
@@ -225,15 +233,15 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
})
|
||||
}
|
||||
|
||||
@cmd({ servers: ["bungee"] })
|
||||
@cmd({ servers: [constants.ServerType.Bungee] })
|
||||
mct(sender: any, command: string, args: string[]) {
|
||||
this.logger.log(sender, command, args);
|
||||
this.logger.log(sender, command, args)
|
||||
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||
}
|
||||
|
||||
@cmd({ servers: ["!bungee"] })
|
||||
@cmd({ servers: [`!${constants.ServerType.Bungee}`] })
|
||||
mchat(sender: any, command: string, args: string[]) {
|
||||
this.logger.log(sender, command, args);
|
||||
this.logger.log(sender, command, args)
|
||||
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||
}
|
||||
|
||||
@@ -241,104 +249,99 @@ export class MiaoChat extends interfaces.Plugin {
|
||||
tabmchat(_sender: any, _command: string, _args: string[]) {
|
||||
}
|
||||
|
||||
@listener({ servers: ['bukkit'] })
|
||||
@listener({ servers: [constants.ServerType.Bukkit] })
|
||||
AsyncPlayerChatEvent(event: org.bukkit.event.player.AsyncPlayerChatEvent) {
|
||||
this.sendChat(event.getPlayer(), event.getMessage(), function () {
|
||||
event.setCancelled(true);
|
||||
});
|
||||
this.sendChat(event.getPlayer(), event.getMessage(), () => event.setCancelled(true))
|
||||
}
|
||||
|
||||
@listener({ servers: ['sponge'] })
|
||||
@listener({ servers: [constants.ServerType.Sponge] })
|
||||
MessageChannelEvent$Chat(event: org.spongepowered.api.event.message.MessageChannelEvent.Chat) {
|
||||
//@ts-ignore
|
||||
var player = event.getCause().first(org.spongepowered.api.entity.living.player.Player.class).orElse(null);
|
||||
var player = event.getCause().first(org.spongepowered.api.entity.living.player.Player.class).orElse(null)
|
||||
if (player == null) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
var plain = event.getRawMessage().toPlain();
|
||||
var plain = event.getRawMessage().toPlain()
|
||||
if (plain.startsWith(Tellraw.duplicateChar)) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
this.sendChat(player, plain, function () {
|
||||
event.setMessageCancelled(true)
|
||||
});
|
||||
this.sendChat(player, plain, () => event.setMessageCancelled(true))
|
||||
}
|
||||
|
||||
initFormat(chatFormats: any[]) {
|
||||
chatFormats.forEach(chatFormat => {
|
||||
var chat_format_str = chatFormat.format;
|
||||
var temp = [];
|
||||
var r: any[];
|
||||
var chat_format_str = chatFormat.format
|
||||
var temp = []
|
||||
var r: any[]
|
||||
while (r = this.FORMAT_PATTERN.exec(chat_format_str)) {
|
||||
temp.push(r[1]);
|
||||
temp.push(r[1])
|
||||
}
|
||||
var format_list = [];
|
||||
var format_list = []
|
||||
temp.forEach(t => {
|
||||
var arr = chat_format_str.split('[' + t + ']', 2);
|
||||
var arr = chat_format_str.split('[' + t + ']', 2)
|
||||
if (arr[0]) {
|
||||
format_list.push(arr[0]);
|
||||
format_list.push(arr[0])
|
||||
}
|
||||
format_list.push(t);
|
||||
chat_format_str = arr[1];
|
||||
});
|
||||
format_list.push(t)
|
||||
chat_format_str = arr[1]
|
||||
})
|
||||
if (chat_format_str) {
|
||||
format_list.push(chat_format_str);
|
||||
format_list.push(chat_format_str)
|
||||
}
|
||||
chatFormat.format_list = format_list;
|
||||
chatFormat.format_list = format_list
|
||||
})
|
||||
}
|
||||
|
||||
sendChat(player: any, plain: string, callback: { (): void; }) {
|
||||
var chat_format = this.getChatFormat(player);
|
||||
sendChat(player: any, plain: string, callback: { (): void }) {
|
||||
var chat_format = this.getChatFormat(player)
|
||||
if (!chat_format) {
|
||||
console.debug('未获得用户', player.getName(), '的 ChatRule 跳过执行...');
|
||||
return;
|
||||
console.debug('未获得用户', player.getName(), '的 ChatRule 跳过执行...')
|
||||
return
|
||||
}
|
||||
callback();
|
||||
var tr = Tellraw.create();
|
||||
callback()
|
||||
var tr = Tellraw.create()
|
||||
chat_format.format_list.forEach((format) => {
|
||||
var style = this.styleFormats[format];
|
||||
var style = this.styleFormats[format]
|
||||
if (style) {
|
||||
tr.then(this.replace(player, style.text.replace(/&(\w)/g, '§$1')));
|
||||
tr.then(this.replace(player, style.text.replace(/&(\w)/g, '§$1')))
|
||||
if (style.hover) {
|
||||
tr.tip(this.replace(player, style.hover.join('\n')));
|
||||
tr.tip(this.replace(player, style.hover.join('\n')))
|
||||
}
|
||||
if (style.click && style.click.type && style.click.command) {
|
||||
var command = this.replace(player, style.click.command);
|
||||
var command = this.replace(player, style.click.command)
|
||||
switch (style.click.type.toUpperCase()) {
|
||||
case "COMMAND":
|
||||
tr.command(command);
|
||||
break;
|
||||
tr.command(command)
|
||||
break
|
||||
case "OPENURL":
|
||||
tr.link(command);
|
||||
break;
|
||||
tr.link(command)
|
||||
break
|
||||
case "SUGGEST":
|
||||
tr.suggest(command);
|
||||
break;
|
||||
tr.suggest(command)
|
||||
break
|
||||
default:
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tr.then(this.replace(player, format));
|
||||
tr.then(this.replace(player, format))
|
||||
}
|
||||
});
|
||||
})
|
||||
let json = tr.then(this.replace(player, plain)).json()
|
||||
this.sendChatAll(json)
|
||||
this.Channel?.send(player, MiaoMessage.CHANNEL, MiaoMessage.encode(json))
|
||||
}
|
||||
|
||||
sendChatAll(json: string) {
|
||||
this.Server.getOnlinePlayers().forEach(player => this.Server.sendJson(player, json))
|
||||
this.Server.getOnlinePlayers().forEach(player => this.chat.sendJson(player, json))
|
||||
}
|
||||
|
||||
getChatFormat(player: any) {
|
||||
for (var i in this.chatFormats) {
|
||||
var format = this.chatFormats[i];
|
||||
for (let format of this.chatFormats) {
|
||||
if (player.hasPermission(format.permission)) {
|
||||
return format;
|
||||
return format
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
replace(player: any, target: string) {
|
||||
|
||||
@@ -81,6 +81,7 @@ export class MiaoCoin extends interfaces.Plugin {
|
||||
}
|
||||
|
||||
disable() {
|
||||
// {"app":"com.tencent.autoreply","desc":"","view":"autoreply","ver":"0.0.0.1","prompt":"[动画表情]","meta":{"metadata":{"title":"点击蓝色字体有惊喜","buttons":[{"slot":1,"action_data":"我是傻逼","name":"点我","action":"notify"}],"type":"guest","token":"LAcV49xqyE57S17B8ZT6FU7odBveNMYJzux288tBD3c="}},"config":{"forward":1,"showSender":1}}
|
||||
}
|
||||
|
||||
@Cmd()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// <reference types="@ccms/nashorn" />
|
||||
|
||||
import { plugin as pluginApi, server, task, constants } 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 { inject, ContainerInstance, Container } from '@ccms/container'
|
||||
import io, { Server as SocketIOServer, Socket as SocketIOSocket } from '@ccms/websocket'
|
||||
@@ -27,6 +27,8 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
private serverType: string
|
||||
@inject(server.Server)
|
||||
private server: server.Server
|
||||
@inject(command.Command)
|
||||
private command: command.Command
|
||||
@inject(task.TaskManager)
|
||||
private task: task.TaskManager
|
||||
@inject(pluginApi.PluginManager)
|
||||
@@ -248,7 +250,7 @@ export class MiaoConsole extends interfaces.Plugin {
|
||||
client.emit('log', `§6命令: §b${cmd} §a执行成功!`)
|
||||
})
|
||||
client.on('tabComplate', (input, index, callback) => {
|
||||
callback && callback(this.server.tabComplete(this.server.getConsoleSender(), input, index))
|
||||
callback?.(this.command.tabComplete(this.server.getConsoleSender(), input, index))
|
||||
})
|
||||
client.on('exec', (code) => {
|
||||
try {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { constants, task, server, channel, chat } from "@ccms/api"
|
||||
import { constants, task, server, channel, chat, proxy } from "@ccms/api"
|
||||
import { JSPlugin, interfaces, Cmd, Tab, Listener, Config } from "@ccms/plugin"
|
||||
|
||||
import { QRCode, QRErrorCorrectLevel } from '@ccms/common/dist/qrcode'
|
||||
|
||||
import { inject, JSClass, optional } from '@ccms/container'
|
||||
import { Autowired, JSClass, optional } from '@ccms/container'
|
||||
import http from '@ccms/common/dist/http'
|
||||
|
||||
let MapView
|
||||
@@ -54,9 +54,9 @@ interface PlaceholderAPI {
|
||||
setPlaceholders: (player: any, str: string) => string
|
||||
}
|
||||
|
||||
@JSPlugin({ prefix: 'MRD', version: '1.2.0', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||
@JSPlugin({ prefix: 'MRD', version: '1.3.0', author: 'MiaoWoo', servers: [constants.ServerType.Bukkit], source: __filename })
|
||||
export class MiaoReward extends interfaces.Plugin {
|
||||
private serverInfo
|
||||
private serverInfo: any
|
||||
private cacheBindUuid = ''
|
||||
private zeroMapView = undefined
|
||||
private zeroMapRender: QRCodeRender = undefined
|
||||
@@ -67,14 +67,17 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
private bindingNotify = new java.util.HashSet<org.bukkit.entity.Player>()
|
||||
private drawCooldown = new Map<string, number>()
|
||||
|
||||
@inject(chat.Chat)
|
||||
@Autowired()
|
||||
private chat: chat.Chat
|
||||
@inject(server.Server)
|
||||
@Autowired()
|
||||
private server: server.Server
|
||||
@inject(task.TaskManager)
|
||||
@Autowired()
|
||||
private taskManager: task.TaskManager
|
||||
@inject(channel.Channel)
|
||||
@optional() private Channel: channel.Channel
|
||||
@optional()
|
||||
@Autowired()
|
||||
private channel: channel.Channel
|
||||
@Autowired()
|
||||
private bungee: proxy.BungeeCord
|
||||
|
||||
@Config()
|
||||
private config = {
|
||||
@@ -97,6 +100,10 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
this.config.prefix = this.config.prefix || '§6[§b广告系统§6]§r'
|
||||
this.config.drawCommand = this.config.drawCommand || 'p give %player_name% %amount%'
|
||||
this.config.drawCooldown = this.config.drawCooldown || 300
|
||||
this.updateServerInfo()
|
||||
}
|
||||
|
||||
private updateServerInfo(player?: any) {
|
||||
this.taskManager.create(() => {
|
||||
if (this.config.serverId) {
|
||||
let result = this.httpPost(`https://reward.yumc.pw/server/server`, {
|
||||
@@ -105,21 +112,61 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
})
|
||||
if (result.code == 200) {
|
||||
this.serverInfo = result.data
|
||||
if (player) this.bungee.for(player).forward("ALL", "MiaoReward", { type: "updateServerInfo", data: result.data }).send()
|
||||
}
|
||||
}
|
||||
}).async().submit()
|
||||
}
|
||||
|
||||
@JSClass('com.google.common.io.ByteStreams')
|
||||
private ByteStreams: any
|
||||
|
||||
enable() {
|
||||
this.initPlaceholderAPI()
|
||||
this.channelOff = this.Channel?.listen(this, 'BungeeCord', () => {
|
||||
this.isBungeeCord = true
|
||||
this.PlayerJoinEvent['off']()
|
||||
this.channelOff.off()
|
||||
this.initBungeeCord()
|
||||
this.initZeroMap()
|
||||
}
|
||||
|
||||
private initBungeeCord() {
|
||||
this.channelOff = this.channel?.listen(this, 'BungeeCord', (data) => {
|
||||
if (!this.isBungeeCord) {
|
||||
this.isBungeeCord = true
|
||||
this.PlayerJoinEvent['off']()
|
||||
}
|
||||
let input = this.ByteStreams.newDataInput(data)
|
||||
let subChannel = input.readUTF()
|
||||
switch (subChannel) {
|
||||
case "GetServer":
|
||||
this.isBungeeCord = true
|
||||
let serverName = input.readUTF()
|
||||
break
|
||||
case "MiaoReward":
|
||||
this.readForward(input)
|
||||
break
|
||||
}
|
||||
})
|
||||
let players = this.server.getOnlinePlayers()
|
||||
if (players.length) this.bungeeCordDetect(players[0])
|
||||
this.initZeroMap()
|
||||
}
|
||||
|
||||
cmdrun(sender: any, ...args: any[]) {
|
||||
try {
|
||||
let tfunc = new Function(`return '§a返回结果: §r'+ eval(${JSON.stringify(args.join(' '))});`)
|
||||
this.logger.sender(sender, tfunc.apply(this) + '')
|
||||
} catch (ex) {
|
||||
this.logger.sender(sender, this.logger.stack(ex))
|
||||
}
|
||||
}
|
||||
|
||||
private readForward(input) {
|
||||
let message = JSON.parse(input.readUTF())
|
||||
console.log(message)
|
||||
switch (message.type) {
|
||||
case "updateServerInfo":
|
||||
this.serverInfo = message.data
|
||||
console.console(this.config.prefix, '§6兑换比例已更新为:§a', message.data.ratio)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private initPlaceholderAPI() {
|
||||
@@ -140,15 +187,17 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
}
|
||||
|
||||
private initZeroMap() {
|
||||
this.zeroMapRender = new QRCodeRender()
|
||||
this.zeroMapView = Bukkit.getMap(0) || Bukkit.createMap(Bukkit.getWorlds()[0])
|
||||
this.zeroMapView.setScale(MapView.Scale.FARTHEST)
|
||||
this.zeroMapView.getRenderers().forEach(r => this.zeroMapView.removeRenderer(r))
|
||||
this.zeroMapView.addRenderer(this.zeroMapRender.getHandler())
|
||||
this.taskManager.create(() => {
|
||||
this.zeroMapRender = new QRCodeRender()
|
||||
this.zeroMapView = Bukkit.getMap(0) || Bukkit.createMap(Bukkit.getWorlds()[0])
|
||||
this.zeroMapView.setScale(MapView.Scale.FARTHEST)
|
||||
this.zeroMapView.getRenderers().forEach(r => this.zeroMapView.removeRenderer(r))
|
||||
this.zeroMapView.addRenderer(this.zeroMapRender.getHandler())
|
||||
}).submit()
|
||||
}
|
||||
|
||||
disable() {
|
||||
this.server.getOnlinePlayers().forEach(p => this.checkAndClear(p))
|
||||
Java.from(this.server.getOnlinePlayers()).forEach(p => this.checkAndClear(p))
|
||||
this.channelOff?.off()
|
||||
}
|
||||
|
||||
@@ -167,9 +216,10 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
|
||||
private scanAuth(sender: org.bukkit.entity.Player, scanType: string, scanObj: { title: string, content: string }, success: (token: string, user: any) => void, cancel?: () => void) {
|
||||
this.chat.sendTitle(sender, this.config.prefix, '§a正在获取授权二维码...')
|
||||
this.logger.sender(sender, '§a正在获取授权二维码...')
|
||||
let scan = this.httpPost('https://reward.yumc.pw/auth/scan', { ...scanObj, type: scanType })
|
||||
if (scan.code == 200) {
|
||||
let sync = { scaned: false, timeout: false }
|
||||
let sync = { scaned: false }
|
||||
this.taskManager.create(() => {
|
||||
let result = this.httpPost('https://reward.yumc.pw/auth/scanCheck', {
|
||||
token: scan.data.token,
|
||||
@@ -191,6 +241,9 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
} else if (result.data.status == "cancel") {
|
||||
this.chat.sendTitle(sender, '§c已取消授权')
|
||||
cancel?.()
|
||||
} else if (result.data.status == "scaned") {
|
||||
this.chat.sendTitle(sender, '§c授权操作超时')
|
||||
cancel?.()
|
||||
} else {
|
||||
this.chat.sendTitle(sender, "§c未知的结果", result.data.status)
|
||||
}
|
||||
@@ -212,14 +265,19 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
let bindUser = Bukkit.getPlayerExact(this.bindingUser)
|
||||
if (bindUser && bindUser.isOnline() && this.isQrCodeItem(bindUser.getItemInHand())[0]) {
|
||||
this.bindingNotify.add(sender)
|
||||
this.logger.sender(sender, "§c当前 §a" + this.bindingUser + " §c玩家正在扫码 §6请稍候 §e" + this.bindingLeftTime + "秒 §6后重试...")
|
||||
this.logger.sender(sender, [
|
||||
"§c当前 §a" + this.bindingUser + " §c玩家正在扫码",
|
||||
"§6请等待 §e" + this.bindingLeftTime + "秒 §6后重试...",
|
||||
"§a玩家操作完成后将会通知您继续操作..."
|
||||
])
|
||||
return true
|
||||
}
|
||||
}
|
||||
if (this.drawCooldown.has(sender.getName())) {
|
||||
if (this.drawCooldown.has(sender.getName()) && !sender.hasPermission('mrd.admin')) {
|
||||
let leftTime = cooldown - (Date.now() - this.drawCooldown.get(sender.getName())) / 1000
|
||||
if (leftTime > 0) {
|
||||
return this.logger.sender(sender, `§c扫码功能冷却中 剩余 ${leftTime} 秒!`)
|
||||
this.logger.sender(sender, `§c扫码功能冷却中 剩余 ${leftTime} 秒!`)
|
||||
return true
|
||||
}
|
||||
}
|
||||
this.drawCooldown.set(sender.getName(), Date.now())
|
||||
@@ -231,6 +289,7 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
|
||||
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()?.getType() !== Material.AIR) { return this.logger.sender(sender, "§c请空手执行此命令!") }
|
||||
if (server) {
|
||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4您没有配置服务器的权限!') }
|
||||
@@ -242,6 +301,7 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
}
|
||||
|
||||
cmddraw(sender: org.bukkit.entity.Player, amount: number) {
|
||||
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
||||
amount = Number(amount)
|
||||
if (!Number.isInteger(amount)) {
|
||||
return this.logger.sender(sender, '§4金额必须是数字!')
|
||||
@@ -253,7 +313,14 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
this.scanAuth(sender,
|
||||
'draw', {
|
||||
title: '兑换授权',
|
||||
content: "是否授权 " + this.serverInfo.name + " 服务器\n兑换 " + amount + " 喵币 到 " + sender.getName()
|
||||
content: [
|
||||
"是否授权 " + this.serverInfo.name + " 兑换喵币",
|
||||
"兑换玩家: " + sender.getName(),
|
||||
"兑换数量: " + amount,
|
||||
"兑换比例: " + parseFloat(this.serverInfo.ratio),
|
||||
"预计到帐: " + (amount * this.serverInfo.ratio).toFixed(0),
|
||||
"注意: 数据可能更新不及时 请以实际到账金额为准!"
|
||||
].join('\n')
|
||||
}, (token: string) => {
|
||||
this.drawCoin(sender, amount, token)
|
||||
})
|
||||
@@ -279,18 +346,18 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
this.taskManager.create(() => {
|
||||
let command = this.config.drawCommand.replace('%player_name%', sender.getName()).replace('%amount%', draw.data)
|
||||
if (!this.server.dispatchConsoleCommand(command)) {
|
||||
return this.sendError(sender, '§6执行命令 §3/' + command + ' §c可能存在异常')
|
||||
return this.sendError(sender, ...draw.msg.split('\n'), `§6执行结果: §4已扣除 §c${amount} §4喵币`, `§6执行命令: §3/${command} §c可能存在异常`)
|
||||
}
|
||||
this.logger.sender(sender, draw.msg.split('\n'))
|
||||
this.sendBoardcast(sender, `${this.config.prefix}§6玩家 §b${sender.getName()} §6成功将 §a${amount}喵币 §6兑换成 §c${draw.data}点券!`)
|
||||
this.sendBoardcast(sender, `${this.config.prefix}§c/mrd help §b查看广告系统帮助 §6快来一起看广告赚点券吧!`)
|
||||
this.sendBroadcast(sender, `${this.config.prefix}§6玩家 §b${sender.getName()} §6成功将 §a${amount}喵币 §6兑换成 §c${draw.data}点券!`)
|
||||
this.sendBroadcast(sender, `${this.config.prefix}§c/mrd help §b查看广告系统帮助 §6快来一起看广告赚点券吧!`)
|
||||
}).submit()
|
||||
}
|
||||
|
||||
private sendError(sender, error) {
|
||||
private sendError(sender: any, ...error: string[]) {
|
||||
return this.logger.sender(sender, [
|
||||
`§c========== ${this.config.prefix}§4兑换异常 §c==========`,
|
||||
error,
|
||||
...error,
|
||||
`§6异常账号: §b${sender.getName()}`,
|
||||
`§6异常时间: §a${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,
|
||||
`§c如果喵币被扣除且未得到奖励 请截图发往QQ群!`,
|
||||
@@ -313,7 +380,7 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
`§6====== ${this.config.prefix} §a喵币兑换排行 §6======`,
|
||||
]
|
||||
if (boardcast) {
|
||||
ranks.forEach(l => this.sendBoardcast(sender, l))
|
||||
ranks.forEach(l => this.sendBroadcast(sender, l))
|
||||
} else {
|
||||
this.logger.sender(sender, ranks)
|
||||
}
|
||||
@@ -338,43 +405,58 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
])
|
||||
}
|
||||
|
||||
cmdratio(sender: any, ratio: number, confirm: string) {
|
||||
cmdratio(sender: any, ratioStr: string, confirm: string) {
|
||||
if (!sender.isOp()) { return this.logger.sender(sender, '§4你没有此命令的权限!') }
|
||||
let mbr = (1 / ratio).toFixed(4)
|
||||
if (!sender.getItemInHand) { return this.logger.sender(sender, '§c手持物品检测异常 请检查是否在客户端执行命令!') }
|
||||
let [ratio, mbr, msg] = this.ratio2string(ratioStr)
|
||||
if (!confirm) {
|
||||
return this.logger.sender(sender, [
|
||||
'§4警告: 您正在设置服务器喵币/点券兑换比例 设置后将实时生效!',
|
||||
`§6您设置的兑换比例为 §c${ratio} §6=> §a${mbr}喵币 §6兑换 §c1点券`,
|
||||
`§6您设置的兑换比例为 ` + msg,
|
||||
`§6玩家至少需要 §a${mbr}喵币 §6才可以兑换点券!`,
|
||||
`§6请执行 §b/mrd ratio §c${ratio} §econfirm §c确认修改!`
|
||||
])
|
||||
}
|
||||
if (confirm != 'confirm') return this.logger.sender(sender, `§6请执行 §b/mrd ratio §c${ratio} §econfirm §c确认修改!`)
|
||||
let result = this.httpPost(`https://reward.yumc.pw/server/ratio`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken,
|
||||
ratio
|
||||
if (this.bindCheck(sender, 60)) return
|
||||
this.scanAuth(sender, "ratio", {
|
||||
title: `是否授权 ${this.serverInfo.name} 调整兑换比例`,
|
||||
content: [
|
||||
`操作玩家: ${sender.getName()}`,
|
||||
`调整前: ${this.serverInfo.ratio}`,
|
||||
`调整后: ${msg.replace(/§./ig, '')}`,
|
||||
'调整结果实时生效!',
|
||||
'跨服端 将自动同步比例!',
|
||||
'非跨服端 请重载插件同步比例!'
|
||||
].join('\n')
|
||||
}, (token) => {
|
||||
let result = this.httpPost(`https://reward.yumc.pw/server/ratio`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken,
|
||||
ratio,
|
||||
userToken: token
|
||||
})
|
||||
if (result.code !== 200) {
|
||||
return this.logger.sender(sender, `§4操作异常 §6服务器返回: §c${result.msg}`)
|
||||
}
|
||||
this.logger.sender(sender, `§a操作成功 §6服务器返回: §a${result.msg}`)
|
||||
this.updateServerInfo(sender)
|
||||
this.sendBroadcast(sender, `${this.config.prefix} §6当前兑换比例已调整为 ` + msg)
|
||||
})
|
||||
if (result.code !== 200) {
|
||||
return this.logger.sender(sender, `§4操作异常 §6服务器返回: §c${result.msg}`)
|
||||
}
|
||||
this.logger.sender(sender, `§a操作成功 §6服务器返回: §a${result.msg}`)
|
||||
this.sendBoardcast(sender, `${this.config.prefix} §6当前兑换比例已调整为 §c${ratio} §6=> §a${mbr}喵币 §6兑换 §c1点券!`)
|
||||
}
|
||||
|
||||
@JSClass('java.io.ByteArrayOutputStream')
|
||||
private ByteArrayOutputStream
|
||||
@JSClass('java.io.DataOutputStream')
|
||||
private DataOutputStream
|
||||
private ratio2string(ratio) {
|
||||
ratio = parseFloat(ratio)
|
||||
if (ratio > 1) {
|
||||
return [ratio, 1, `§c${ratio} §6就是 §a1喵币 §6=> §c${ratio}点券!`]
|
||||
}
|
||||
let mbr = Math.round(1 / ratio * 10000) / 10000
|
||||
return [ratio, mbr, `§c${ratio} §6就是 §a${mbr}喵币 §6=> §c1点券!`]
|
||||
}
|
||||
|
||||
private sendBoardcast(player, message) {
|
||||
private sendBroadcast(player, message) {
|
||||
if (!this.isBungeeCord) { return org.bukkit.Bukkit.broadcastMessage(message) }
|
||||
let byteArray = new this.ByteArrayOutputStream()
|
||||
let out = new this.DataOutputStream(byteArray)
|
||||
out.writeUTF("Message")
|
||||
out.writeUTF("ALL")
|
||||
out.writeUTF(message)
|
||||
player.sendPluginMessage(base.getInstance(), "BungeeCord", byteArray.toByteArray())
|
||||
this.bungee.for(player).broadcast(message).send()
|
||||
}
|
||||
|
||||
private bindServer(sender: org.bukkit.entity.Player) {
|
||||
@@ -393,9 +475,9 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
if (check.code == 200) {
|
||||
this.config.serverId = check.data.serverId
|
||||
this.config.serverToken = check.data.serverToken
|
||||
// @ts-ignore
|
||||
this.config.save()
|
||||
this.config['save']()
|
||||
this.logger.sender(sender, '§a已成功绑定服务器: §b' + check.data.serverName)
|
||||
this.updateServerInfo()
|
||||
}
|
||||
sync.scaned = true
|
||||
}).async().submit()
|
||||
@@ -453,6 +535,7 @@ export class MiaoReward extends interfaces.Plugin {
|
||||
}
|
||||
|
||||
private queryUser(sender: org.bukkit.entity.Player, sync = false) {
|
||||
if (!this.config.serverId || !this.config.serverToken) { return this.logger.sender(sender, '§4当前服务器尚未配置绑定ID 请联系腐竹进行配置!') }
|
||||
return this.httpPost(`https://reward.yumc.pw/server/queryUser`, {
|
||||
id: this.config.serverId,
|
||||
token: this.config.serverToken,
|
||||
@@ -589,10 +672,7 @@ CAST TIME : ${Date.now() - startTime}`)
|
||||
|
||||
private bungeeCordDetect(player) {
|
||||
if (this.isBungeeCord === undefined && player) {
|
||||
let byteArray = new this.ByteArrayOutputStream()
|
||||
let out = new this.DataOutputStream(byteArray)
|
||||
out.writeUTF("GetServer")
|
||||
player.sendPluginMessage(base.getInstance(), "BungeeCord", byteArray.toByteArray())
|
||||
this.bungee.for(player).getServer().send()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -606,7 +686,6 @@ CAST TIME : ${Date.now() - startTime}`)
|
||||
let [cancelled, id] = this.isQrCodeItem(event.getItemDrop().getItemStack())
|
||||
if (id != null && id != undefined && cancelled) {
|
||||
event.getItemDrop().remove()
|
||||
this.cancelTask(event.getPlayer())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -616,7 +695,6 @@ CAST TIME : ${Date.now() - startTime}`)
|
||||
let [cancelled, id] = this.isQrCodeItem(inv.getItem(event.getPreviousSlot() as any))
|
||||
if (id != null && id != undefined && cancelled) {
|
||||
inv.setItem(event.getPreviousSlot(), null)
|
||||
this.cancelTask(event.getPlayer())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -626,7 +704,6 @@ CAST TIME : ${Date.now() - startTime}`)
|
||||
let [cancelled, id] = this.isQrCodeItem(item)
|
||||
if (id != null && id != undefined && cancelled) {
|
||||
event.getInventory().setItem(event.getSlot(), null)
|
||||
this.cancelTask(event.getWhoClicked())
|
||||
event.setCancelled(true)
|
||||
}
|
||||
}
|
||||
@@ -637,9 +714,10 @@ CAST TIME : ${Date.now() - startTime}`)
|
||||
}
|
||||
|
||||
private cancelTask(player) {
|
||||
console.ex(new Error())
|
||||
if (!this.isBinding) return
|
||||
this.isBinding = false
|
||||
this.bindingTask.cancel()
|
||||
this.bindingTask = undefined
|
||||
this.bindingUser = 'unknow'
|
||||
this.checkAndClear(player)
|
||||
this.chat.sendActionBar(player, "")
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { plugin as pluginApi, task, server, plugin, channel, constants } from '@ccms/api'
|
||||
|
||||
import { plugin as pluginApi, task, server, channel, constants, proxy } from '@ccms/api'
|
||||
import { Translate } from '@ccms/i18n'
|
||||
import { inject, DefaultContainer as container, optional, JSClass } from '@ccms/container'
|
||||
import { DefaultContainer as container, JSClass, Autowired } from '@ccms/container'
|
||||
import { interfaces, JSPlugin, Cmd, Tab, enable, Listener, disable } from '@ccms/plugin'
|
||||
|
||||
import * as fs from '@ccms/common/dist/fs'
|
||||
@@ -10,16 +9,16 @@ import http from '@ccms/common/dist/http'
|
||||
|
||||
let help = [
|
||||
'§6========= §6[§aMiaoScriptPackageManager§6] 帮助 §aBy §bMiaoWoo §6=========',
|
||||
'§6/mpm §ainstall §e<插件名称> §6- §3安装仓库插件',
|
||||
'§6/mpm §aload §e<插件名称> §6- §3安装本地插件',
|
||||
'§6/mpm §aunload §e<插件名称> §6- §3卸载已安装插件',
|
||||
'§6/mpm §areload §e<插件名称> §6- §3重载已安装插件(无名称则重载自身)',
|
||||
'§6/mpm §alist [i] §6- §3列出仓库插件[已安装的插件]',
|
||||
'§6/mpm §aupdate §e[插件名称] §6- §3更新插件(无名称则更新源)',
|
||||
'§6/mpm §aupgrade §e[插件名称] §6- §3升级插件/框架(§4无名称则升级框架§3)',
|
||||
'§6/mpm §arun §e<JS代码> §6- §3运行JS代码',
|
||||
'§6/mpm §adeploy §e<插件名称> §6- §3发布插件',
|
||||
'§6/mpm §crestart §6- §4重启MiaoScript脚本引擎'
|
||||
'§6/mspm §ainstall §e<插件名称> §6- §3安装仓库插件',
|
||||
'§6/mspm §aload §e<插件名称> §6- §3安装本地插件',
|
||||
'§6/mspm §aunload §e<插件名称> §6- §3卸载已安装插件',
|
||||
'§6/mspm §areload §e<插件名称> §6- §3重载已安装插件(无名称则重载自身)',
|
||||
'§6/mspm §alist [i] §6- §3列出仓库插件[已安装的插件]',
|
||||
'§6/mspm §aupdate §e[插件名称] §6- §3更新插件(无名称则更新源)',
|
||||
'§6/mspm §aupgrade §e[插件名称] §6- §3升级插件/框架(§4无名称则升级框架§3)',
|
||||
'§6/mspm §arun §e<JS代码> §6- §3运行JS代码',
|
||||
'§6/mspm §adeploy §e<插件名称> §6- §3发布插件',
|
||||
'§6/mspm §crestart §6- §4重启MiaoScript脚本引擎'
|
||||
]
|
||||
|
||||
let langMap = {
|
||||
@@ -27,25 +26,35 @@ let langMap = {
|
||||
'main.command.help.tip': '§6请执行 §b/{command} §ahelp §6查看帮助!',
|
||||
'main.command.no.permission': '§c你没有此命令的权限!',
|
||||
'list.install.header': '§6当前 §bMiaoScript §6已安装下列插件:',
|
||||
'list.install.body': '§6插件名称: §b{name}\n§6版本: §a{version}\n§6作者: §3{author}\n§6来源: §c{from}',
|
||||
'list.install.body': `§6┌插件名称: §b{name}
|
||||
§6├版本: §a{version}
|
||||
§6├作者: §3{author}
|
||||
§6└来源: §c{from}`,
|
||||
'list.header': '§6当前 §bMiaoScriptPackageCenter §6中存在下列插件:',
|
||||
'list.body': '§6插件名称: §b{name}\n§6版本: §a{version}\n§6作者: §3{author}\n§6更新时间: §9{updated_at}',
|
||||
'list.body': `§6┌插件名称: §b{name}
|
||||
§6├版本: §a{version}
|
||||
§6├作者: §3{author}
|
||||
§6└更新时间: §9{updated_at}`,
|
||||
'plugin.not.exists': '§6插件 §b{name} §c不存在!',
|
||||
'plugin.unload.finish': '§6插件 §b{name} §a已卸载!',
|
||||
'plugin.reload.finish': '§6插件 §b{name} §a重载完成!',
|
||||
'plugin.unload.start': '§c开始卸载 §6插件 §b{name} §6版本 §3{version}!',
|
||||
'plugin.unload.finish': '§6插件 §b{name} §6版本 §3{version} §a已卸载!',
|
||||
'plugin.reload.start': '§a开始重载 §6插件 §b{name} §6版本 §3{version}!',
|
||||
'plugin.reload.finish': '§6插件 §b{name} §6版本 §3{version} §a重载完成!',
|
||||
'plugin.name.empty': '§c请输入插件名称!',
|
||||
'cloud.update.finish': '§6成功从 §aMiaoScriptPackageCenter §6获取到 §a{length} §6个插件!',
|
||||
'cloud.not.exists': '§6当前 §aMiaoScriptPackageCenter §c不存在 §a{name} §c插件!',
|
||||
'cloud.update.exists': '§6插件 §b{name} §a发现新版本 §3{new_version} §6当前版本 §3{old_version}!',
|
||||
'download.start': '§6开始下载插件: §b{name}',
|
||||
'download.start': '§6开始下载插件: §b{name} §6版本 §3{version}',
|
||||
'download.url': '§6插件下载地址: §b{url}',
|
||||
'download.finish': '§6插件 §b{name} §a下载完毕 开始加载 ...',
|
||||
'install.finish': '§6插件 §b{name} §a安装成功!',
|
||||
'update.finish': '§6插件 §b{name} §a更新成功!',
|
||||
'upgrade.confirm': '§6您正在尝试升级 §bMiaoScript §c核心 §6请执行 §b/mpm §aupgrade §cconfirm §6确认执行!',
|
||||
'download.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更新成功!',
|
||||
'upgrade.confirm': '§6您正在尝试更新 §bMiaoScript §c核心 §6请执行 §b/mpm §aupgrade §cconfirm §6确认执行!',
|
||||
'upgrade.failed': '§6尝试热更新 §bMiaoScript §c核心 §4失败! §6请重启服务器完成更新...',
|
||||
'deploy.token.not.exists': '§4请先配置发布Token!',
|
||||
'deploy.success': '§6插件 §b{name} §a发布成功! §6服务器返回: §a{msg}',
|
||||
'deploy.fail': '§6插件 §b{name} §c发布失败! §6服务器返回: §c{msg}',
|
||||
'deploy.success': '§6插件 §b{name} §6版本 §3{version} §a发布成功! §6服务器返回: §a{msg}',
|
||||
'deploy.fail': '§6插件 §b{name} §6版本 §3{version} §c发布失败! §6服务器返回: §c{msg}',
|
||||
'prun.script': '§6指定插件:§b {name}',
|
||||
'run.script': '§b运行脚本:§r {script}',
|
||||
'run.result': '§a返回结果:§r {result}',
|
||||
'run.noresult': '§4没有返回结果!',
|
||||
@@ -53,32 +62,72 @@ let langMap = {
|
||||
|
||||
let fallbackMap = langMap
|
||||
|
||||
@JSPlugin({ prefix: 'PM', version: '1.2.0', author: 'MiaoWoo', source: __filename })
|
||||
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
@inject(plugin.PluginManager)
|
||||
private pluginManager: pluginApi.PluginManager
|
||||
@inject(task.TaskManager)
|
||||
private taskManager: task.TaskManager
|
||||
@inject(server.ServerType)
|
||||
private serverType: string
|
||||
@inject(server.Server)
|
||||
private server: server.Server
|
||||
@inject(pluginApi.PluginFolder)
|
||||
private pluginFolder: string
|
||||
@inject(channel.Channel)
|
||||
@optional() private channel: channel.Channel
|
||||
class FakeSender {
|
||||
private _proxy
|
||||
private name: string
|
||||
private plugin: MiaoScriptPackageManager
|
||||
constructor(name: string, plugin: MiaoScriptPackageManager, superclass: any) {
|
||||
this.name = name
|
||||
this.plugin = plugin
|
||||
let FakeSenderAdapter = Java.extend(superclass, {
|
||||
getName: () => this.name,
|
||||
isOp: () => true,
|
||||
hasPermission: () => true,
|
||||
sendMessage: (message) => this.sendMessage(message)
|
||||
})
|
||||
this._proxy = new FakeSenderAdapter()
|
||||
}
|
||||
|
||||
sendMessage(message) {
|
||||
return this.plugin.sendBungeeCordMessage(this.name, `§6[§3BPM§6][§a${this.plugin.serverName}§6] ${message}`)
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this._proxy
|
||||
}
|
||||
}
|
||||
|
||||
class BukkitFakeSender extends FakeSender {
|
||||
constructor(name: string, plugin: MiaoScriptPackageManager) {
|
||||
super(name, plugin, Java.type('org.bukkit.command.CommandSender'))
|
||||
}
|
||||
}
|
||||
|
||||
class SpongeFakeSender extends FakeSender {
|
||||
constructor(name: string, plugin: MiaoScriptPackageManager) {
|
||||
super(name, plugin, Java.type('org.spongepowered.api.command.CommandSource'))
|
||||
}
|
||||
|
||||
sendMessage(message) {
|
||||
return super.sendMessage(message.content)
|
||||
}
|
||||
}
|
||||
|
||||
@JSPlugin({ prefix: 'PM', version: '1.3.0', author: 'MiaoWoo', source: __filename })
|
||||
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
@Autowired()
|
||||
private pluginManager: pluginApi.PluginManager
|
||||
@Autowired()
|
||||
private taskManager: task.TaskManager
|
||||
@Autowired(server.ServerType)
|
||||
private serverType: string
|
||||
@Autowired()
|
||||
private server: server.Server
|
||||
@Autowired(pluginApi.PluginFolder)
|
||||
private pluginFolder: string
|
||||
@Autowired()
|
||||
private channel: channel.Channel
|
||||
@Autowired()
|
||||
private bungee: proxy.BungeeCord
|
||||
|
||||
@JSClass('java.io.ByteArrayOutputStream')
|
||||
private ByteArrayOutputStream: any
|
||||
@JSClass('java.io.DataOutputStream')
|
||||
private DataOutputStream: any
|
||||
@JSClass('com.google.common.io.ByteStreams')
|
||||
private ByteStreams: any
|
||||
|
||||
private packageCache: any[] = [];
|
||||
private packageNameCache: string[] = [];
|
||||
|
||||
private serverName: string
|
||||
private isBungeeCord = false
|
||||
public serverName: string
|
||||
private translate: Translate
|
||||
private channelOff: { off: () => void }
|
||||
|
||||
@@ -97,6 +146,7 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
let subChannel = input.readUTF()
|
||||
switch (subChannel) {
|
||||
case "GetServer":
|
||||
this.isBungeeCord = true
|
||||
this.serverName = input.readUTF()
|
||||
break
|
||||
case "MiaoScriptPackageManager":
|
||||
@@ -115,27 +165,30 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
|
||||
private bungeeCordDetect(player) {
|
||||
if (player) {
|
||||
let byteArray = new this.ByteArrayOutputStream()
|
||||
let out = new this.DataOutputStream(byteArray)
|
||||
out.writeUTF("GetServer")
|
||||
this.channel.send(player, "BungeeCord", byteArray.toByteArray())
|
||||
this.bungee.for(player).getServer().send()
|
||||
}
|
||||
}
|
||||
private bungeeCordForward(player, command) {
|
||||
if (player) {
|
||||
let byteArray = new this.ByteArrayOutputStream()
|
||||
let out = new this.DataOutputStream(byteArray)
|
||||
out.writeUTF("Forward")
|
||||
out.writeUTF("ALL")
|
||||
out.writeUTF("MiaoScriptPackageManager")
|
||||
out.writeUTF(JSON.stringify(command))
|
||||
this.channel.send(player, "BungeeCord", byteArray.toByteArray())
|
||||
this.bungee.for(player).forward("ALL", "MiaoScriptPackageManager", command).send()
|
||||
}
|
||||
}
|
||||
private readForward(input) {
|
||||
let message = JSON.parse(input.readUTF())
|
||||
this.taskManager.create(() => this.main(this.server.getConsoleSender(), message.command, message.args)).async().submit()
|
||||
this.sendBungeeCordMessage(message.sender, `§6[§cMS§6][§bPM§6] [§3BPM§6][§a${this.serverName}§6] §6命令 §b/mpm ${message.args?.join?.(' ')} §a执行成功!`)
|
||||
let fakeSender = this.getProxySender(message.sender)
|
||||
this.taskManager.create(() => this.main(fakeSender, message.command, message.args)).async().submit()
|
||||
this.logger.sender(fakeSender, `§6命令 §b/mpm ${message.args?.join?.(' ')} §a执行成功!`)
|
||||
}
|
||||
|
||||
private getProxySender(name: string) {
|
||||
switch (this.serverType) {
|
||||
case constants.ServerType.Bukkit:
|
||||
return new BukkitFakeSender(name, this).getHandler()
|
||||
case constants.ServerType.Sponge:
|
||||
return new SpongeFakeSender(name, this).getHandler()
|
||||
default:
|
||||
return this.server.getConsoleSender()
|
||||
}
|
||||
}
|
||||
|
||||
@Listener({ servers: [constants.ServerType.Bukkit] })
|
||||
@@ -154,15 +207,10 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
private sendBungeeCordMessage(sender, message) {
|
||||
sendBungeeCordMessage(sender, message) {
|
||||
let players = this.server.getOnlinePlayers()
|
||||
if (players.length) {
|
||||
let byteArray = new this.ByteArrayOutputStream()
|
||||
let out = new this.DataOutputStream(byteArray)
|
||||
out.writeUTF("Message")
|
||||
out.writeUTF(sender)
|
||||
out.writeUTF(message)
|
||||
this.channel.send(players[0], "BungeeCord", byteArray.toByteArray())
|
||||
this.bungee.for(players[0]).message(sender, message).send()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,21 +219,23 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
}
|
||||
|
||||
@Cmd({ servers: [`!${constants.ServerType.Bungee}`] })
|
||||
bmpm(sender: any, command: string, args: string[]) {
|
||||
if (!sender.isOp()) { return this.i18n(sender, 'main.command.no.permission') }
|
||||
gmspm(sender: any, command: string, args: string[]) {
|
||||
if (!sender.hasPermission('mspm.admin')) { return this.i18n(sender, 'main.command.no.permission') }
|
||||
if (!this.isBungeeCord) return this.logger.sender(sender, '§c当前服务器尚未检测到 BungeeCord 链接...')
|
||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit()
|
||||
this.bungeeCordForward(sender, { sender: sender.getName(), command, args })
|
||||
this.logger.sender(sender, `§6[§3BPM§6][§a${this.serverName}§6] §6命令 §b/mpm ${args.join?.(' ')} §a发布成功!`)
|
||||
}
|
||||
|
||||
@Cmd({ servers: [constants.ServerType.Bungee] })
|
||||
mpmanager(sender: any, command: string, args: string[]) {
|
||||
if (!sender.isOp()) { return this.i18n(sender, 'main.command.no.permission') }
|
||||
bungeemspm(sender: any, command: string, args: string[]) {
|
||||
if (!sender.hasPermission('mspm.admin')) { return this.i18n(sender, 'main.command.no.permission') }
|
||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit()
|
||||
}
|
||||
|
||||
@Cmd({ servers: [`!${constants.ServerType.Bungee}`] })
|
||||
mpm(sender: any, command: string, args: string[]) {
|
||||
if (!sender.isOp()) { return this.i18n(sender, 'main.command.no.permission') }
|
||||
mspm(sender: any, command: string, args: string[]) {
|
||||
if (!sender.hasPermission('mspm.admin')) { return this.i18n(sender, 'main.command.no.permission') }
|
||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit()
|
||||
}
|
||||
|
||||
@@ -208,6 +258,12 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
this.logger.sender(sender, help)
|
||||
}
|
||||
|
||||
cmdinfo(sender: any) {
|
||||
this.logger.sender(sender, [
|
||||
|
||||
])
|
||||
}
|
||||
|
||||
cmdload(sender: any, name: string) {
|
||||
let pluginFile = fs.concat(__dirname + '', name)
|
||||
if (!fs.exists(pluginFile)) {
|
||||
@@ -237,7 +293,10 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
|
||||
return
|
||||
}
|
||||
this.download(sender, name)
|
||||
this.download(sender, name, false, () => {
|
||||
let plugin = this.pluginManager.loadFromFile(fs.concat(root, this.pluginFolder, name + '.js'))
|
||||
this.i18n(sender, 'install.finish', { name, version: plugin.description.version })
|
||||
})
|
||||
}
|
||||
|
||||
cmdupdate(sender: any, name: string) {
|
||||
@@ -253,29 +312,46 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
if (!confirm) { return this.i18n(sender, 'upgrade.confirm') }
|
||||
let enginePath = fs.path(fs.file(root, 'node_modules'))
|
||||
if (enginePath.startsWith(root)) {
|
||||
base.delete(enginePath)
|
||||
this.cmdrestart(sender)
|
||||
try {
|
||||
base.delete(enginePath)
|
||||
this.cmdrestart(sender)
|
||||
} catch (ex) {
|
||||
if (global.debug) {
|
||||
console.ex(ex)
|
||||
}
|
||||
if (fs.exists(enginePath)) {
|
||||
this.i18n(sender, 'upgrade.failed')
|
||||
fs.create(fs.file(root, 'upgrade'))
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (this.checkPlugin(sender, name)) {
|
||||
this.update(sender, name)
|
||||
this.pluginManager.reload(name)
|
||||
this.update(sender, name, () => this.reload(sender, name))
|
||||
}
|
||||
}
|
||||
|
||||
cmdunload(sender: any, name: string) {
|
||||
if (this.checkPlugin(sender, name)) {
|
||||
this.pluginManager.disable(name)
|
||||
this.i18n(sender, 'plugin.unload.finish', { name })
|
||||
let plugin = this.pluginManager.getPlugins().get(name)
|
||||
this.i18n(sender, 'plugin.unload.start', { name, version: plugin.description.version })
|
||||
this.pluginManager.disable(plugin)
|
||||
this.i18n(sender, 'plugin.unload.finish', { name, version: plugin.description.version })
|
||||
}
|
||||
}
|
||||
|
||||
cmdreload(sender: any, name: string) {
|
||||
name = name || this.description.name
|
||||
this.reload(sender, name)
|
||||
}
|
||||
|
||||
private reload(sender: any, name: string) {
|
||||
if (this.checkPlugin(sender, name)) {
|
||||
this.pluginManager.reload(name)
|
||||
this.i18n(sender, 'plugin.reload.finish', { name })
|
||||
let plugin = this.pluginManager.getPlugins().get(name)
|
||||
this.i18n(sender, 'plugin.reload.start', { name, version: plugin.description.version })
|
||||
this.pluginManager.reload(plugin)
|
||||
this.i18n(sender, 'plugin.reload.finish', { name, version: this.pluginManager.getPlugins().get(name).description.version })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,14 +388,27 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||
try {
|
||||
let script = args.join(' ')
|
||||
this.i18n(sender, 'run.script', { script })
|
||||
let result = this.runCode(script, sender)
|
||||
let result = this.runCode(script, sender, this)
|
||||
this.i18n(sender, 'run.result', { result: result == undefined ? this.translate.translate('run.noresult') : result + '' })
|
||||
} catch (ex) {
|
||||
this.logger.sender(sender, this.logger.stack(ex))
|
||||
}
|
||||
}
|
||||
|
||||
private runCode(code: string, sender: any) {
|
||||
cmdprun(sender: any, name: string, ...args: any[]) {
|
||||
try {
|
||||
if (!this.pluginManager.getPlugins().has(name)) { return this.logger.sender(sender, `§4插件 §c${name} §4不存在!`) }
|
||||
let script = args.join(' ')
|
||||
this.i18n(sender, 'prun.script', { name })
|
||||
this.i18n(sender, 'run.script', { script })
|
||||
let result = this.runCode(script, sender, this.pluginManager.getPlugins().get(name))
|
||||
this.i18n(sender, 'run.result', { result: result == undefined ? this.translate.translate('run.noresult') : result + '' })
|
||||
} catch (ex) {
|
||||
this.logger.sender(sender, this.logger.stack(ex))
|
||||
}
|
||||
}
|
||||
|
||||
private runCode(code: string, sender: any, _this: any) {
|
||||
let paramNames = [
|
||||
'sender',
|
||||
'reflect',
|
||||
@@ -340,8 +429,8 @@ if (this.serverType == "spring") {
|
||||
var db = dbm.getMainDatabase()
|
||||
var df = base.getInstance().getAutowireCapableBeanFactory()
|
||||
}
|
||||
return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
||||
return tfunc.apply(this, params) + ''
|
||||
return ''+ eval(${JSON.stringify(code)});`)
|
||||
return tfunc.apply(_this, params) + ''
|
||||
}
|
||||
|
||||
cmddeploy(sender: any, name: any) {
|
||||
@@ -355,20 +444,23 @@ return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
||||
version: plugin.description.version,
|
||||
source: base.read((plugin.description.source || plugin.description.loadMetadata.file).toString())
|
||||
})
|
||||
this.i18n(sender, result.code == 200 ? 'deploy.success' : 'deploy.fail', { name, msg: result.msg })
|
||||
this.i18n(sender, result.code == 200 ? 'deploy.success' : 'deploy.fail', { name, version: plugin.description.version, msg: result.msg })
|
||||
}
|
||||
}).async().submit()
|
||||
}
|
||||
|
||||
update(sender: any, name: string) {
|
||||
private update(sender: any, name: string, callback?: () => void) {
|
||||
if (this.checkCloudPlugin(sender, name)) {
|
||||
this.download(sender, name, true)
|
||||
this.download(sender, name, true, () => {
|
||||
this.i18n(sender, 'update.finish', { name, version: this.packageCache[name].version })
|
||||
callback?.()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@Tab()
|
||||
tabmpm(sender: any, command: any, args: string | any[]) {
|
||||
if (args.length === 1) { return ['list', 'install', 'update', 'upgrade', 'reload', 'restart', 'run', 'help', 'create', 'deploy'] }
|
||||
@Tab({ alias: ['gmspm', 'bungeemspm'] })
|
||||
tabmspm(_sender: any, _command: any, args: string | any[]) {
|
||||
if (args.length === 1) { return ['list', 'install', 'update', 'upgrade', 'reload', 'restart', 'run', 'prun', 'help', 'create', 'deploy'] }
|
||||
if (args.length > 1) {
|
||||
switch (args[0]) {
|
||||
case "list":
|
||||
@@ -379,6 +471,9 @@ return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
||||
if (args.length == 2) return ["system", ...this.pluginManager.getPlugins().keys()]
|
||||
if (args.length == 3 && args[1] == "system") return ["confirm"]
|
||||
return []
|
||||
case "prun":
|
||||
if (args.length == 2) return [...this.pluginManager.getPlugins().keys()]
|
||||
return []
|
||||
case "update":
|
||||
case "load":
|
||||
case "unload":
|
||||
@@ -405,19 +500,15 @@ return '§a返回结果: §r'+ eval(${JSON.stringify(code)});`)
|
||||
}).async().submit()
|
||||
}
|
||||
|
||||
download(sender: any, name: string, update: boolean = false) {
|
||||
download(sender: any, name: string, update: boolean, callback?: () => void) {
|
||||
this.taskManager.create(() => {
|
||||
this.i18n(sender, 'download.start', { name })
|
||||
this.i18n(sender, 'download.url', { url: this.packageCache[name].url })
|
||||
let pluginPkg = this.packageCache[name]
|
||||
this.i18n(sender, 'download.start', { name, version: pluginPkg.version })
|
||||
this.i18n(sender, 'download.url', { url: pluginPkg.url })
|
||||
let pluginFile = update ? fs.concat(root, this.pluginFolder, 'update', name + '.js') : fs.concat(root, this.pluginFolder, name + '.js')
|
||||
http.download(this.packageCache[name].url, pluginFile)
|
||||
this.i18n(sender, 'download.finish', { name })
|
||||
if (!update) {
|
||||
this.pluginManager.loadFromFile(fs.concat(root, this.pluginFolder, name + '.js'))
|
||||
this.i18n(sender, 'install.finish', { name })
|
||||
} else {
|
||||
this.i18n(sender, 'update.finish', { name })
|
||||
}
|
||||
http.download(pluginPkg.url, pluginFile)
|
||||
this.i18n(sender, 'download.finish', { name, version: pluginPkg.version })
|
||||
callback?.()
|
||||
}).async().submit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/sponge",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -22,11 +22,11 @@
|
||||
"@javatypes/sponge-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/common": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/common": "^0.9.4",
|
||||
"@ccms/container": "^0.9.4"
|
||||
}
|
||||
}
|
||||
|
||||
22
packages/sponge/src/chat.ts
Normal file
22
packages/sponge/src/chat.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { chat } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
|
||||
const Sponge = org.spongepowered.api.Sponge
|
||||
const ChatTypes = org.spongepowered.api.text.chat.ChatTypes
|
||||
const TextSerializers = org.spongepowered.api.text.serializer.TextSerializers
|
||||
|
||||
@provideSingleton(chat.Chat)
|
||||
export class SpongeChat extends chat.Chat {
|
||||
sendJson(sender: any, json: string | object) {
|
||||
sender.sendMessage(TextSerializers.JSON.deserialize(typeof json === "string" ? json : JSON.stringify(json)))
|
||||
}
|
||||
sendMessage(sender: any, message: string) {
|
||||
sender.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(message))
|
||||
}
|
||||
sendActionBar(sender: any, message: string) {
|
||||
sender.sendMessage(ChatTypes.ACTION_BAR, TextSerializers.FORMATTING_CODE.deserialize(message))
|
||||
}
|
||||
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
||||
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
|
||||
}
|
||||
}
|
||||
@@ -49,11 +49,11 @@ class SimpleCommandCallable {
|
||||
this.callable = new CommandCallable({
|
||||
//CommandResult process(CommandSource source, String arguments) throws CommandException
|
||||
process: (sender: any, args) => {
|
||||
return this.executor(sender, '', command, Java.to(args.split(" ").filter(e => e))) ? CommandResult.success() : CommandResult.empty()
|
||||
return this.executor(sender, '', command, Java.to(args.split(" "))) ? CommandResult.success() : CommandResult.empty()
|
||||
},
|
||||
//List<String> getSuggestions(CommandSource source, String arguments, @Nullable Location<World> targetPosition) throws CommandException
|
||||
getSuggestions: (sender: any, args, target) => {
|
||||
return this.tabCompleter(sender, '', command, Java.to(args.split(" ").filter(e => e)))
|
||||
return this.tabCompleter(sender, '', command, Java.to(args.split(" ")))
|
||||
},
|
||||
//boolean testPermission(CommandSource source)
|
||||
testPermission: () => {
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
import { server } from '@ccms/api'
|
||||
import { Container } from '@ccms/container'
|
||||
|
||||
import { SpongeConsole } from './console';
|
||||
import './event';
|
||||
import './server';
|
||||
import './command';
|
||||
import './channel';
|
||||
import './task';
|
||||
import { SpongeConsole } from './console'
|
||||
import './chat'
|
||||
import './task'
|
||||
import './event'
|
||||
import './server'
|
||||
import './command'
|
||||
import './channel'
|
||||
|
||||
export default function SpongeImpl(container: Container) {
|
||||
container.bind(server.Console).toConstantValue(SpongeConsole);
|
||||
container.bind(server.Console).toConstantValue(SpongeConsole)
|
||||
}
|
||||
|
||||
@@ -35,10 +35,10 @@ export class SpongeServer extends server.ReflectServer {
|
||||
if (typeof sender === 'string') {
|
||||
sender = this.getPlayer(sender)
|
||||
}
|
||||
return Sponge.getCommandManager().process(sender, command).getQueryResult().get() != 0
|
||||
return Sponge.getCommandManager().process(sender, command).getSuccessCount().get() != 0
|
||||
}
|
||||
dispatchConsoleCommand(command: string): boolean {
|
||||
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getQueryResult().get() != 0
|
||||
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getSuccessCount().get() != 0
|
||||
}
|
||||
getPluginsFolder(): string {
|
||||
return this.pluginsFolder
|
||||
@@ -55,10 +55,4 @@ export class SpongeServer extends server.ReflectServer {
|
||||
getRootLogger() {
|
||||
return this.rootLogger
|
||||
}
|
||||
sendJson(sender: string | any, json: string): void {
|
||||
if (typeof sender === "string") {
|
||||
sender = this.getPlayer(sender)
|
||||
}
|
||||
sender.sendMessage(TextSerializers.JSON.deserialize(json))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ const Callable = Java.type('java.util.concurrent.Callable')
|
||||
const TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class SpongeTaskManager implements task.TaskManager {
|
||||
export class SpongeTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
private syncExecutor: any
|
||||
@@ -18,21 +18,20 @@ export class SpongeTaskManager implements task.TaskManager {
|
||||
this.syncExecutor = Sponge.getScheduler().createSyncExecutor(this.pluginInstance)
|
||||
}
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') }
|
||||
create0(func: Function): task.Task {
|
||||
return new SpongeTask(this.pluginInstance, func)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
// @ts-ignore
|
||||
return this.syncExecutor.schedule(new Callable({ call: () => func() }), java.lang.Long.valueOf(0), TimeUnit.NANOSECONDS).get()
|
||||
}
|
||||
disable() {
|
||||
disable0() {
|
||||
Sponge.getScheduler().getScheduledTasks(this.pluginInstance).forEach((task: task.Cancelable) => task.cancel())
|
||||
}
|
||||
}
|
||||
|
||||
export class SpongeTask extends task.Task {
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
submit0(...args: any[]): task.Cancelable {
|
||||
let run = Task.builder().execute(new Consumer({ accept: () => this.run(...args) }))
|
||||
if (this.isAsync) { run.async() }
|
||||
if (this.laterTime) { run.delayTicks(this.laterTime) }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/spring",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript spring package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -21,12 +21,12 @@
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/common": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2",
|
||||
"@ccms/database": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/common": "^0.9.4",
|
||||
"@ccms/container": "^0.9.4",
|
||||
"@ccms/database": "^0.9.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@ export class SpringCommand extends command.Command {
|
||||
protected create(plugin: any, command: string) {
|
||||
return this.commandMap.register(plugin, command)
|
||||
}
|
||||
public tabComplete(sender: any, input: string, index?: number): string[] {
|
||||
return this.commandMap.tabComplate(sender, input, index)
|
||||
}
|
||||
protected remove(plugin: any, command: string) {
|
||||
this.commandMap.unregister(plugin, command)
|
||||
}
|
||||
|
||||
@@ -20,10 +20,11 @@ export default function SpringImpl(container: Container) {
|
||||
}
|
||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
container.bind(server.Console).toConstantValue(SpringConsole)
|
||||
container.bind(ioc.Autowired).toDynamicValue((ctx) => {
|
||||
container.rebind(ioc.Autowired).toDynamicValue((ctx) => {
|
||||
var metadata: any = reduceMetadata(ctx)
|
||||
if (toString.call(metadata.named) === "[object Symbol]") { return container.get(metadata.named) }
|
||||
if (toString.call(metadata.named) === '[object jdk.internal.dynalink.beans.StaticClass]') { metadata.named = metadata.named.class }
|
||||
let key = toString.call(metadata.named)
|
||||
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
|
||||
if (key === '[object jdk.internal.dynalink.beans.StaticClass]') { metadata.named = metadata.named.class }
|
||||
return beanFactory.getBean(metadata.named)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { server } from '@ccms/api'
|
||||
import { provideSingleton, inject } from '@ccms/container'
|
||||
import { NativePluginManager } from '@ccms/api/dist/interfaces/server/native_plugin'
|
||||
import { NativePluginManager } from '@ccms/api'
|
||||
import { CommandMap } from './internal/command'
|
||||
|
||||
@provideSingleton(server.Server)
|
||||
@@ -8,8 +8,6 @@ export class SpringServer implements server.Server {
|
||||
@inject(CommandMap)
|
||||
private commandMap: CommandMap
|
||||
|
||||
constructor() {
|
||||
}
|
||||
getVersion(): string {
|
||||
return "SpringFramework"
|
||||
}
|
||||
@@ -47,10 +45,4 @@ export class SpringServer implements server.Server {
|
||||
getRootLogger() {
|
||||
return Packages.org.slf4j.LoggerFactory.getLogger("root") || global.logger
|
||||
}
|
||||
sendJson(sender: any, json: string | object): void {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
tabComplete(sender: any, input: string, index?: number) {
|
||||
return this.commandMap.tabComplate(sender, input, index)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,44 +6,57 @@ const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
const AtomicBoolean = Java.type("java.util.concurrent.atomic.AtomicBoolean")
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
|
||||
const taskId = new AtomicInteger(0)
|
||||
const tasks: { [key: number]: task.Cancelable } = {}
|
||||
const executor = thread_pool.create({
|
||||
groupName: '@ccms/spring'
|
||||
})
|
||||
|
||||
@provideSingleton(task.TaskManager)
|
||||
export class SpringTaskManager implements task.TaskManager {
|
||||
export class SpringTaskManager extends task.TaskManager {
|
||||
@inject(plugin.PluginInstance)
|
||||
private pluginInstance: any
|
||||
|
||||
private innerTaskId: any
|
||||
private innerTasks: { [s: string]: task.Cancelable }
|
||||
private innerExecutor: java.util.concurrent.ThreadPoolExecutor
|
||||
private taskId: any
|
||||
private tasks: { [s: string]: task.Cancelable }
|
||||
private executor: java.util.concurrent.ThreadPoolExecutor
|
||||
|
||||
constructor() {
|
||||
this.innerTaskId = taskId
|
||||
this.innerTasks = tasks
|
||||
this.innerExecutor = executor
|
||||
super()
|
||||
this.taskId = new AtomicInteger(0)
|
||||
this.tasks = {}
|
||||
this.executor = thread_pool.create({
|
||||
groupName: '@ccms/spring'
|
||||
})
|
||||
}
|
||||
|
||||
create(func: Function): task.Task {
|
||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') }
|
||||
return new SpringTask(this.pluginInstance, func)
|
||||
create0(func: Function): task.Task {
|
||||
return new SpringTask(this.pluginInstance, func, this)
|
||||
}
|
||||
callSyncMethod(func: Function): any {
|
||||
return func()
|
||||
}
|
||||
disable() {
|
||||
Object.values(this.innerTasks).forEach((task) => task?.cancel())
|
||||
this.innerExecutor.shutdown()
|
||||
disable0() {
|
||||
Object.values(this.tasks).forEach((task) => task?.cancel())
|
||||
this.executor.shutdown()
|
||||
}
|
||||
nextId() {
|
||||
return this.taskId.incrementAndGet()
|
||||
}
|
||||
submit(id: number, task: SpringTask, func: Function) {
|
||||
this.tasks[id] = task
|
||||
this.executor.execute(func as any)
|
||||
}
|
||||
cancel(id: number) {
|
||||
delete this.tasks[id]
|
||||
}
|
||||
}
|
||||
|
||||
export class SpringTask extends task.Task {
|
||||
public id = taskId.incrementAndGet()
|
||||
private id: number
|
||||
private taskManager: SpringTaskManager
|
||||
private running = new AtomicBoolean(true)
|
||||
|
||||
constructor(plugin: any, func: Function, taskManager: SpringTaskManager) {
|
||||
super(plugin, func)
|
||||
this.id = taskManager.nextId()
|
||||
this.taskManager = taskManager
|
||||
}
|
||||
|
||||
run(...args: any[]) {
|
||||
if (this.laterTime > 0) {
|
||||
try {
|
||||
@@ -70,19 +83,18 @@ export class SpringTask extends task.Task {
|
||||
this.cancel()
|
||||
}
|
||||
|
||||
cancel(): any {
|
||||
cancel0(): any {
|
||||
var wasRunning = this.running.getAndSet(false)
|
||||
if (wasRunning) {
|
||||
delete tasks[this.id]
|
||||
this.taskManager.cancel(this.id)
|
||||
}
|
||||
}
|
||||
|
||||
submit(...args: any[]): task.Cancelable {
|
||||
tasks[this.id] = this
|
||||
executor.execute((() => this.run(...args)) as any)
|
||||
submit0(...args: any[]) {
|
||||
this.taskManager.submit(this.id, this, () => this.run(...args))
|
||||
return {
|
||||
cancel: () => {
|
||||
return this.cancel()
|
||||
return this.cancel0()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/web",
|
||||
"version": "0.9.2",
|
||||
"version": "0.9.5",
|
||||
"description": "MiaoScript web package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -26,10 +26,10 @@
|
||||
"@javatypes/tomcat": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.9.2",
|
||||
"@ccms/container": "^0.9.2"
|
||||
"@ccms/api": "^0.9.5",
|
||||
"@ccms/container": "^0.9.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ccms/websocket",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.4",
|
||||
"description": "MiaoScript websocket package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
@@ -19,10 +19,10 @@
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.9.0",
|
||||
"@ccms/nashorn": "^0.9.4",
|
||||
"@javatypes/tomcat-websocket-api": "^0.0.2",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^3.9.6"
|
||||
"typescript": "^4.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user