main.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const outputApi = require("./outputs.js");
  2. require('process').chdir(__dirname);
  3. function notFound(res) {
  4. res.statusCode = 404;
  5. res.statusMessage = "Not Found";
  6. res.end(res.statusMessage);
  7. }
  8. function getMime(filename) {
  9. const suffix = (/(.*\.)[^.]+/).exec(filename),
  10. ext = filename.substr(suffix ? suffix[1].length : 0),
  11. mime = require("mime");
  12. if (!mime)
  13. return null;
  14. return mime.getType(ext);
  15. }
  16. function serveFile(url, res) {
  17. const filename = "./public/" +(url || "index.html").replace('/\//g', '');
  18. require("fs").readFile(filename, (err, data) => {
  19. if (err) {
  20. notFound(res);
  21. } else {
  22. const type = getMime(filename);
  23. if (type)
  24. res.setHeader("Content-Type", type);
  25. res.end(data);
  26. }
  27. });
  28. }
  29. function serveApi(method, url, res) {
  30. var urlParts = url.split('?', 2),
  31. args = (urlParts[1] || "").split('&'),
  32. argObj = {};
  33. url = urlParts[0];
  34. args.forEach(i => {
  35. var argSplited = i.split("=", 2);
  36. argObj[argSplited[0]] = argSplited[1] || true;
  37. });
  38. switch (url) {
  39. case "outputs":
  40. res.end(JSON.stringify(outputApi.listOutputs()));
  41. break;
  42. case "setState":
  43. if (argObj.output === undefined || argObj.input === undefined || argObj.state === undefined) {
  44. notFound(res);
  45. } else {
  46. outputApi.setOutputState(argObj.output, argObj.input, argObj.state == 1);
  47. res.end(JSON.stringify(outputApi.listOutputs()));
  48. }
  49. break;
  50. case "setVol":
  51. if (argObj.output === undefined || argObj.volume === undefined) {
  52. notFound(res);
  53. } else {
  54. outputApi.setOutputVolume(argObj.output, argObj.volume);
  55. //FIXME wait for completion
  56. res.end(JSON.stringify(outputApi.listOutputs()));
  57. }
  58. break;
  59. default:
  60. notFound(res);
  61. break;
  62. }
  63. }
  64. function onRequest(req, res) {
  65. const url = req.url.split("/").filter(i => i.length);
  66. if (req.method == "GET" && url[0] !== "api")
  67. serveFile(url[0], res);
  68. else if (url[0] === "api")
  69. serveApi(req.method, url.splice(1).join("/"), res);
  70. else
  71. notFound(res);
  72. }
  73. const srv = require('http').createServer(onRequest);
  74. srv.on("clientError", (err, sock) => sock.end("HTTP/1.1 400 Bad Request\r\n\r\n"));
  75. srv.listen(require('./config.js').HTTP_PORT);
  76. require("./alsaOutput.js").init();
  77. require("./remoteOutput.js").init();