// requirements
const path = require('path');
const config = require('../config');
const packageJSON = require('../package.json');
const logger = require('./logger');
const blinkstick = require('./blinkstick');
// third party requirements
const express = require('express');
const favicon = require('serve-favicon')
const parser = require('body-parser');
// setup express, blinkstick and other stuff
const app = express();
app.use(favicon(path.join(path.dirname(__dirname), "public", "favicon.ico")));
app.use(parser.json());
app.use(parser.urlencoded({ extended: true }));
// get the html content for get requests
// TODO: replace with template engine (vue.js)
function getHTML() {
let welcomeMessage =
"" +
"
" +
"" + packageJSON.name + " " + packageJSON.version + "" +
"" +
"" +
"" +
"" +
"
" + packageJSON.name + " " + packageJSON.version + "
" +
"" +
"
";
welcomeMessage +=
"" +
"
get:
" +
"
" + config.api.get.description + "
" +
"
";
welcomeMessage +=
"" +
"
post:
" +
"
" +
"argument | " +
"available values | " +
"default | " +
"description | ";
Object.keys(config.api.post).forEach(function (argument) {
welcomeMessage +=
"" +
"" + argument + " | " +
"" + config.api.post[argument].available + " | " +
"" + config.api.post[argument].default + " | " +
"" + config.api.post[argument].description + " | " +
"
";
});
welcomeMessage +=
"
" +
"
" +
"" +
""
return welcomeMessage;
}
// run the express http server and handle gets/posts
function start() {
return new Promise(function (resolve, reject) {
app.listen(config.server.port, config.server.listen)
.on("listening", function () {
return resolve("server listening on " + config.server.listen + ":" + config.server.port + "...")
})
.on("error", function (err) {
return reject("error starting server (" + err + ")");
});
});
}
function handleRequests() {
// GET methods
app.get('*', function (request, response) {
logger.logRequest(request);
response.send(getHTML());
response.end();
});
// POST methods
app.post('*', function (request, response) {
logger.logRequest(request);
response.end();
blinkstick.illuminate(parseRequest(request.body))
.then(logger.info)
.catch(logger.error);
return;
});
}
// parse the request and return an object with sane defaults
function parseRequest(data) {
let blinkstickConfig = {
"id": Math.random(),
"mode": data["mode"] || config.api.post.mode.default,
"color": blinkstick.parseColor(data["color"]),
"options": {
"duration": data["duration"] || config.api.post.duration.default,
"pulse": {
"max": data["pulses"] || 0,
"done": 0
}
}
};
blinkstickConfig.options.steps = blinkstickConfig.options.duration / 10;
if (blinkstickConfig.options.duration < 100) {
blinkstickConfig.options.duration = 100;
}
return blinkstickConfig;
}
// exports
module.exports = {
start,
handleRequests
};