main.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 serveFile(url, res) {
  9. require("fs").readFile("./public/" +(url || "index.html").replace('/\//g', ''), (err, data) => {
  10. if (err)
  11. notFound(res);
  12. else
  13. res.end(data);
  14. });
  15. }
  16. function serveApi(method, url, res) {
  17. var urlParts = url.split('?', 2),
  18. args = (urlParts[1] || "").split('&'),
  19. argObj = {};
  20. url = urlParts[0];
  21. args.forEach(i => {
  22. var argSplited = i.split("=", 2);
  23. argObj[argSplited[0]] = argSplited[1] || true;
  24. });
  25. switch (url) {
  26. case "outputs":
  27. res.end(JSON.stringify(outputApi.listOutputs()));
  28. break;
  29. case "setState":
  30. if (argObj.output === undefined || argObj.input === undefined || argObj.state === undefined) {
  31. notFound(res);
  32. } else {
  33. outputApi.setOutputState(argObj.output, argObj.input, argObj.state == 1);
  34. res.end(JSON.stringify(outputApi.listOutputs()));
  35. }
  36. break;
  37. case "setVol":
  38. if (argObj.output === undefined || argObj.volume === undefined) {
  39. notFound(res);
  40. } else {
  41. outputApi.setOutputVolume(argObj.output, argObj.volume);
  42. //FIXME wait for completion
  43. res.end(JSON.stringify(outputApi.listOutputs()));
  44. }
  45. break;
  46. default:
  47. notFound(res);
  48. break;
  49. }
  50. }
  51. function onRequest(req, res) {
  52. const url = req.url.split("/").filter(i => i.length);
  53. if (req.method == "GET" && url[0] !== "api")
  54. serveFile(url[0], res);
  55. else if (url[0] === "api")
  56. serveApi(req.method, url.splice(1).join("/"), res);
  57. else
  58. notFound(res);
  59. }
  60. const srv = require('http').createServer(onRequest);
  61. srv.on("clientError", (err, sock) => sock.end("HTTP/1.1 400 Bad Request\r\n\r\n"));
  62. srv.listen(require('./config.js').HTTP_PORT);
  63. require("./alsaOutput.js").init();
  64. require("./remoteOutput.js").init();