var mime = require('mime-types'), path = require('path'), fs = require('fs'); var log = require('hlogger').createLogger('hci-http-test'); function loadControllers() { var targetPath = __dirname + "/controllers"; var files = fs.readdirSync(targetPath); var ret = {} for(var f of files) { if(!f.endsWith(".js")) continue; var filePath = path.join(targetPath, f); var controllerName = path.basename(f,".js"); ret[controllerName] = require(filePath); }; return ret; } function bundleStart(context) { var controllers = loadControllers(); context.on('hci-http:stop',() => { console.log("Stopping http monitor"); context.stop(); }); var channel = context.prefix('hci-http:req'); channel.on('/monitor/api/(.*)',(req,res,e)=> { var [conName,conMethod = 'index',...params] = e.match[1].split(/\//); var con = controllers[conName]; if(con == undefined || con[conMethod] == undefined) { res.statusCode = 404; return; } var to = setTimeout(function() { res.writeHead(408); res.end("Controller timeout"); },5000); function cb(conRet) { clearTimeout(to); res.end(JSON.stringify(conRet)); } con[conMethod](context,cb,...params); // Setting a timeout would be good }); // Static server for path / monitor channel.on('/monitor/?(.*)',(req,res,e) => { if(e.count != 0) { // Something else executed return; } // Not executed // var reqroute = e.match[1]; if(reqroute.length == 0) { reqroute = "index.html"; } var filePath = path.join(__dirname, "/web"); var fullPath = path.join(filePath, reqroute); if( fullPath.indexOf(filePath) != 0 ) { res.writeHead(400,"Permission denied"); res.end("Permission denied"); return; } if(!fs.existsSync(fullPath)) { res.statusCode = 404; return; } // MimeTypes?? var mimeType = mime.lookup(fullPath); res.writeHead(200,{'Content-type':mimeType}); var s = fs.createReadStream(fullPath); s.pipe(res); }); } module.exports.bundleStart = bundleStart;