2021-10-01 18:00:03 +00:00
|
|
|
import { ISqueebotCore, logger } from '@squeebot/core/lib/core';
|
|
|
|
import {
|
|
|
|
Plugin,
|
|
|
|
EventListener,
|
|
|
|
} from '@squeebot/core/lib/plugin';
|
|
|
|
|
|
|
|
class XProtocolPlugin extends Plugin {
|
|
|
|
private core: ISqueebotCore | null = null;
|
|
|
|
|
|
|
|
@EventListener('pluginUnload')
|
|
|
|
public unloadEventHandler(plugin: string | Plugin): void {
|
|
|
|
if (plugin === this.name || plugin === this) {
|
|
|
|
this.core = null;
|
|
|
|
this.emit('pluginUnloaded', this);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public async sendTo(target: string, ...data: any[]): Promise<boolean> {
|
|
|
|
if (!this.core) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find target plugin
|
|
|
|
const rxSplit = target.split('/');
|
|
|
|
const plugin = this.core.pluginManager.getLoadedByName(rxSplit[0]);
|
|
|
|
if (!plugin || !plugin.service) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find target protocol
|
|
|
|
const protocol = plugin.service.getProtocolByName(rxSplit[1]);
|
|
|
|
if (!protocol || !protocol.running) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return protocol.sendTo(target, ...data);
|
|
|
|
}
|
|
|
|
|
|
|
|
initialize(): void {
|
|
|
|
this.on('core', (core: ISqueebotCore) => {
|
|
|
|
this.core = core;
|
|
|
|
});
|
|
|
|
|
|
|
|
this.emitTo('core', 'request-core', this.name);
|
|
|
|
|
|
|
|
this.on('send', (data: any[]) => {
|
|
|
|
const target = data[0];
|
|
|
|
this.sendTo(target, ...data.slice(1)).catch((error: Error) => {
|
2021-12-15 16:33:13 +00:00
|
|
|
logger.error('[xprotocol] Sending to protocol from event failed:', error.message ?? error);
|
2021-10-01 18:00:03 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = XProtocolPlugin;
|