index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. var mime = require('mime-types'),
  2. path = require('path'),
  3. fs = require('fs');
  4. var log = require('hlogger').createLogger('hci-http-test');
  5. function loadControllers() {
  6. var targetPath = __dirname + "/controllers";
  7. var files = fs.readdirSync(targetPath);
  8. var ret = {}
  9. for(var f of files) {
  10. if(!f.endsWith(".js")) continue;
  11. var filePath = path.join(targetPath, f);
  12. var controllerName = path.basename(f,".js");
  13. ret[controllerName] = require(filePath);
  14. };
  15. return ret;
  16. }
  17. function bundleStart(context) {
  18. var controllers = loadControllers();
  19. context.events
  20. .channel('core-http')
  21. .on('stop',()=> {
  22. console.log("Stopping http monitor");
  23. context.stop();
  24. })
  25. .channel('request')
  26. .on('GET/monitor/api',(req,res,e) => {
  27. e.stop();
  28. // Manual router
  29. var re = new RegExp("/monitor/api/(.*)");
  30. var match = req.url.match(re);
  31. if(match != null) {
  32. api(match,req,res,e);
  33. return;
  34. }
  35. }).on('GET/monitor', (req,res,e) => {
  36. re = new RegExp("/monitor/?(.*)");
  37. match = req.url.match(re);
  38. if(match!=null) {
  39. staticHandler(match,req,res,e);
  40. return;
  41. }
  42. res.statusCode = 404;
  43. });
  44. //router?!
  45. function api(match,req,res,e) {
  46. var [conName,conMethod = 'index',...params] = match[1].split(/\//);
  47. var con = controllers[conName];
  48. if(con == undefined || con[conMethod] == undefined) {
  49. res.statusCode = 404;
  50. return;
  51. }
  52. var to = setTimeout(function() {
  53. res.writeHead(408);
  54. res.end("Controller timeout");
  55. },5000);
  56. function cb(conRet) {
  57. clearTimeout(to);
  58. res.end(JSON.stringify(conRet));
  59. }
  60. con[conMethod](context,cb,...params);
  61. // Setting a timeout would be good
  62. };
  63. function staticHandler(match,req,res,e) {
  64. if(e.count != 0) { // Something else executed
  65. return;
  66. }
  67. // Not executed
  68. //
  69. var reqroute = match[1];
  70. if(reqroute.length == 0) {
  71. reqroute = "index.html";
  72. }
  73. var filePath = path.join(__dirname, "/web");
  74. var fullPath = path.join(filePath, reqroute);
  75. if( fullPath.indexOf(filePath) != 0 ) {
  76. res.writeHead(400,"Permission denied");
  77. res.end("Permission denied");
  78. return;
  79. }
  80. if(!fs.existsSync(fullPath)) {
  81. res.statusCode = 404;
  82. return;
  83. }
  84. // MimeTypes??
  85. var mimeType = mime.lookup(fullPath);
  86. res.writeHead(200,{'Content-type':mimeType});
  87. var s = fs.createReadStream(fullPath);
  88. s.pipe(res);
  89. };
  90. }
  91. module.exports.bundleStart = bundleStart;