diff --git a/app/components/Broadcast.js b/app/components/Broadcast.js index 215c478..3c263eb 100644 --- a/app/components/Broadcast.js +++ b/app/components/Broadcast.js @@ -1,7 +1,7 @@ const store = require('../store'); const events = require('../events'); -function Broadcast(event, data) { +function Broadcast(event, data, collection) { const connections = Object.values(store.activeConnections); if (!Object.values(events).includes(event)) return console.log('Invalid event:', event); @@ -9,9 +9,14 @@ function Broadcast(event, data) { connections.forEach(({ connection, id }) => { if (!connection) return; - connection.send(JSON.stringify({ event, data })); + connection.send(JSON.stringify({ event, data, collection }), (error) => { + if (!error) return; - console.log('Broadcasted event: ', id, event); + // If connection no longer exists delete it. + delete connections[id]; + }); + + console.log('Broadcasted event: ', [id], event); }); return Object.keys(store.activeConnections); diff --git a/app/components/Connect.js b/app/components/Connect.js index a6a8497..ca8e493 100644 --- a/app/components/Connect.js +++ b/app/components/Connect.js @@ -2,27 +2,39 @@ const store = require('../store'); const events = require('../events'); const Broadcast = require('./Broadcast'); -function Connect(connection, { protocol }) { +function Connect(connection, req) { + const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; + + // const location = url.parse(req.url, true); + // You might use location.query.access_token to authenticate or share sessions + // or req.headers.cookie (see http://stackoverflow.com/a/16395220/151312) + const id = store.globalCounter; store.activeConnections[id] = { connection, id }; // Connected. - connection.sendUTF(JSON.stringify({ event: events.CONNECT })); + connection.send(JSON.stringify({ event: events.CONNECT })); store.globalCounter += 1; connection.on('message', (message) => { - if (message.type !== 'utf8') return; - - // Only broadcast preview messages. - if (protocol !== 'preview-protocol') return; - - Broadcast(events.COLLECTIONS_PREVIEW); + let data; + try { + data = JSON.parse(message); + } catch (error) { + return; + } + + Broadcast(data.event, data.entry); }); - connection.on('close', (reasonCode, description) => { - console.log(`${new Date()} Peer ${connection.remoteAddress} disconnected. ${description}`); + connection.on('error', (error) => { + console.log(`${new Date()} Peer ${ip} disconnected. ${error}`); + delete store.activeConnections[connection.id]; + }); + connection.on('close', (error) => { + console.log(`${new Date()} Peer ${ip} disconnected. ${error}`); delete store.activeConnections[connection.id]; }); } diff --git a/app/webServer.js b/app/webServer.js index 9b4452c..0f013b2 100644 --- a/app/webServer.js +++ b/app/webServer.js @@ -14,9 +14,9 @@ function webServer() { app.use(bodyParser.json()); app.post('/update', (req, res) => { - const { body: { event, args } } = req.body; + const { body: { event, args } } = req; - Broadcast(event, args); + Broadcast(event, args[1], args[0]); res.send('ok'); }); diff --git a/app/webSocketServer.js b/app/webSocketServer.js index 5a8a7b5..142d460 100644 --- a/app/webSocketServer.js +++ b/app/webSocketServer.js @@ -1,35 +1,11 @@ -const WebSocketServer = require('websocket').server; -const WebSocketRouter = require('websocket').router; +const WebSocket = require('ws'); const Connect = require('./components/Connect'); -const originIsAllowed = origin => true || origin; +function webSocketServer(server) { + const wss = new WebSocket.Server({ server }); -function webSocketServer(httpServer) { - const wsServer = new WebSocketServer({ - httpServer, - // You should not use autoAcceptConnections for production - // applications, as it defeats all standard cross-origin protection - // facilities built into the protocol and the browser. You should - // *always* verify the connection's origin and decide whether or not - // to accept it. - autoAcceptConnections: false, - }); - - // Ws Router. - const router = new WebSocketRouter(); - - router.attachServer(wsServer); - - // Accepts all protocols. - router.mount('*', '*', (request) => { - if (!originIsAllowed(request.origin)) { - request.reject(); - return; - } - - const connection = request.accept(request.origin); - - Connect(connection, request); + wss.on('connection', (connection, req) => { + Connect(connection, req); }); } diff --git a/package-lock.json b/package-lock.json index adff71b..b5dd7ba 100644 --- a/package-lock.json +++ b/package-lock.json @@ -193,6 +193,11 @@ "integrity": "sha1-GdOGodntxufByF04iu28xW0zYC0=", "dev": true }, + "async-limiter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==" + }, "axobject-query": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-0.1.0.tgz", @@ -2558,11 +2563,6 @@ "integrity": "sha1-PMWfAAJRlLarLjjbrmaJJWtmBXI=", "dev": true }, - "is-typedarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" - }, "isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", @@ -2949,7 +2949,9 @@ "nan": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/nan/-/nan-2.7.0.tgz", - "integrity": "sha1-2Vv3IeyHfgjbJ27T/G63j5CDrUY=" + "integrity": "sha1-2Vv3IeyHfgjbJ27T/G63j5CDrUY=", + "dev": true, + "optional": true }, "natural-compare": { "version": "1.4.0", @@ -3897,20 +3899,17 @@ "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", "dev": true }, - "typedarray-to-buffer": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.2.tgz", - "integrity": "sha1-EBezLZhP9VbroQD1AViauhrOLgQ=", - "requires": { - "is-typedarray": "1.0.0" - } - }, "ua-parser-js": { "version": "0.7.17", "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.17.tgz", "integrity": "sha512-uRdSdu1oA1rncCQL7sCj8vSyZkgtL7faaw9Tc9rZ3mGgraQ7+Pdx7w5mnOSF3gw9ZNG6oc+KXfkon3bKuROm0g==", "dev": true }, + "ultron": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ultron/-/ultron-1.1.1.tgz", + "integrity": "sha512-UIEXBNeYmKptWH6z8ZnqTeS8fV74zG0/eRU9VGkpzz+LIJNs8W/zM/L+7ctCkRrgbNnnR0xxw4bKOr0cW0N0Og==" + }, "undefsafe": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-0.0.3.tgz", @@ -3988,17 +3987,6 @@ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" }, - "websocket": { - "version": "1.0.24", - "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.24.tgz", - "integrity": "sha1-dJA+dfJUW2suHeFCW8HJBZF6GJA=", - "requires": { - "debug": "2.6.9", - "nan": "2.7.0", - "typedarray-to-buffer": "3.1.2", - "yaeti": "0.0.6" - } - }, "whatwg-fetch": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.3.tgz", @@ -4091,17 +4079,29 @@ "signal-exit": "3.0.2" } }, + "ws": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-3.3.3.tgz", + "integrity": "sha512-nnWLa/NwZSt4KQJu51MYlCcSQ5g7INpOrOMt4XV8j4dqTXdmlUmSHQ8/oLC069ckre0fRsgfvsKwbTdtKLCDkA==", + "requires": { + "async-limiter": "1.0.0", + "safe-buffer": "5.1.1", + "ultron": "1.1.1" + }, + "dependencies": { + "safe-buffer": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" + } + } + }, "xdg-basedir": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-3.0.0.tgz", "integrity": "sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ=", "dev": true }, - "yaeti": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz", - "integrity": "sha1-8m9ITXJoTPQr7ft2lwqhYI+/lXc=" - }, "yallist": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", diff --git a/package.json b/package.json index f4c6732..c5b42a0 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "fetch": "^1.1.0", "isomorphic-fetch": "^2.2.1", "node-fetch": "^2.0.0-alpha.9", - "websocket": "^1.0.24" + "ws": "^3.3.3" }, "devDependencies": { "eslint": "^4.11.0",