| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- const outputApi = require("./outputs.js");
- require('process').chdir(__dirname);
- function notFound(res) {
- res.statusCode = 404;
- res.statusMessage = "Not Found";
- res.end(res.statusMessage);
- }
- function getMime(filename) {
- const suffix = (/(.*\.)[^.]+/).exec(filename),
- ext = filename.substr(suffix ? suffix[1].length : 0),
- mime = require("mime");
- if (!mime)
- return null;
- return mime.getType(ext);
- }
- function serveFile(url, res) {
- const filename = "./public/" +(url || "index.html").replace('/\//g', '');
- require("fs").readFile(filename, (err, data) => {
- if (err) {
- notFound(res);
- } else {
- const type = getMime(filename);
- if (type)
- res.setHeader("Content-Type", type);
- res.end(data);
- }
- });
- }
- function serveApi(method, url, res) {
- var urlParts = url.split('?', 2),
- args = (urlParts[1] || "").split('&'),
- argObj = {};
- url = urlParts[0];
- args.forEach(i => {
- var argSplited = i.split("=", 2);
- argObj[argSplited[0]] = argSplited[1] || true;
- });
- switch (url) {
- case "outputs":
- res.end(JSON.stringify(outputApi.listOutputs()));
- break;
- case "setState":
- if (argObj.output === undefined || argObj.input === undefined || argObj.state === undefined) {
- notFound(res);
- } else {
- outputApi.setOutputState(argObj.output, argObj.input, argObj.state == 1);
- res.end(JSON.stringify(outputApi.listOutputs()));
- }
- break;
- case "setVol":
- if (argObj.output === undefined || argObj.volume === undefined) {
- notFound(res);
- } else {
- outputApi.setOutputVolume(argObj.output, argObj.volume);
- //FIXME wait for completion
- res.end(JSON.stringify(outputApi.listOutputs()));
- }
- break;
- default:
- notFound(res);
- break;
- }
- }
- function onRequest(req, res) {
- const url = req.url.split("/").filter(i => i.length);
- if (req.method == "GET" && url[0] !== "api")
- serveFile(url[0], res);
- else if (url[0] === "api")
- serveApi(req.method, url.splice(1).join("/"), res);
- else
- notFound(res);
- }
- const srv = require('http').createServer(onRequest);
- srv.on("clientError", (err, sock) => sock.end("HTTP/1.1 400 Bad Request\r\n\r\n"));
- srv.listen(require('./config.js').HTTP_PORT);
- require("./alsaOutput.js").init();
- require("./remoteOutput.js").init();
|