kulmapaikka-ircbot/plugins/pluginManager.js

98 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

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())
2018-04-29 17:37:07 +03:00
}
})
}
loadAllPlugins () {
var that = this
this.enabledPlugins.forEach(function (pluginName) {
var Plugin = require('./' + pluginName + '.js')
2018-04-29 17:37:07 +03:00
var plugin = new Plugin(that.config)
that.plugins.push(plugin)
})
2018-04-29 17:37:07 +03:00
this.enabledPmPlugins.forEach(function (pluginName) {
var Plugin = require('./pm' + pluginName + '.js')
2018-04-29 17:37:07 +03:00
var plugin = new Plugin(that.config)
that.pmPlugins.push(plugin)
})
}
2019-11-20 20:49:21 +02:00
async validateResult (resultPromise) {
let results = await resultPromise
2019-11-20 20:28:11 +02:00
2019-11-20 20:49:21 +02:00
let promises = []
if (!Array.isArray(results)) {
results = [results]
}
2019-11-20 20:28:11 +02:00
2019-11-20 20:49:21 +02:00
results.forEach((result) => {
let to = 'channel'
let message = result
if (typeof result === 'object' && typeof result.to !== 'undefined') {
to = result.to
message = result.message
}
2019-11-20 20:28:11 +02:00
2019-11-20 20:49:21 +02:00
promises.push(new Promise((resolve) => resolve({ to, message })))
2019-11-20 20:28:11 +02:00
})
2019-11-20 20:49:21 +02:00
return promises
2019-11-20 20:28:11 +02:00
}
2019-11-20 20:49:21 +02:00
async testPlugins (input, publicChat) {
2018-04-29 17:37:07 +03:00
if (typeof publicChat === 'undefined') {
publicChat = true
}
var promises = []
2018-04-29 17:37:07 +03:00
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')
2019-11-20 20:49:21 +02:00
promises = [...promises, ...await this.validateResult(plugin.result(input))]
2018-04-29 17:37:07 +03:00
}
}
} 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')
2019-11-20 20:49:21 +02:00
promises = [...promises, ...await this.validateResult(plugin.result(input))]
2018-04-29 17:37:07 +03:00
}
}
}
2018-04-29 17:37:07 +03:00
return Promise.all(promises)
}
}
// export default BasePlugin;
module.exports = PluginManager