2016-12-22 04:54:22 +00:00
|
|
|
const path = require('path');
|
|
|
|
const express = require('express');
|
|
|
|
const bodyParser = require('body-parser');
|
2016-12-30 07:22:12 +00:00
|
|
|
const moment = require('moment');
|
2016-12-22 04:54:22 +00:00
|
|
|
|
|
|
|
const app = express();
|
|
|
|
|
2016-12-27 05:50:48 +00:00
|
|
|
const host = 'http://127.0.0.1';
|
2016-12-22 04:54:22 +00:00
|
|
|
const port = 3000;
|
|
|
|
|
|
|
|
app.use(bodyParser.urlencoded({ extended: false }));
|
|
|
|
|
2016-12-30 07:22:12 +00:00
|
|
|
function log(message) {
|
|
|
|
console.log(moment().format() + ': ' + message);
|
|
|
|
}
|
|
|
|
|
2016-12-28 08:50:58 +00:00
|
|
|
app.use('/', express.static(path.join(__dirname, 'public')));
|
2016-12-23 00:40:05 +00:00
|
|
|
app.get('/*', (req, res) => {
|
2016-12-28 08:50:58 +00:00
|
|
|
res.sendFile(path.join(__dirname, 'public/index.html'));
|
2016-12-22 04:54:22 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
app.post('*', (req, res) => {
|
2017-01-09 23:58:42 +00:00
|
|
|
let id = req.path.substring(1, 20); // Ignore first, truncate after 20
|
2016-12-24 22:27:38 +00:00
|
|
|
let data = Object.keys(req.body)[0];
|
2016-12-23 00:40:05 +00:00
|
|
|
|
2016-12-24 22:27:38 +00:00
|
|
|
if (data && data.substring(0,2) === 'd:') {
|
2017-01-09 23:58:42 +00:00
|
|
|
if (io.sockets.adapter.rooms[id]) {
|
|
|
|
let message = data.substring(2);
|
2016-12-23 00:40:05 +00:00
|
|
|
|
2017-01-09 23:58:42 +00:00
|
|
|
log('[NOTICA] Message sent to ' + id + ': ' + message);
|
2016-12-23 00:40:05 +00:00
|
|
|
|
2017-01-09 23:58:42 +00:00
|
|
|
io.in(id).emit('message', message);
|
2016-12-24 22:27:38 +00:00
|
|
|
|
2017-01-09 23:58:42 +00:00
|
|
|
res.end();
|
|
|
|
} else {
|
|
|
|
log('No one in room to send data to: ' + id);
|
|
|
|
res.send('No devices have that Notica ID open. Please open this URL: https://notica.us/' + id + '\n');
|
|
|
|
}
|
2016-12-30 07:22:12 +00:00
|
|
|
} else {
|
|
|
|
log('Ignoring bad POST data to: ' + id);
|
2017-01-09 23:58:42 +00:00
|
|
|
res.send('Bad POST data. Expecting prefix of "d:".\n');
|
2016-12-24 22:27:38 +00:00
|
|
|
}
|
2016-12-23 00:40:05 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const server = app.listen(port, 'localhost', (err) => {
|
|
|
|
if (err) {
|
2016-12-30 07:22:12 +00:00
|
|
|
log('[ERROR] Server error: ' + err);
|
2016-12-23 00:40:05 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
console.info('==> Listening on port %s. Open up %s:%s/ in your browser.', port, host, port);
|
2016-12-22 04:54:22 +00:00
|
|
|
});
|
|
|
|
|
2016-12-23 00:40:05 +00:00
|
|
|
const io = require('socket.io').listen(server);
|
|
|
|
|
|
|
|
io.on('connection', (socket) => {
|
|
|
|
socket.on('room', (room) => {
|
2016-12-30 07:22:12 +00:00
|
|
|
log('New connection joining room: ' + room);
|
2016-12-23 00:40:05 +00:00
|
|
|
socket.join(room);
|
|
|
|
});
|
2016-12-22 00:59:10 +00:00
|
|
|
});
|