98 lines
2.6 KiB
JavaScript
98 lines
2.6 KiB
JavaScript
var fs = require('fs')
|
|
var Promise = require('promise')
|
|
const logger = require('../logger')
|
|
class PluginManager {
|
|
constructor (config) {
|
|
this.enabledPlugins = []
|
|
this.enabledPmPlugins = []
|
|
this.plugins = []
|
|
this.pmPlugins = []
|
|
this.config = config
|
|
|
|
var that = this
|
|
|
|
config.plugins.forEach(function (pluginName) {
|
|
logger.info('checking ' + pluginName + '...')
|
|
|
|
if (fs.existsSync('./plugins/' + pluginName.toLowerCase() + '.js')) {
|
|
logger.info('* Exists. Enabling...')
|
|
that.enabledPlugins.push(pluginName.toLowerCase())
|
|
}
|
|
if (fs.existsSync('./plugins/pm' + pluginName.toLowerCase() + '.js')) {
|
|
logger.info('* Exists as PM plugin. Enabling...')
|
|
that.enabledPmPlugins.push(pluginName.toLowerCase())
|
|
}
|
|
})
|
|
}
|
|
|
|
loadAllPlugins () {
|
|
var that = this
|
|
this.enabledPlugins.forEach(function (pluginName) {
|
|
var Plugin = require('./' + pluginName + '.js')
|
|
|
|
var plugin = new Plugin(that.config)
|
|
that.plugins.push(plugin)
|
|
})
|
|
|
|
this.enabledPmPlugins.forEach(function (pluginName) {
|
|
var Plugin = require('./pm' + pluginName + '.js')
|
|
|
|
var plugin = new Plugin(that.config)
|
|
that.pmPlugins.push(plugin)
|
|
})
|
|
}
|
|
|
|
async validateResult (resultPromise) {
|
|
let results = await resultPromise
|
|
|
|
let promises = []
|
|
if (!Array.isArray(results)) {
|
|
results = [results]
|
|
}
|
|
|
|
results.forEach((result) => {
|
|
let to = 'channel'
|
|
let message = result
|
|
if (typeof result === 'object' && typeof result.to !== 'undefined') {
|
|
to = result.to
|
|
message = result.message
|
|
}
|
|
|
|
promises.push(new Promise((resolve) => resolve({ to, message })))
|
|
})
|
|
return promises
|
|
}
|
|
|
|
async testPlugins (input, publicChat) {
|
|
if (typeof publicChat === 'undefined') {
|
|
publicChat = true
|
|
}
|
|
|
|
var promises = []
|
|
|
|
if (publicChat) {
|
|
for (let i = 0; i < this.plugins.length; i++) {
|
|
let plugin = this.plugins[i]
|
|
if (plugin.test(input)) {
|
|
logger.info('* Plugin ' + plugin.name + ' reported hit')
|
|
promises = [...promises, ...await this.validateResult(plugin.result(input))]
|
|
}
|
|
}
|
|
} else {
|
|
for (let i = 0; i < this.pmPlugins.length; i++) {
|
|
let plugin = this.pmPlugins[i]
|
|
|
|
if (plugin.test(input)) {
|
|
logger.info('* Plugin ' + plugin.name + ' reported hit')
|
|
promises = [...promises, ...await this.validateResult(plugin.result(input))]
|
|
}
|
|
}
|
|
}
|
|
|
|
return Promise.all(promises)
|
|
}
|
|
}
|
|
|
|
// export default BasePlugin;
|
|
module.exports = PluginManager
|