2013-04-14 19:21:24 +02:00
|
|
|
/**
|
|
|
|
* Name: API
|
|
|
|
* Description: Expose DBot API functionality with a REST API
|
|
|
|
*/
|
|
|
|
var _ = require('underscore')._;
|
|
|
|
|
|
|
|
var api = function(dbot) {
|
2013-05-17 16:13:42 +02:00
|
|
|
this.onLoad = function() {
|
2013-05-17 16:15:15 +02:00
|
|
|
dbot.modules.web.app.get('/api', function(req, res) {
|
2013-05-17 15:29:28 +02:00
|
|
|
var externalApi = {};
|
|
|
|
_.each(dbot.api, function(moduleApi, moduleName) {
|
|
|
|
externalApi[moduleName] = {};
|
|
|
|
_.each(moduleApi, function(method, methodName) {
|
|
|
|
if(method.external == true) {
|
|
|
|
externalApi[moduleName][methodName] = method.extMap;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2013-05-17 16:15:59 +02:00
|
|
|
res.render('api/api', { 'name': dbot.config.name, 'api': externalApi });
|
2013-05-17 16:13:42 +02:00
|
|
|
});
|
2013-05-17 15:29:28 +02:00
|
|
|
|
2013-04-14 19:21:24 +02:00
|
|
|
dbot.modules.web.app.get('/api/:module/:method', function(req, res) {
|
|
|
|
var module = req.params.module,
|
|
|
|
method = req.params.method,
|
2013-04-14 20:14:59 +02:00
|
|
|
reqArgs = req.query,
|
2013-04-14 19:21:24 +02:00
|
|
|
body = { 'err': null, 'data': null };
|
|
|
|
|
|
|
|
if(!_.has(dbot.api, module)) {
|
|
|
|
body.err = 'No such API module';
|
|
|
|
} else if(!_.has(dbot.api[module], method)) {
|
|
|
|
body.err = 'No such API function in ' + module;
|
|
|
|
} else if(dbot.api[module][method].external !== true) {
|
|
|
|
body.err = 'API function ' + module + '.' + method +
|
|
|
|
' not enabled for external access';
|
|
|
|
}
|
|
|
|
|
|
|
|
if(!body.err) {
|
2013-04-14 20:14:59 +02:00
|
|
|
var func = dbot.api[module][method],
|
|
|
|
paramNames = func.extMap,
|
|
|
|
args = [];
|
2013-04-14 19:21:24 +02:00
|
|
|
|
2013-04-14 20:14:59 +02:00
|
|
|
_.each(reqArgs, function(arg, name) {
|
|
|
|
var callbackIndex = paramNames.indexOf(name);
|
|
|
|
if(callbackIndex != -1) {
|
|
|
|
args[callbackIndex] = decodeURIComponent(arg);
|
|
|
|
}
|
|
|
|
});
|
2013-04-14 19:21:24 +02:00
|
|
|
|
|
|
|
var callbackIndex = paramNames.indexOf('callback');
|
|
|
|
if(callbackIndex != -1) {
|
|
|
|
args[callbackIndex] = function() {
|
|
|
|
body.data = Array.prototype.slice.call(arguments, 0);
|
|
|
|
res.json(body);
|
|
|
|
};
|
|
|
|
func.apply(null, args);
|
|
|
|
} else {
|
2013-04-14 20:14:59 +02:00
|
|
|
body.data = func.apply(null, args);
|
2013-04-14 19:21:24 +02:00
|
|
|
res.json(body);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
res.json(body);
|
|
|
|
}
|
|
|
|
}.bind(this));
|
|
|
|
}.bind(this);
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.fetch = function(dbot) {
|
|
|
|
return new api(dbot);
|
|
|
|
};
|