Last active
June 19, 2017 13:50
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
// parameters to be modified | |
var TOKEN='XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'; // Your own secret token | |
var MACADDR='XX:XX:XX:XX:XX:XX'; // MAC address of your recorder | |
var IP='192.168.0.1'; // local IP address of your recorder | |
var PUBLIC_HOST='xxx.ddns.net'; // Your public domain name | |
var POST_URL='https://connect.codyltech.com/connectors/webhook/push/XXXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXX'; | |
var PORT=9004; // PORT for webhook | |
var PORT_PROXY=9005; // PORT for proxy | |
var DEBUG=true; // set true for console.log | |
// | |
var command='/usr/sbin/etherwake -i eth0 -b -D ' + MACADDR; | |
var express = require('express'); | |
var bodyParser = require('body-parser'); | |
var exec = require('child_process').exec; | |
var app = express(); | |
app.set('port', process.env.PORT || PORT); | |
app.use(bodyParser.json()); | |
app.post('/wake', function (req, res) { | |
var wake_event = req.body; | |
DEBUG && console.log('incoming event:' + JSON.stringify(wake_event)); | |
if (!wake_event.token || | |
wake_event.token != TOKEN) { | |
DEBUG && console.log('invalid token'); | |
res.send('invalid token'); | |
return; | |
} | |
var child = exec(command,function(error, stdout, stderr){ | |
DEBUG && console.log('exec command:' + command); | |
DEBUG && console.log(stdout); | |
res.send('OK'); | |
wait_wakeup(function() { | |
post_webhook(); | |
}); | |
}); | |
}); | |
var server = app.listen(app.get('port'), function() { | |
DEBUG && console.log('Listening on port %d', server.address().port); | |
}); | |
// reverse proxy | |
var httpProxy = require('http-proxy'); | |
httpProxy.createServer({target: "http://" + IP + "/"}) | |
.listen(PORT_PROXY) | |
.on('error', function(err, req, res) { | |
res.writeHead(500, { | |
'Content-Type': 'text/plain' | |
}); | |
res.end("Proxy error"); | |
}) | |
// wait wakeup recorder | |
function wait_wakeup (done) { | |
// just wait 10 sec | |
setTimeout(function() { | |
DEBUG && console.log("wait_wakeup done"); | |
done(); | |
}, 10000); | |
} | |
function post_webhook () { | |
const https = require('https'); | |
const url = require('url'); | |
var urlobj = url.parse(POST_URL); | |
var postData = { | |
"url": "http://" + PUBLIC_HOST + ":" + PORT_PROXY, | |
}; | |
var postDataStr = JSON.stringify(postData); | |
var options = { | |
host: urlobj.host, | |
path: urlobj.path, | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
} | |
}; | |
var req = https.request(options, (res) => { | |
}); | |
req.write(postDataStr); | |
req.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment