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.events .channel('core-http') .on('stop',()=> { console.log("Stopping http monitor"); context.stop(); }) .channel('request') .on('GET/monitor/api',(req,res,e) => { e.stop(); // Manual router var re = new RegExp("/monitor/api/(.*)"); var match = req.url.match(re); if(match != null) { api(match,req,res,e); return; } }).on('GET/monitor', (req,res,e) => { re = new RegExp("/monitor/?(.*)"); match = req.url.match(re); if(match!=null) { staticHandler(match,req,res,e); return; } res.statusCode = 404; }); //router?! function api(match,req,res,e) { var [conName,conMethod = 'index',...params] = 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 }; function staticHandler(match,req,res,e) { if(e.count != 0) { // Something else executed return; } // Not executed // var reqroute = 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;