slack-command-server/app.js

82 lines
2.1 KiB
JavaScript
Raw Normal View History

2014-08-09 06:21:11 +00:00
var connect = require('connect'),
SlackIncoming = require('slack-command-router'),
path = require('path'),
2014-08-09 06:40:38 +00:00
fs = require('fs'),
_ = require('lodash');
2014-08-09 06:21:11 +00:00
2014-08-09 06:40:38 +00:00
var config = JSON.parse(fs.readFileSync("config.json"));
var requiredSetup = ["port"];
if (_.intersection(_.keys(config), requiredSetup).length !== requiredSetup.length) {
throw {
message: "Missing required configuration parameters"
}
}
var slack = new SlackIncoming();
2014-08-09 06:21:11 +00:00
var pluginsToInstall = config.plugins || [],
pluginsToLoad = config["local-plugins"] || [];
function installPlugins(callback) {
2014-08-09 23:03:19 +00:00
var pluginNames = _.keys(pluginsToInstall);
if (pluginNames.length === 0) {
2014-08-09 06:21:11 +00:00
callback([]);
return;
}
var npm = require('npm');
npm.load({}, function (err) {
if (err) throw err;
2014-08-09 23:03:19 +00:00
npm.commands["install"](pluginNames, function (err) {
2014-08-09 06:21:11 +00:00
if (err) throw err;
var loadedPlugins = [];
2014-08-09 23:03:19 +00:00
_.forEach(pluginNames, function(name) {
//Load and configure each plugin
loadedPlugins.push(require(name)(pluginsToInstall[name]));
});
2014-08-09 06:21:11 +00:00
callback(loadedPlugins);
});
});
}
function loadPlugins(callback) {
2014-08-09 23:03:19 +00:00
var pluginNames = _.keys(pluginsToLoad);
if (pluginNames.length === 0) {
callback([]);
return;
2014-08-09 06:21:11 +00:00
}
2014-08-09 23:03:19 +00:00
var loadedPlugins = [];
_.forEach(pluginNames, function(path) {
//Load and configure each plugin
loadedPlugins.push(require(path.resolve(__dirname, path))(pluginsToLoad[path]));
});
2014-08-09 06:21:11 +00:00
callback(loadedPlugins);
}
function initPlugins(plugins, callback) {
for (var i = 0; i < plugins.length; i++) {
slack.registerHandler(plugins[i]);
}
callback();
}
function initCallback(callback) {
return function (loadedPlugins) {
initPlugins(loadedPlugins, callback);
}
}
function startApp() {
var app = connect();
app.use(slack.getMiddleware());
app.use(function (req, res) {
res.writeHead(400);
res.end("Unable to handle request");
});
2014-08-09 06:40:38 +00:00
app.listen(config.port);
2014-08-09 06:21:11 +00:00
}
installPlugins(initCallback(function() {
loadPlugins(initCallback(startApp));
}));